Search code examples
javastring-lengthcharat

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7


I'm trying to print the last name character, but my code is generating an exception.

Code:

import java.util.Scanner;

public class LastCharacter {


    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Type your name: ");
        String name = reader.nextLine();
        char nameLastChar = lastCharacter(name);
        System.out.println("Last character = " + nameLastChar);


    }


    public static char lastCharacter(String text){

        int last = text.length();
        char lastChar = text.charAt(last);
        return lastChar;
    }


}

Exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7

I can't find my mistake and I don't understand the exception information.


Solution

  • If a String is 7 characters long, the last index is 6, not 7. Remember, indexing starts at 0.

    You want

    int last = text.length() - 1; // Adjust the index
    char lastChar = text.charAt(last);