Result of unexpected increment in java array

While learning how to declare, initialize, and access 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 get an unexpected result.

The output I get is:

 24 46 23 1 

So,

Why 24 instead of 23 as the value of a[0] ? If this corresponds to the increment a[0] in a[2] , then why is the element a[1] 46 , not 48 .

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

+4
source share
4 answers

a[2] = a[0]++; increases the value [0] after copying the value to [2]

This is the same as:

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

If you want to increase the value to the destination, use a[2] = ++(a[0]);

This is the same as:

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

there is

  int temp = a[0]; a[2] = a[0]; a[0] = temp + 1; 
+4
source

Due to the following line:

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

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

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

Another example is a similar concept of the number ++. If you wrote:

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

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

+3
source

small modification is required in your program

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 you can ask questions

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

yes, this is due to the increment a [0] at the point [2]. But point - moment u do [1] = a [0] * 2; its not yet increased.

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

you do [2] = a [0] ++; what happens is the first value of parameter [0] assigned to the value [2], and then ultimately the value at a [0] increases, and not at a [2]

+1
source

Source: https://habr.com/ru/post/1483385/


All Articles