Java Strings
Work with String objects in Java — create, concatenate, and manipulate strings, and understand string immutability.
A String represents a sequence of characters and is, after int, the type you'll touch most. It's a class (not a primitive), but Java gives it special syntax — literals in double quotes, the + operator for concatenation — so it feels primitive-like to use. The most important fact about strings: they are immutable.
Creating a string
The easiest way is a string literal in double quotes:
String greeting = "Hello, World!";
String empty = "";
String multi = "Line 1\nLine 2"; // \n is a newlineYou can also construct one with new, though there's rarely a reason to:
String fromLiteral = "Hello";
String fromNew = new String("Hello");new String(...) always allocates a fresh object. Literals are pooled — two literals with the same characters are the same object. This matters for == comparisons but not much else; you should always use .equals() to compare contents anyway.
Strings are immutable
Once a String is created, its contents never change. Every method that "modifies" a string actually returns a new string:
String s = "hello";
s.toUpperCase();
System.out.println(s); // "hello" — unchanged
s = s.toUpperCase();
System.out.println(s); // "HELLO" — new string assignedImmutability has several benefits:
- Safe to share between threads — no synchronisation needed.
- Hash code can be cached.
- Strings can be safely used as map keys.
The trade-off: building a long string in a loop with + creates many intermediate strings. For that, use StringBuilder (String Concatenation).
Length and indexing
length() returns the number of characters:
String s = "hello";
System.out.println(s.length()); // 5charAt(i) returns the character at index i (zero-based):
System.out.println(s.charAt(0)); // 'h'
System.out.println(s.charAt(4)); // 'o'
// s.charAt(5); // StringIndexOutOfBoundsExceptionNote: length() is the number of UTF-16 code units, not always the number of user-perceived characters. For most ASCII and BMP text they're the same, but emoji and some non-Latin scripts use surrogate pairs and count as 2.
Comparing strings
Use .equals() for content equality, never ==:
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // trueequalsIgnoreCase ignores case:
"HELLO".equalsIgnoreCase("hello"); // trueFor ordering, use compareTo (returns negative/zero/positive):
"apple".compareTo("banana"); // negativeCommon operations
The most-used methods, with examples:
String s = " Hello, World! ";
s.length(); // 17
s.trim(); // "Hello, World!" (whitespace removed)
s.strip(); // "Hello, World!" (Unicode-aware, Java 11+)
s.toUpperCase(); // " HELLO, WORLD! "
s.toLowerCase(); // " hello, world! "
s.contains("World"); // true
s.startsWith(" Hello"); // true
s.endsWith("! "); // true
s.indexOf("World"); // 9
s.indexOf("xyz"); // -1
s.replace(",", ";"); // " Hello; World! "
s.substring(2, 7); // "Hello"
s.split(", "); // [" Hello", "World! "]
s.isEmpty(); // false — length() == 0?
s.isBlank(); // false — only whitespace? (Java 11+)For the full reference, see Java String Methods.
Concatenation
The + operator joins strings, and converts other types to string as needed:
String name = "Ada";
int age = 36;
String msg = "Name: " + name + ", Age: " + age;
// "Name: Ada, Age: 36"Inside a loop, prefer StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i).append(",");
}
String result = sb.toString();Text blocks — multi-line strings
Since Java 15, text blocks let you write multi-line strings without escapes:
String json = """
{
"name": "Ada",
"age": 36
}
""";The compiler strips the common leading whitespace from every line so your indentation in the source doesn't bleed into the string.
Formatting
String.format builds a string with printf-style placeholders:
String s = String.format("Name: %s, Age: %d", "Ada", 36);The placeholders are the same as System.out.printf — see Java Output.
A demonstration
What's next
Java String Methods — a reference of every method you'll regularly use.
Practice
Which statement about Java strings is correct?