Strings
A String in Java is:
- An immutable sequence of characters
- Stored in String Pool for memory optimization
- Represented internally as a
char[](Java 8) orbyte[]with coder (Java 9+)
Once created, a String cannot be modified.
Why String is Immutable?
- Security (used in URLs, DB connections, class loading)
- Thread safety
- Caching & String Pool optimization
- HashCode caching (important for HashMap)
String Pool
- String literals go to String Pool
new String("abc")creates object in heapintern()moves string to pool
String a = "java";
String b = "java"; // same reference
String c = new String("java"); // different reference
Common String Operations
๐น Length & Access
- length()
- charAt(int index)
- substring(int begin)
- substring(int begin, int end)
๐น Comparison
- equals()
- equalsIgnoreCase()
- compareTo()
- compareToIgnoreCase()
โ ๏ธ Never use == for content comparison.
๐น Searching
- contains()
- indexOf()
- lastIndexOf()
- startsWith()
- endsWith()
๐น Modification (Creates New String)
- toUpperCase()
- toLowerCase()
- trim()
- strip() // Java 11+
- stripLeading()
- stripTrailing()
- replace()
- replaceAll()
- replaceFirst()
๐น Splitting & Joining
- split()
- String.join()
Java 11+ String Enhancements (Very Important)
- isBlank() // checks whitespace only
- lines() // stream of lines
- repeat(int n)
- strip() // Unicode-aware trim
Example:
โ โ.isBlank(); // true
โab\ncdโ.lines();
Java 12+ / 15+ Updates (FYI)
-
Compact Strings (internal optimization)
-
Text Blocks (โโโ โโโ) โ not a String method, but related
String json = """
{
"name": "Java"
}
""";
Mutable Alternatives
๐น StringBuilder
- Mutable
- Faster
- Not thread-safe
๐น StringBuffer
- Mutable
- Thread-safe
- Slower
Use StringBuilder in almost all cases.