iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Strings

Java String is immutable. Every operation that “changes” a string returns a new one. For lots of edits in a hot loop, use StringBuilder.

Real string operations

EXAMPLE
String name = "Ada";
String greeting = "Hello, " + name + "!";   // concatenation

// 1) Common ops
name.length();
name.charAt(0);
name.toUpperCase();
name.toLowerCase();
name.trim();                       // remove leading/trailing whitespace
name.strip();                      // Unicode-aware trim (Java 11+)
name.isBlank();                    // empty or only whitespace

// 2) Comparison — NEVER ==
name.equals("Ada");
name.equalsIgnoreCase("ada");
name.compareTo("Bo");              // negative, 0, or positive

// 3) Slicing + searching
name.substring(1);                 // "da"
name.substring(0, 2);              // "Ad"
name.indexOf("d");                 // 1
name.contains("da");
name.startsWith("A");
name.endsWith("a");

// 4) Replace + split
"a,b,c".split(",");                // ["a","b","c"]
"hello".replace('l', 'L');         // "heLLo"
"hello world".replaceAll("\\s+", "-");

// 5) Format / interpolation
String.format("Hello, %s — you scored %d", name, 92);
"%s scored %d".formatted(name, 92);   // Java 15+

// 6) Text blocks — multi-line literals
String json = """
    {
        \"name\": \"Ada\",
        \"age\":  36
    }
    """;

// 7) Hot-loop edits — StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i).append(',');
String out = sb.toString();

Why it matters

== on strings is a reference check — sometimes lies because of the string intern pool. .equals() always. Cement this on day one.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
String s = "Hello";
System.out.println(s.length());
System.out.println(s.toUpperCase());
System.out.println(s.replace('l', 'L'));
Try it Yourself »

Discussion

Loading…