Tutorials / Java: From Zero to Advanced / Strings, formatting and text blocks

Strings, formatting and text blocks

13 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Strings are objects

String is a class, not a primitive. A string literal is written between double quotes, and Java creates a String object for it. The most important property is that strings are immutable. Once created, a string never changes. Methods like toUpperCase return a new string and leave the original alone.

import java.util.List;

public class Main {

    public static void main(String[] args) {
        String raw = "  Java Is Fun  ";

        // Methods return new strings
        System.out.println(raw.trim());              // old way
        System.out.println(raw.strip().toLowerCase());
        System.out.println(raw.length());
        System.out.println(raw.isBlank());
        System.out.println("ab".repeat(3));

        String email = "sara.khan@example.com";
        int at = email.indexOf('@');
        System.out.println(email.substring(0, at));      // sara.khan
        System.out.println(email.substring(at + 1));     // example.com
        System.out.println(email.contains("example"));
        System.out.println(email.endsWith(".com"));
        System.out.println(email.replace(".", "_"));
        System.out.println(email.charAt(0));

        // Splitting and joining
        String[] parts = "red,green,blue".split(",");
        System.out.println(parts.length);
        System.out.println(String.join(" | ", parts));
        System.out.println(String.join("-", List.of("a", "b", "c")));

        // equals, not ==
        String a = "java";
        String b = new String("java");
        System.out.println(a == b);                  // false: different objects
        System.out.println(a.equals(b));             // true: same text
        System.out.println("JAVA".equalsIgnoreCase(a));

        // Building a string in a loop
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) sb.append(", ");
        }
        System.out.println(sb);
        System.out.println(sb.reverse());

        // Formatting
        String name = "Ayesha";
        double price = 1234.5;
        System.out.println(String.format("%s paid %,.2f rupees", name, price));
        System.out.println("%-8s|%6d|%8.1f".formatted("item", 42, 3.14159));

        // Text blocks (Java 15+)
        String json = """
                {
                  "name": "%s",
                  "active": true
                }
                """.formatted(name);
        System.out.print(json);
    }
}

Walking through it

The first block shows common methods. strip removes whitespace from both ends and understands all Unicode spaces, so prefer it over the older trim. isBlank is true for empty strings and strings made only of whitespace, which is a better check than isEmpty when you validate user input. repeat repeats a string.

The email example shows the standard way to take a string apart. indexOf returns the position of the first match, or -1 if there is none. substring(start, end) includes the start position and excludes the end. Positions start at zero. If the position is out of range, you get a StringIndexOutOfBoundsException, so check for -1 before you use the result.

split takes a regular expression, not just a plain character. That is fine for a comma, but for a character that has special meaning in regular expressions, such as a dot or a pipe, you must escape it: split("\\.").

equals versus ==

This is the first Java trap almost everyone falls into. For objects, == asks whether two variables point to the same object. equals asks whether they have the same content. In the example, new String("java") makes a separate object, so a == b is false although both hold the same text. Sometimes == on strings appears to work, because Java reuses identical literals, and that makes the bug hard to notice. Always compare strings with equals. If one side may be null, put the literal first, as in "yes".equals(answer), so that a null value does not cause an exception.

StringBuilder

Because strings are immutable, s = s + x in a loop creates a new string on every pass. For a few joins this is fine, and the compiler handles simple cases well. For loops with many iterations, use StringBuilder. You call append as often as you like, and toString at the end, which println does for you.

Formatting and text blocks

String.format and the instance method formatted use the same format codes as printf. %s is a string, %d a whole number, %f a decimal. Flags and widths refine them: %,.2f adds thousands separators and two decimals, %-8s pads a string to eight characters on the left side, %6d right-aligns a number in six characters. Be aware that decimal separators depend on the default locale of the machine. If you need a fixed output, pass Locale.ROOT or Locale.US as the first argument to String.format.

A text block starts and ends with three double quotes. The content begins on the line after the opening quotes. Java removes the common indentation, so you can indent the block to match your code and the output is not affected. You can use quotes inside without escaping them. Text blocks are ideal for JSON, SQL and HTML snippets.

Common mistakes

  • Using == to compare strings.
  • Ignoring the return value. name.toUpperCase(); on its own line does nothing useful.
  • Calling a method on null. A null string gives NullPointerException.
  • Concatenating inside big loops instead of using StringBuilder.
  • Splitting on a special character without escaping.

Try it yourself

  1. Write a method that checks whether a word is a palindrome, ignoring case.
  2. Given the string "2026-03-15", print the year, month and day separately.
  3. Print a three-row table of names and prices with aligned columns using printf.
  4. Write a small HTML snippet in a text block and print it.
java
import java.util.List;

public class Main {

    public static void main(String[] args) {
        String raw = "  Java Is Fun  ";

        // Methods return new strings
        System.out.println(raw.trim());              // old way
        System.out.println(raw.strip().toLowerCase());
        System.out.println(raw.length());
        System.out.println(raw.isBlank());
        System.out.println("ab".repeat(3));

        String email = "sara.khan@example.com";
        int at = email.indexOf('@');
        System.out.println(email.substring(0, at));      // sara.khan
        System.out.println(email.substring(at + 1));     // example.com
        System.out.println(email.contains("example"));
        System.out.println(email.endsWith(".com"));
        System.out.println(email.replace(".", "_"));
        System.out.println(email.charAt(0));

        // Splitting and joining
        String[] parts = "red,green,blue".split(",");
        System.out.println(parts.length);
        System.out.println(String.join(" | ", parts));
        System.out.println(String.join("-", List.of("a", "b", "c")));

        // equals, not ==
        String a = "java";
        String b = new String("java");
        System.out.println(a == b);                  // false: different objects
        System.out.println(a.equals(b));             // true: same text
        System.out.println("JAVA".equalsIgnoreCase(a));

        // Building a string in a loop
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) sb.append(", ");
        }
        System.out.println(sb);
        System.out.println(sb.reverse());

        // Formatting
        String name = "Ayesha";
        double price = 1234.5;
        System.out.println(String.format("%s paid %,.2f rupees", name, price));
        System.out.println("%-8s|%6d|%8.1f".formatted("item", 42, 3.14159));

        // Text blocks (Java 15+)
        String json = """
                {
                  "name": "%s",
                  "active": true
                }
                """.formatted(name);
        System.out.print(json);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account