Could any one please tell me the meaning of "++" with 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 is arr[ i ]++
meaning in above code, and why we can't do like:
arr[ i ]++ = i + 1;
The operator being discussed here is called the postfix increment operator (JLS 15.14.2). It is specified to behave as follows:
- At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs.
- Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable.
- Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable.
- If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored.
- The value of the postfix increment expression is the value of the variable before the new value is stored.
The last point is the key for this question: the reason why you can't do arr[i]++ = v;
is the same exact reason why you can't do x++ = v;
; the postfix increment expression returns a value, not a variable.
From JLS 15.1 Evaluation, Denotation and Result:
When an expression in a program is evaluated (executed), the result denotes one of three things:
- A variable [...] (in C, this would be called an lvalue)
- A value [...]
- Nothing (the expression is said to be void)
An assignment needs a variable on the left hand side, and a value is NOT a variable, and that's why you can't do x++ = v;
.
From JLS 15.26 Assignment Operators:
The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable [...], or it may be a computed variable, as can result from a field [...] or an array access. [...]
The following snippet shows erroneous attempts to assign to a value, going from rather subtle to more obvious:
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"
Note that you can use the postfix increment operator somewhere on the left hand side of an assignment operator, as long as the final result is 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]"
The code System.out.println(arr[i]++)
means this:
int tmp = arr[i];
arr[i] = arr[i] + 1;
System.out.println(tmp);
Your second example doesn't make sense because you can't use the ++
operator on a value.
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