Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]);
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading