final int a=5;
System.out.println(a+1)
prints 6 whereas System.out.println(a++)
or a=a+1
and then sop(a)
would give error.
Why would it print 6 when final values cant be changed?
Both a++
and a=a+1
assign a new value to a
.
a+1
does not: it just evaluates to 1 more than the value in a
.
Evaluating the statements:
System.out.println(a);
System.out.println(a+1);
System.out.println(a);
will show that the value of a
is the same before and after. Doing the same with a++
or a=a+1
in the middle statement (obviously making a
non-final first) will show that a
is changed.
This should be no more surprising than System.out.println(5+1)
printing 6, whilst leaving the values of 5
and 1
unchanged.
Because you never modify a
in your example. You print the result of a+1
. If you print a afterwards you'll see that it is still 5
.
It is basically
int a = 5;
int b = a+1;
System.out.println(b); // prints 6
System.out.println(a); // still prints 5
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.