-5

hey guys i am getting this error i did the same in C and it worked but when i did it in java i am getting the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5" can you look into this -->

import java.util.Scanner;

class sort {

    public static void main(String args[]) {

        Scanner obj = new Scanner(System.in);
        int a[] = new int[5];
        int i, j;
        int temp;

        System.out.println("Enter the elements of array : ");

        for (i = 0; i < 5; i++) {
            a[i] = obj.nextInt();
        }

        for (i = 0; i < 5; i++)
            for (j = 0; j < 5; j++) {
                if (a[i + 1] < a[i]) {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                }
            }

        for (i = 0; i < 5; i++)
            System.out.println("\n" + a[i]);

    }
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
DETSUP
  • 107
  • 6
  • 4
    Probably because C does not check array bounds? https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – jackarms Aug 15 '17 at 05:50
  • In this code `if(a[i+1] – Scary Wombat Aug 15 '17 at 05:51
  • I see no reason to wonder things across languages. – ChiefTwoPencils Aug 15 '17 at 05:51
  • 1
    You got away with this in C because C doesn't explicitly check. Though I think in certain flavors of C/C++ you would have gotten an error. Bottom line is listen to the Java error and stop going out of bounds. – Tim Biegeleisen Aug 15 '17 at 05:51
  • Hint: A) just google the exception message and B) learn to **read** that exception message. Java messages are typically very human readable. You array is OUT OF bounds, it gives you the line number, and tells you the invalid index. What else would you need to understand the problem? – GhostCat Aug 15 '17 at 06:21

3 Answers3

1

Your problem is here:

    for (i = 0; i < 5; i++)
        for (j = 0; j < 5; j++) {
            // When `i` == `4` this accesses `a[5]` which does not exist.
            if (a[i + 1] < a[i]) {
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

It is ERROR in any language to access out-bounded array element.

eg, in C:

int a[1];
int tmp = a[5];

is WRONG (even if there is no crash or no execption)

so your java code is wrong, do NOT access any out-bounded element in any language.

shawn
  • 4,305
  • 1
  • 17
  • 25
-1

buddy, you can't set i equal to or greater than 5 (indexes are 0 to 4) so when it reach i == 4 in your second loop and you use a[i+1] you'll get an outOfBounException.

for (i = 0; i < 4; i++)
            for (j = 0; j < 5; j++) {
                if (a[i + 1] < a[i]) {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                }
            }
Alireza
  • 21
  • 1
  • 5