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]? 
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];
                        a[2] = a[0]++; 
is
  int temp = a[0];
  a[2] = a[0];
  a[0] = temp + 1;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With