String Basics

What is a String?

A String is a sequence of characters in double quotes. It is a reference type (a class in java.lang), and it is immutable: once created it cannot change. Methods like toUpperCase() return a new String.

Example

public class Main {
    public static void main(String[] args) {
        String greeting = "Hello";
        String name = new String("Anil");   // also works, but rarely needed
        System.out.println(greeting + ", " + name);
        System.out.println("Length: " + greeting.length());

        String upper = greeting.toUpperCase();
        System.out.println(upper);
        System.out.println(greeting);  // original is unchanged
    }
}

Output

Hello, Anil
Length: 5
HELLO
Hello

Index Positions

String s = "CAREER";
  index:     0   1   2   3   4   5
  char:      C   A   R   E   E   R
  s.length() = 6, last index = 5

Example

public class Main {
    public static void main(String[] args) {
        String s = "CAREER";
        System.out.println(s.charAt(0));
        System.out.println(s.charAt(s.length() - 1));
        System.out.println(s.indexOf('E'));
        System.out.println(s.lastIndexOf('E'));
    }
}

Output

C
R
3
4

Note: s.charAt(6) on a 6-letter string throws StringIndexOutOfBoundsException. Valid indexes are 0 to length-1.