Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

EVerytime I write any code similar to this one, I get this type of error. It's building a file but not letting it run, it just throws exception. I'm not familiar with exceptions as i am a beginner kindly help me out and specifically point out the mistake that I'm making.

public static void main(String args[]) {
    String name = "Umer Hassan";
    String name1 = "Hassan Umer";
    char[] name2 = new char[name.length()];

    for (int j = 0; j <= name.length(); j++) {
        for (int i = 0; i <= name.length(); i++) {
            if (name.length() == name1.length()) {
                if (name.charAt(i) == name1.charAt(i)) {
                    name2[i] = name1.charAt(i);
                }
            }
        }
    }
}

When I run the program it shows the following error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(String.java:658)
    at Anagram.main(Anagram.java:24)
like image 232
Umer Hassan Avatar asked Dec 09 '12 18:12

Umer Hassan


People also ask

How do you fix a string index out of range error?

The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.

What does string index out of range mean Java?

The string index out of range means that the index you are trying to access does not exist. In a string, that means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.

What is exception write a program for index out of bound exception?

If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This is unlike C/C++, where no index of the bound check is done. The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime.


2 Answers

Your loop control variables (i / j) are going up to name.length() - which is an out of bounds index (since the max index of a string/list is len - 1 - remember the first index is 0).

Try using i < name.length() and j < name.length() as the loop conditions instead.

like image 122
arshajii Avatar answered Oct 09 '22 16:10

arshajii


You should write the for cycle as

for (int i = 0; i < name.length(); i++)

The indexes in the strings are zero-based, as in the arrays, so they have a range from 0 to length - 1. You go to length, which is outside of bounds.

like image 30
Malcolm Avatar answered Oct 09 '22 15:10

Malcolm