Skip to lesson

String recap: characters and index positions

A String is a row of characters, and each character has a position number called an index. As in an array, the first index is 0.

Every character has an index

A ticket app needs the first letter of a passenger's name, so it must know where each letter sits. Each character has an index: the first is 0, the next 1, and the last is length() - 1, as in arrays (opens in a new tab).

The String "Ravi" as four boxes: R at index 0, a at 1, v at 2 and i at 3. length() is 4, so the last index is 3. charAt(0) gives R, charAt(3) gives i, and charAt(4) is an error because there is no index 4.
length() counts every character, spaces too (Text with String (opens in a new tab)). Arrays write a.length without brackets; Strings write s.length(), because it is a method.

Read one character: charAt()

A college checks the first and last character of a roll number. charAt(i) gives the character at index i as a char.

Example 1 · First, last and middle characters

RollNumber.javaJava
public class RollNumber {    public static void main(String[] args) {        String roll = "21CS045";        int n = roll.length();        System.out.println("Length: " + n);        System.out.println("First: " + roll.charAt(0));        System.out.println("Last: " + roll.charAt(n - 1));        System.out.println("Index 2: " + roll.charAt(2));    }}
Output
Length: 7
First: 2
Last: 5
Index 2: C

What this code does

  • roll has 7 characters, so the indexes run from 0 to 6.
  • roll.charAt(n - 1) is charAt(6), the last character 5.
  • charAt(2) is the third character, C, because counting starts at 0.

n - 1 works for a String of any length, so you never need to count the characters yourself.

Joining characters: initials

A form prints a student's initials, PS for Priya Sharma. Take charAt(0) of each name and join the two char values into text.

Example 2 · Initials from a name

Initials.javaJava
public class Initials {    public static void main(String[] args) {        String first = "Priya";        String last = "Sharma";        char a = first.charAt(0);        char b = last.charAt(0);        System.out.println("Initials: " + a + b);        System.out.println(a + b);   // 163, not PS    }}
Output
Initials: PS
163

What this code does

  • "Initials: " + a is already text, so + b joins the second letter too.
  • a + b on its own adds two char values as numbers: P is 80 and S is 83.

Every char is a number underneath (char and boolean (opens in a new tab)). Start the line with a String, or use "" + a + b, whenever you want letters and not a sum.

Empty text: isEmpty()

An app asks for a nickname and the user just presses Enter. The result is the empty String "": no characters, length 0. isEmpty() gives true only for it.

Example 3 · Check for an empty answer

Nickname.javaJava
import java.util.Scanner;
public class Nickname {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("Nickname: ");        String nick = sc.nextLine();        if (nick.isEmpty()) {            System.out.println("No nickname given");        } else {            System.out.println("Hi, " + nick + " (" + nick.length() + " letters)");        }        sc.close();    }}
Sample output
Nickname: Chintu
Hi, Chintu (6 letters)

What this code does

  • The sample shows the user typing Chintu, so isEmpty() is false and the else part runs.
  • If the user only presses Enter, nextLine() gives "" and the program prints No nickname given.

An index that does not exist

"Ravi" has indexes 0 to 3, so charAt(4) compiles but stops the program with StringIndexOutOfBoundsException.

Java
String name = "Ravi";char last = name.charAt(3);   // 'i'char oops = name.charAt(4);   // StringIndexOutOfBoundsException

Recent Java versions add a clear message: Index 4 out of bounds for length 4. It is the same mistake as an index outside an array (opens in a new tab).

Experiment

charAt lab

Type a word and move the index. What happens when the index reaches the length?

String s = "Ravi";
int i = 3;
System.out.println(s.length());
System.out.println(s.charAt(i));
s.length()
4
s.charAt(i)
i

Next step

Check your understanding

9 quick questions