Java Strings

A String in Java is an object that holds a sequence of characters, such as a word, a sentence, or an entire paragraph. Strings are one of the most-used types in real programs, so getting comfortable with them early pays off.

Creating a String

You create a String by wrapping text in double quotes and assigning it to a variable of type String. Because String is a class (not a primitive), its name begins with a capital S. Once created, the text can be printed, measured, searched, and transformed using the many methods the String class provides.

Declaring and printing a String

public class Main {
  public static void main(String[] args) {
    String greeting = "Hello, Java!";
    System.out.println(greeting);
  }
}

String Length

Every String can tell you how many characters it contains through the length() method. Notice the parentheses: length() is a method call for Strings, unlike arrays where length is a field without parentheses. This is a common source of confusion for beginners.

Measuring a String

String name = "Programming";
System.out.println("Characters: " + name.length()); // 11

Common String Methods

The String class ships with dozens of helper methods. A few you will reach for constantly are shown below. Remember that these methods do not change the original String; they return a brand new one, because Strings in Java are immutable.

MethodWhat it doesExample result
toUpperCase()Returns the text in capital letters"hi" becomes "HI"
toLowerCase()Returns the text in small letters"HI" becomes "hi"
indexOf("a")Position of the first match, or -1"java".indexOf("a") is 1
charAt(0)The character at a given position"java".charAt(0) is 'j'
trim()Removes spaces at the start and end" hi " becomes "hi"

Using String methods together

String title = "  java Basics  ";
System.out.println(title.trim());            // "java Basics"
System.out.println(title.trim().toUpperCase()); // "JAVA BASICS"
System.out.println("java Basics".indexOf("Basics")); // 5
Note: Strings are immutable, meaning their contents never change after creation. Methods like toUpperCase() build and return a new String, so remember to store or print the returned value.
  • Use double quotes for String values; single quotes are only for a single char.
  • length() counts every character, including spaces and punctuation.
  • Chain methods left to right, for example text.trim().toLowerCase().
  • To compare text, use equals() rather than == so you compare content, not object identity.

Exercise: Java Strings

What does == actually compare when used on two String objects?