Strings
java strings immutable string pool constant pool equals StringBuilder StringBuffer concat substring split trim interview
Introduction
In the previous lessons, you learned about variables, arrays, methods, and Object-Oriented Programming. One of the most frequently used data types in Java applications is the String.
Whether you're building a Spring Boot REST API, an e-commerce application, a banking system, or an Android app, you'll constantly work with strings to handle:
- User names
- Passwords
- Email addresses
- Product names
- URLs
- JSON/XML data
- Log messages
- SQL queries
Although a String looks like a primitive data type, it is actually an object of the String class.
Java Strings are immutable, meaning once a String object is created, its value cannot be changed.
Understanding how Strings work internally is one of the most commonly tested topics in Java interviews.
In this lesson, you'll learn:
- What is a String?
- String Creation
- String Pool
- String Immutability
- String Methods
- Comparing Strings
- String Concatenation
- Escape Characters
- StringBuilder vs StringBuffer
- String Performance
- Real-world Examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
What is a String?
A String is a sequence of Unicode characters.
Example:
String name = "Jagannath";
Unlike primitive data types, a String is an object.
Internally:
String name = new String("Jagannath");
The first syntax is preferred because it uses the String Pool efficiently.
Why Strings are Important
Almost every Java application processes text.
Examples:
- Customer Name
- Email Address
- Password
- Product Description
- Search Keywords
- File Names
- JSON Responses
- XML Documents
Without Strings, modern applications would not be possible.
Creating Strings
Using String Literal
String city = "Hyderabad";
Stored inside the String Constant Pool.
Using new Keyword
String city = new String("Hyderabad");
Creates a new object in heap memory regardless of whether the same value already exists.
String Constant Pool
The JVM maintains a special memory area called the String Constant Pool (SCP).
Example:
String s1 = "Java";String s2 = "Java";
Memory:
String Pool+--------+| Java |+--------+s1 ─┐├──► "Java"s2 ─┘
Only one object is created.
Now:
String s3 = new String("Java");
Memory:
Heaps3 ─► New Object↓String Pool"Java"
A new heap object is created in addition to the pooled literal.
String Immutability
Strings cannot be modified after creation.
Example:
String language = "Java";language.concat(" Programming");System.out.println(language);
Output:
Java
The original object remains unchanged because concat() returns a new String.
Correct:
language = language.concat(" Programming");
Output:
Java Programming
Why are Strings Immutable?
Immutability provides:
- Thread Safety
- Security
- Better Performance through String Pool
- Reliable Hash Codes
- Safe Class Loading
Examples:
- URLs
- File Paths
- Database Connections
- Usernames
- Class Names
If Strings were mutable, many security vulnerabilities could occur.
Comparing Strings
Using ==
String s1 = "Java";String s2 = "Java";System.out.println(s1 == s2);
Output:
true
Because both references point to the same pooled object.
Using equals()
String a = new String("Java");String b = new String("Java");System.out.println(a.equals(b));
Output:
true
equals() compares content, not object references.
Why == Can Be Misleading
String a = new String("Java");String b = new String("Java");System.out.println(a == b);
Output:
false
Because == compares memory references.
Rule:
==→ Reference Comparisonequals()→ Content Comparison
Common String Methods
length()
String text = "Java";System.out.println(text.length());
Output:
4
charAt()
String text = "Java";System.out.println(text.charAt(2));
Output:
v
substring()
String text = "Programming";System.out.println(text.substring(3,7));
Output:
gram
toUpperCase()
System.out.println("java".toUpperCase());
Output:
JAVA
toLowerCase()
System.out.println("JAVA".toLowerCase());
Output:
java
contains()
String email = "user@gmail.com";System.out.println(email.contains("@"));
Output:
true
startsWith()
String url = "https://example.com";System.out.println(url.startsWith("https"));
Output:
true
endsWith()
String file = "report.pdf";System.out.println(file.endsWith(".pdf"));
Output:
true
replace()
String sentence = "Java is fun";System.out.println(sentence.replace("fun","powerful"));
Output:
Java is powerful
split()
String csv = "Apple,Banana,Orange";String[] fruits = csv.split(",");
Output:
AppleBananaOrange
trim()
String name = " Java ";System.out.println(name.trim());
Output:
Java
Escape Characters
| Escape | Meaning |
|---|---|
\n | New Line |
\t | Tab |
\" | Double Quote |
\\ | Backslash |
Example:
System.out.println("Java\nProgramming");
Output:
JavaProgramming
String Concatenation
Using +
String first = "Hello";String second = "Java";System.out.println(first + " " + second);
Output:
Hello Java
StringBuilder
For multiple string modifications, use StringBuilder.
StringBuilder sb = new StringBuilder("Java");sb.append(" Programming");System.out.println(sb);
Output:
Java Programming
StringBuilder is mutable and faster than repeated String concatenation.
StringBuffer
StringBuffer sb = new StringBuffer("Java");sb.append(" Programming");
Difference:
| StringBuilder | StringBuffer |
|---|---|
| Faster | Slower |
| Not Thread-Safe | Thread-Safe |
| Preferred in Single Thread | Preferred in Multi Thread |
String vs StringBuilder vs StringBuffer
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-Safe | Yes (Immutable) | No | Yes |
| Performance | Slower for repeated modifications | Fastest | Slightly slower |
Real-World Example: Email Validation
String email = "user@gmail.com";if(email.contains("@") && email.endsWith(".com")){System.out.println("Valid Email");}
Real-World Example: Full Name
String firstName = "Jagannath";String lastName = "Mishra";String fullName = firstName + " " + lastName;System.out.println(fullName);
Best Practices
Use String Literals When Possible
Prefer:
String language = "Java";
Instead of:
String language = new String("Java");
Use equals() for Comparison
Never compare String contents using ==.
Use StringBuilder for Repeated Modifications
Avoid:
text = text + value;
Inside loops.
Check for Null Before Calling Methods
if(name != null){System.out.println(name.length());}
Avoid Hardcoded Strings
Store reusable constants in static final variables.
Common Mistakes
Using == Instead of equals()
This compares references instead of content.
Forgetting String Immutability
Methods like concat(), replace(), and trim() return a new String.
Excessive String Concatenation in Loops
Use StringBuilder for better performance.
Ignoring Case Sensitivity
Use equalsIgnoreCase() when appropriate.
Not Handling Null Values
Calling methods on a null String results in a NullPointerException.
Hands-on Exercise
Create a Java program that:
- Creates Strings using literals and the
newkeyword. - Demonstrates the String Constant Pool.
- Compares Strings using
==andequals(). - Uses at least ten commonly used String methods.
- Reads a full name and prints initials.
- Validates an email address.
- Reverses a String using
StringBuilder. - Counts the number of words in a sentence.
Summary
Strings are among the most widely used objects in Java. Their immutability provides security, thread safety, and efficient memory usage through the String Constant Pool. Understanding String creation, comparison, common methods, and performance considerations is essential for writing robust Java applications.
Key Takeaways
- A String is an immutable object.
- Prefer String literals to take advantage of the String Constant Pool.
- Use
equals()for content comparison. ==compares object references.- Common methods include
length(),substring(),contains(),replace(), andsplit(). StringBuilderis ideal for repeated modifications.StringBufferprovides thread-safe mutable strings.- String immutability improves security and performance.
Professional Interview Questions
1Why are Strings immutable in Java?
Professional Answer
Strings are immutable to ensure security, thread safety, efficient memory sharing through the String Constant Pool, and consistent hash codes. Immutability also prevents accidental modifications to critical values such as file paths, URLs, database connection strings, and class names.
Follow-up Questions
- How does immutability improve security?
- Which other Java classes are immutable?
Interview Tip: Mention both String Pool optimization and thread safety to demonstrate a deeper understanding.
2What is the difference between == and equals() for Strings?
Professional Answer
The == operator compares object references to determine whether two references point to the same object in memory. The equals() method compares the actual sequence of characters stored in the strings. In most business applications, equals() should be used for String comparison.
Follow-up Questions
- When can == return true for two Strings?
- What does equalsIgnoreCase() do?
Interview Tip: Remember: == → Memory Reference, equals() → Content Comparison.
3What is the difference between String, StringBuilder, and StringBuffer?
Professional Answer
String is immutable, making it safe and suitable for constant values. StringBuilder is mutable and offers better performance for repeated modifications in single-threaded applications. StringBuffer is also mutable but synchronizes its methods, making it thread-safe at the cost of some performance.
Follow-up Questions
- Why is StringBuilder faster than StringBuffer?
- When would you choose StringBuffer?
Interview Tip: String → Fixed text, StringBuilder → High-performance string manipulation, StringBuffer → Multi-threaded environments requiring thread safety.