Skip to content
Strings
step 1/7

Reading — step 1 of 7

Learn

~3 min readStrings

String is a class in Java, not a primitive. Strings are immutable — every operation that "modifies" a string returns a new one. The original is never changed. Master strings and you've got the most-used type in any Java program.

Creating strings

String s1 = "hello";                           // string literal
String s2 = new String("hello");                // explicit constructor (rare)
String s3 = String.valueOf(42);                  // "42" — convert other types

Use string literals 99% of the time. The new String() form creates a brand new object — almost never what you want.

⚠️ The classic pitfall: == vs .equals()

This trips up EVERY Java beginner:

String a = "hello";
String b = "hello";
String c = new String("hello");

a == b           // true (sometimes — string interning)
a == c           // false — different objects in memory!
a.equals(c)      // true — same content

Rule: ALWAYS use .equals() to compare String contents. == checks if they're the SAME OBJECT, not whether they have the same content.

For case-insensitive comparison: a.equalsIgnoreCase(b).

Common methods

String s = "Hello, World";

s.length();                    // 12
s.charAt(0);                   // 'H' — note char, not String
s.indexOf("World");            // 7  — or -1 if not found
s.contains("World");           // true
s.startsWith("Hello");         // true
s.endsWith("!");               // false
s.substring(7);                 // "World"
s.substring(0, 5);              // "Hello" — start inclusive, end exclusive
s.toUpperCase();                // "HELLO, WORLD"
s.toLowerCase();                // "hello, world"
s.trim();                       // strips whitespace from both ends
s.replace("World", "Java");    // "Hello, Java"
s.split(", ");                  // ["Hello", "World"]
String.join("-", "a", "b", "c");  // "a-b-c"

All return new strings (or new arrays). The original s never changes.

Concatenation

String a = "Hello";
String b = "World";
String c = a + ", " + b;        // "Hello, World"
String d = a.concat(", ").concat(b);   // same

The compiler converts + to StringBuilder calls internally — but ONLY for inline concatenation. Concatenating in a LOOP with += creates many garbage strings:

// SLOW — creates a new String every iteration:
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i;
}

// FAST — mutates one buffer:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i);
}
String result = sb.toString();

StringBuilder for heavy concatenation

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("World");
sb.append("!");
String result = sb.toString();    // "Hello, World!"

// Other useful methods:
sb.reverse();
sb.insert(0, ">>> ");
sb.delete(0, 4);
sb.replace(0, 5, "Hi");

Use StringBuilder whenever you build a string in a loop or across many steps. For thread-safe building, use StringBuffer (rarely needed in modern code).

Formatted strings

String name = "Alice";
int age = 30;

// String.format — printf-style:
String s = String.format("%s is %d years old", name, age);

// printf directly:
System.out.printf("%s is %d%n", name, age);     // %n is platform newline

// Java 15+ formatted strings:
String s2 = "%s is %d".formatted(name, age);

Iterating characters

for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    System.out.println(c);
}

// Or stream them:
s.chars().forEach(c -> System.out.println((char) c));

Common mistakes

  • Comparing with == — checks reference identity. Use .equals().
  • Using += in a loop — slow. Use StringBuilder.
  • .substring(start, end) thinking end is inclusive — it's exclusive.
  • Calling .equals() with possible null left sidenull.equals(...) crashes. Use Objects.equals(a, b) for null-safe comparison.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Strings — Java Fundamentals