CodeBlanks Logo Icon CodeBlanks

length and charAt

Learn string access with length() and charAt().

length and charAt

The length of a String is given by the length() method. To get a specific character use charAt(i); i starts at zero.

String name = "Alex";
int n = name.length();      // 4
char first = name.charAt(0);  // 'A'

The first character has index 0, the last has index length() - 1. Going beyond this throws StringIndexOutOfBoundsException.

In loops, i < name.length() is a safe bound.

Index bounds

String indices start at 0. For a String of length n, valid indices are between 0 and n - 1.

String s = "Java";  // length 4
s.charAt(0);  // 'J' - valid
s.charAt(3);  // 'a' - valid (last)
s.charAt(4);  // ERROR!

An out-of-range index throws StringIndexOutOfBoundsException. So loops use i < s.length(), not i <= s.length().

Practice Use length and charAt

Write a Main class with a main method. Assign "Java" to String word. Print word.length() and word.charAt(0) on separate lines with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        String word = "Java";
        System.out.println(word.length());
        System.out.println(word.charAt(0));
    }
}

Expected output

4
J

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does "Java".length() return?

  • 4 Correct answer
  • 3
  • 5
  • 0

Explanation: length() gives the character count.

2 Complete the charAt call

Question
char first = name.____(0);
Answer
char first = name.charAt(0);

Explanation: charAt(0) gives the first character.

3 Match the methods

Term Meaning
length() Length
charAt(0) First char
charAt(n-1) Last char
"Java" String

All lessons in Beginner