AeriaGlorisia AeriaGlorisia - 1 year ago 85
Java Question

String index out of range - Why is this occurring?

(Please keep in mind I have only been studying java for under a month on my own)

I am trying to make a program that simply tells you the last char of the name you give the program. Here is my code:

import java.util.Scanner;

public class LastCharacter {

public static void main(String[] args) {
Scanner reader = new Scanner(;
String name = reader.nextLine();

public static char lastChar(String text) {
char lastChar = '\0';;
int i = 0;
for (i = 0; i <= text.length(); i++) {
lastChar = text.charAt(i);

return lastChar;


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(
at LastCharacter.lastChar(
at LastCharacter.main(

Java Result: 1

I also know this can be made by subtracting the length of the string by 1, however I would like to know why this method isn't working. I don't really know how to word this but do strings and chars not get along? (pls dont make fun of me)


Answer Source

Java strings start at a base index of 0. Therefore, this line: for (i = 0; i <= text.length(); i++) { is trying to access an index that doesn't exist. The string main only goes from 0 to 3. So, when you try to access index 4, you get the out of bounds error.

Replace this line: for (i = 0; i <= text.length(); i++) {

With this: for (i = 0; i < text.length(); i++) { to fix the problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download