Can someone tell me the value of “++” with an array in the following code in Java:
int [ ] arr = new int[ 4 ]; for(int i = 0; i < arr.length; i++){ arr[ i ] = i + 1; System.out.println(arr[ i ]++); }
what does the arr[ i ]++meaning in the code above mean and why we cannot do:
arr[ i ]++
arr[ i ]++ = i + 1;
The operator discussed here is called the postfix increment operator ( JLS 15.14.2 ). It is indicated that it behaves as follows:
At run time, if the evaluation of the expression of the operand completes abruptly, then the expression of the incremental increment completes abruptly for the same reason and no increment occurs.1 , .(§5.6.2) 1 .(. 5.1.3) / (§5.1.7) .postfix .
- : , arr[i]++ = v;, - , x++ = v;; postfix increment , .
arr[i]++ = v;
x++ = v;
JLS 15.1 , :
(), :[...] ( C lvalue)[...]( )
(), :
, , x++ = v;.
JLS 15.26 :
. [...], , [...] . [...]
, :
int v = 42; int x = 0; x = v; // OKAY! x++ = v; // illegal! (x + 0) = v; // illegal! (x * 1) = v; // illegal! 42 = v; // illegal! // Error message: "The left-hand side of an assignment must be a variable"
, - , .
int[] arr = new int[3]; int i = 0; arr[i++] = 2; arr[i++] = 3; arr[i++] = 5; System.out.println(Arrays.toString(arr)); // prints "[2, 3, 5]"
System.out.println(arr[i]++) :
System.out.println(arr[i]++)
int tmp = arr[i]; arr[i] = arr[i] + 1; System.out.println(tmp);
, ++ .
++
arr[i]++ " arr[i] 1" . arr[i] i+1 arr[ i ] = i + 1;. i + 2 arr[ i ]++ , , .. i + 1.
arr[i]++
arr[i]
i+1
arr[ i ] = i + 1;
i + 2
i + 1
arr[ i ] = arr[i] + 1; , " arr[i] 1 ".
arr[ i ] = arr[i] + 1;
arr[ i ]++ = i + 1;, .
++ . (, , lvalue) 1. , ++ .
++ x, x ++. x, : ++ x x x ++ . , 1, 2, 3, 4 2, 3, 4, 5.
arr[ i ]++ arr [i] 1. :
arr[i] = i + 1;
As for arr[ i ]++ = i + 1;, do not try to write such code. Even if it compiles, it will be a puzzle for you or for others.
PS I would prefer:
++arr[i];
arr [i] ++ increments the value of arr [i] by one and assigns
as for arr[ i ]++ = i + 1;This phrase means something completely different, I do not know that it is even valid java to be honest. I would, if it worked, increase the value with arr [i], and then assign it to index + 1;