Java Tutorial · Java Basics · Lesson 10 of 37

Java Strings

Create strings, compare them, use common methods, text blocks and StringBuilder.

String basics

Strings are immutable objects. Methods return new strings:

Example 1
public class Main {
    public static void main(String[] args) {
        String s = "  Hello, Java  ";
        String t = s.strip();
        System.out.println(t.length());
        System.out.println(t.toUpperCase());
        System.out.println(t.charAt(0) + " " + t.indexOf("Java"));
        System.out.println(t.substring(7));
        System.out.println(t.replace("Java", "World"));
        System.out.println(t.contains("Java") + " " + t.startsWith("Hello"));
        System.out.println(String.join("-", "a", "b", "c"));
        System.out.println("a,b,,c".split(",").length);
        System.out.println("ha".repeat(3) + " " + "".isEmpty() + " " + "  ".isBlank());
    }
}

Output

11
HELLO, JAVA
H 7
Java
Hello, World
true true
a-b-c
4
hahaha true true

Run this on your computer — see “Get Started” for setup.

Comparing strings

Use equals() (or equalsIgnoreCase()), never ==, to compare contents:

Example 2
public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = new String("java");
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println("JAVA".equalsIgnoreCase(a));
        System.out.println("apple".compareTo("banana") < 0);
    }
}

Output

false
true
true
true

Run this on your computer — see “Get Started” for setup.

Text blocks (Java 15+)

Triple quotes create multi-line strings without escape noise — great for JSON, SQL and HTML:

Example 3
public class Main {
    public static void main(String[] args) {
        String json = """
            {
              "name": "Ada",
              "lang": "Java"
            }
            """;
        System.out.print(json);
    }
}

Output

{
  "name": "Ada",
  "lang": "Java"
}

Run this on your computer — see “Get Started” for setup.

StringBuilder

Building a string in a loop with + creates many temporary objects. StringBuilder is the efficient way:

Example 4
public class Main {
    public static void main(String[] args) {
        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(new StringBuilder("stressed").reverse());
    }
}

Output

1, 2, 3, 4, 5
desserts

Run this on your computer — see “Get Started” for setup.

Test yourself

How should you compare the contents of two strings in Java?

  1. a == b
  2. a.equals(b)
  3. a = b
  4. a.compare(b)
Show answer

Answer: a.equals(b)

Practice next