</>
Skip to content
Java lessons (11/47)

Java — Strings

Creating strings

A String in Java is an object — not a primitive. You create one with double quotes:

String greeting = "Hello";
String empty = "";
String withSpace = "Hello World";

You can also use the constructor (rarely needed):

String constructed = new String("Hello");

The direct form is preferred — it's shorter and lets Java reuse the same string in memory.

String length

String name = "Ada";
System.out.println(name.length());  // 3

Unlike arrays where .length is a property, strings use .length() as a method. Forgetting the parentheses is a compile error.

Accessing characters

String word = "Hello";

System.out.println(word.charAt(0));   // H
System.out.println(word.charAt(4));   // o

Characters are zero-indexed — position 0 is the first character. Java throws a StringIndexOutOfBoundsException if you go past the end.

Finding substrings and positions

String sentence = "Java is fun and powerful";

System.out.println(sentence.indexOf("fun"));       // 9
System.out.println(sentence.indexOf("Python"));    // -1 (not found)
System.out.println(sentence.substring(9));          // fun and powerful
System.out.println(sentence.substring(9, 12));     // fun

indexOf returns the starting position (or -1). substring(start) takes everything from that position. substring(start, end) takes the slice between the two positions (end is exclusive).

Case conversion

String name = "Ada Lovelace";

System.out.println(name.toUpperCase());  // ADA LOVELACE
System.out.println(name.toLowerCase());  // ada lovelace

Both return new strings — the original stays unchanged. Strings are immutable in Java.

Trimming and replacing

String messy = "   Hello, World!   ";

System.out.println(messy.trim());                    // "Hello, World!"
System.out.println(messy.strip());                   // "Hello, World!" (Java 11+)
System.out.println("Hello".replace("l", "L"));      // HeLLo
System.out.println("aabbcc".replaceAll("a", "x"));  // xxbbcc

trim() removes leading and trailing whitespace. strip() is the modern version that also handles Unicode spaces.

Checking string content

String email = "user@example.com";

System.out.println(email.isEmpty());              // false
System.out.println(email.contains("@"));          // true
System.out.println(email.startsWith("user"));     // true
System.out.println(email.endsWith(".com"));        // true

These methods return booleans, making them perfect for conditions:

if (email.contains("@") && email.contains(".")) {
    System.out.println("Looks like an email.");
}

Comparing strings

Never use == to compare string content:

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

System.out.println(a == b);       // true (Java reused the same object)
System.out.println(a == c);       // false (different objects!)
System.out.println(a.equals(c));  // true  (same content)

== checks if two references point to the same object in memory. .equals() checks if the content is identical. Always use .equals() for string comparison.

For case-insensitive comparison:

String name = "Ada";
System.out.println(name.equalsIgnoreCase("ada"));  // true

Splitting and joining

String csv = "apple,banana,cherry";
String[] fruits = csv.split(",");
System.out.println(fruits.length);  // 3
System.out.println(fruits[1]);      // banana

String joined = String.join(" - ", fruits);
System.out.println(joined);  // apple - banana - cherry

split() breaks a string into an array using a delimiter. String.join() reassembles them with a new separator. These are essential for parsing data.

String concatenation

String first = "Hello";
String second = " World";
String result = first + second;
System.out.println(result);  // Hello World

For building strings in loops, StringBuilder is more efficient:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
    sb.append(i).append(" ");
}
System.out.println(sb.toString().trim());  // 0 1 2 3 4

Each + on strings creates a new String object. In a loop, that's wasteful. StringBuilder builds one string, modifying it internally until you call toString().

String formatting

String name = "Ada";
int age = 36;

// Concatenation
String v1 = "Name: " + name + ", Age: " + age;

// printf
String v2 = String.format("Name: %s, Age: %d", name, age);

// Both produce: Name: Ada, Age: 36

String.format() is the String equivalent of System.out.printf — it returns the formatted string instead of printing it. Use it when you need to store or pass formatted text.

Common string mistakes

// Mistake 1: comparing with ==
String a = new String("hello");
String b = new String("hello");
if (a == b) { /* this won't run! */ }

// Mistake 2: null check before methods
String s = null;
if (s.length() > 0) { }  // NullPointerException!

// Correct approach:
if (s != null && s.length() > 0) { }  // safe

NullPointerException on strings is the most common runtime error in Java. Always check for null before calling methods.

Mini Practice

  1. Create a string with your full name — print its length and each character
  2. Reverse a string: "Hello" → "olleH" using charAt() and a loop
  3. Check if a string is a palindrome (reads the same forwards and backwards)
  4. Split a sentence into words and print each word on a new line
  5. Build a story by concatenating strings from an array using a for loop

Next: making decisions with if-else →

Related Topics

Frequently Asked Questions about Strings

What is Strings in Java?

Strings is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in Java?

Strings is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.