String Handling in Java

    Atul Kabra3 min readUpdated

    A String in Java is an object that holds a sequence of characters — and crucially it is immutable: once created, its contents never change. Every method that seems to "modify" a String actually returns a new String. Java gives String rich built-in methods for searching, slicing, and transforming text, plus StringBuilder for efficient repeated edits. Understanding immutability and how to compare Strings correctly avoids the most common beginner bugs.

    Creating Strings

    String name = "Asha";              // string literal
    String city = new String("Jalgaon"); // explicit object (rarely needed)
    

    Prefer the literal form. Identical literals are shared from a pool, which saves memory.

    Immutability

    String s = "hello";
    s.toUpperCase();          // returns "HELLO" but does NOT change s
    System.out.println(s);    // still "hello"
    s = s.toUpperCase();      // reassign to keep the result
    System.out.println(s);    // "HELLO"
    

    Because Strings are immutable, you must capture the return value of any transforming method.

    Common String methods

    String text = "Infoplanet, Jalgaon";
    System.out.println(text.length());          // 19  number of characters
    System.out.println(text.charAt(0));         // 'I' character at index 0
    System.out.println(text.toLowerCase());     // "infoplanet, jalgaon"
    System.out.println(text.contains("plan"));  // true
    System.out.println(text.indexOf("Jalgaon")); // 12  start index, or -1 if absent
    System.out.println(text.substring(0, 10));  // "Infoplanet" (start inclusive, end exclusive)
    System.out.println(text.replace("Jalgaon", "Pune")); // "Infoplanet, Pune"
    System.out.println("  trim me  ".trim());   // "trim me" (or use strip())
    System.out.println(String.join("-", "a", "b", "c")); // "a-b-c"
    

    split turns text into an array; String.format builds formatted strings.

    String csv = "1,2,3";
    String[] parts = csv.split(","); // {"1", "2", "3"}
    String line = String.format("%s scored %d", "Asha", 72); // "Asha scored 72"
    

    Comparing Strings correctly

    This is the single most important rule: compare content with .equals(), not ==.

    String a = "yes";
    String b = new String("yes");
    System.out.println(a == b);        // false — different objects in memory
    System.out.println(a.equals(b));   // true  — same characters
    System.out.println(a.equalsIgnoreCase("YES")); // true
    

    == compares references (are they the same object?); .equals() compares the actual text. For beginner code, almost always use .equals().

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Building strings efficiently

    Because Strings are immutable, concatenating in a loop with + creates many throwaway objects. Use StringBuilder for repeated appends.

    // Inefficient in a big loop: each += makes a new String.
    // Efficient: StringBuilder mutates one buffer.
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= 5; i++) {
        sb.append(i).append(" ");
    }
    String result = sb.toString(); // "1 2 3 4 5 "
    System.out.println(result.strip());
    

    For a few concatenations, plain + is perfectly fine and readable.

    Text blocks (modern Java)

    For multi-line strings, a text block (triple quotes) is far cleaner than escaped newlines.

    String json = """
        {
          "name": "Asha",
          "city": "Jalgaon"
        }
        """;
    // Preserves line breaks; no \n clutter.
    

    Common mistakes

    • Using == to compare text. It checks object identity, not content. Use .equals().
    • Ignoring the return value. s.replace(...) does nothing visible unless you assign the result.
    • substring index confusion. The end index is exclusive: "hello".substring(1, 3) is "el".
    • Concatenating in big loops with +. Switch to StringBuilder for performance.
    • Calling methods on a null String. Check for null first, or initialise to "".

    FAQ

    Why are Strings immutable? It makes them safe to share, cache, and use as map keys without surprises, and it improves security and thread-safety.

    trim() or strip()? strip() (JDK 11+) is Unicode-aware and the modern choice; trim() only removes ASCII whitespace.

    Keep going

    Next, handle errors gracefully with Exception Handling in Java, or revisit Packages & Access Modifiers. All tutorials are on the Java hub; for guided practice in Jalgaon, see the Java course.


    Get fluent with Java text handling at Infoplanet, Jalgaon. Join the waitlist for the Java course.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides