Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected increment result in java array

While learning how to declare, initialize and access the array elements in java, I wrote this simple code:

class ArrayAccess{

    public static void main(String args[]){
        int[] a;
        a = new int[4];
        a[0] = 23;
        a[1] = a[0]*2;
        a[2] = a[0]++;
        a[3]++;
        int i = 0;
        while(i < a.length){
            System.out.println(a[i]);
            i++;

        }
    }
}

But I am getting unexpected output.

The output I am getting is:

24     

46

23

1

So,

Why 24 instead of 23 as the value of a[0]? If this is due increment of a[0] at a[2] then why a[1]'s element is 46 and not 48.

why 23 instead of 24 as the value of a[2]?

like image 287
fortytwo Avatar asked Dec 03 '22 23:12

fortytwo


2 Answers

a[2] = a[0]++; incremnets a[0] after copying the value into a[2]

Its the same as:

a[2] = a[0];
a[0]+=1;

If you want to increment the value before the assignation use a[2] = ++(a[0]);

This ist the same as:

a[0]+=1;
a[2] = a[0];
like image 149
pad Avatar answered Dec 05 '22 13:12

pad


a[2] = a[0]++; 

is

  int temp = a[0];
  a[2] = a[0];
  a[0] = temp + 1;
like image 45
AllTooSir Avatar answered Dec 05 '22 12:12

AllTooSir