-4

I am lost learning for an exam right now. I try to understand why the Output 4 throws an exceptions while 5 works, since f is from type C1_A.

The Error 4 throws: Exception in thread "main" java.lang.Error: Unresolved compilation problem: mt_A cannot be resolved or is not a field at C1_O.main(C1_O.java:15)

public class C1_A {
    static int [] a = {4,3,2,9};
    public int mt_A(int b) {
        int[] a = {31,30,29};
        return(a[b]);
    }
}

public class C1_O {
    public static void main (String args[]){
        int a=2;
        int b=2;
        int c=a;
        int d;
        C1_A f = new C1_A();
        a = C1_A.a[b];
        System.out.println(a); //Output 1
        System.out.println(c); //Output 2
        System.out.println(f.mt_A(a)); //Output 3
        C1_A.a[c+1]= 2;
        d=C1_A.a[c-1];
        System.out.println(f.mt_A(d)); //Output 4
        System.out.println(f.mt_A(C1_A.a[3])); //Output 5
    }
}
  • 3
    Take a paper and a pen, write down the inital values of all the variables in a table and fill up the table according to the program. – TDG Sep 21 '18 at 18:02
  • 1
    This is a perfect example of a rubber duck debugging: https://en.wikipedia.org/wiki/Rubber_duck_debugging – Rabbit Guy Sep 21 '18 at 18:03
  • you will get an error at the line following //Output 3 bcz you are trying to assign a value to a static variable – Rabbit Guy Sep 21 '18 at 18:06
  • @GBlodgett Output 5 doesn't throw an error (as far as I know) – Decent_Excitement Sep 21 '18 at 18:09
  • Your output 4 fails cos Your array length is 3 meaning your max index is 2. But you are passing in d with a value of 3. This index doesn't exists thus an ArrayOutofbounds exception. – kar Sep 21 '18 at 18:10

1 Answers1

-2

Output 3 works for me (should be 29).

Output 4 breaks because d = 3 after d = C1_A.a[c-1];
This means you try and reference the 4th index of the array which only has 3 elements.
That's why you get the ArrayIndexOutOfBounds exception.

Five works fine two because the static array was modified by C1_A.a[c+1]= 2;
This makes the 3rd element = 2. So C1_A.a[3] == 2 and not 9.
So the output 5 is 29.