Java · Chapter 10 of 42

Java Strings

A String in Java is an object representing a sequence of characters. Strings are immutable — once created, their content cannot change; operations like concatenation create new String objects.

The String class provides many useful methods like length(), charAt(), substring(), toUpperCase(), and equals() for comparing content.

Syntax
String s = "text";
s.length();
s.substring(0, 3);

Creating and using strings

Strings can be created with a literal ("text") or with `new String(...)`. Use + or concat() to join strings together.

Common String methods

length() returns character count, charAt(i) gets a character, substring() extracts part of a string, and equals() compares content (never use == for strings).

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    String name = "Java";
    System.out.println(name.length());
    System.out.println(name.toUpperCase());
    System.out.println(name.equals("Java"));
  }
}
Output
4
JAVA
true

length() returns 4 characters, toUpperCase() converts case, equals() compares content.

Key points

  • Strings are immutable objects.
  • Use equals() to compare string content, not ==.
  • length(), charAt(), substring() are common methods.
  • Concatenation with + creates a new String.
💡 Note: Using == on Strings compares references, not content, and is a classic Java interview trap.

📝 Quick Quiz

1. How should you compare String content?

2. Are Java Strings mutable?

3. Which method returns a string's character count?