Home > database >  For a block of code to get usernames (sample given in body), I'm getting an array index bound e
For a block of code to get usernames (sample given in body), I'm getting an array index bound e

Time:06-06

This is an example block of code

public class usernames {
    public static void main(String[] args)
    {
        int user[] = { 1, 2, 3, 4, 5 };
        for (int i = 0; i <= user.length; i  )
            System.out.println(user[i]);
    }
}

CodePudding user response:

Here if you have defined i<=user.length that means i<=5 since you array length is 5 but when you are indexing the array to print it can print between 0 to 4 indexes when it reaches index 5 there is no value in the array for index 5 hence it throws index out of bound error. try this code

public class Usernames {
    public static void main(String[] args)
    {
        int user[] = { 1, 2, 3, 4, 5 };
  
        for (int i = 0; i < user.length; i  )
            System.out.println(user[i]);
    }
}
  • Related