string index out of bound exception, String index out of range

26,469

Solution 1

A String of length() == n has valid indices from 0 to n-1;

Change

for(int i=0; i<=n; i++)

to

for(int i=0; i<n; i++)

Solution 2

Imagine you have the following array of length 7:

-----------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |  <-- Array index
-----------------------------
|10 |20 |30 |40 |50 |60 |70 |  <-- Array values
-----------------------------

A for loop of for(int i=0; i<=n; i++) in this case will loop 8 times iterating from index 0 to 7.

But the array element at index 7 does not exist, hence giving outOfBoundsException.

Where as a for loop of for(int i=0; i<n; i++) will loop 7 times iterating from 0 to 6.

Share:
26,469
Arvind Lakhani
Author by

Arvind Lakhani

Updated on July 09, 2022

Comments

  • Arvind Lakhani
    Arvind Lakhani almost 2 years

    So, I was writing a simple program to enter a string and count the total no. of m. So, here's my code

    for(int i=0; i<=n; i++)
        {
            if((str.charAt(i)=='m'))
            {
            } else {
                count++;
            }
        }
        System.out.println("The total number of m is "+count);
    

    where n=str.length(); and str is a string which I had taken but there this error which keeps coming

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
    at java.lang.String.charAt(String.java:646)
    at javaapplication.JavaApplication.main(JavaApplication.java:28
    Java Result: 1
    

    what's this error and how to remove it?