简体   繁体   中英

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] ?

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;

Because of the following line:

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

Increment (++) has a side effect of incrementing the right-side value. Otherwise you should use:

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

Another example is the similar concept of ++number. If you had written:

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

a[0] would be incremented, and THEN added to a[2]. So in a[2] you would have: 24

small modification in your prog required

class ArrayAccess{

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

    }
}

}

now lets come to questions

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.

yes it is due of increment of a[0] at a[2]. But point is the moment u are doing a[1] = a[0]*2; its not incremented yet.

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

you are doing a[2] = a[0]++; whats happening is first value of a[0] is assigned to a[2] and then ultimately value at a[0] is incremented not at a[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM