Sunday, May 26, 2019

Assignment

More About Assignment

Variable assignment is a form of expression; in fact, because one assignment expression results
in a value, you can string them together like this:
x = y = z = 0;
In this example, all three variables now have the value 0.
The right side of an assignment expression is always evaluated before the assignment takes place.
This means that expressions such as x = x + 2 do the right thing; 2 is added to the value of x,
and then that new value is reassigned to x. In fact, this sort of operation is so common that Java
has several operators to do a shorthand version of this, borrowed from C and C++. Table 3.4
shows these shorthand assignment operators.
Table 3.4. Assignment operators.

Expression Meaning

x += y x = x + y
x –= y x + x – y
x *= y x = x * y
x ¸= y x = x ¸ y

Technical Note: If you rely on complicated side effects of subexpressions on either
side of these assignments, the shorthand expressions may not be entirely equivalent
to their longhand equivalents. For more information about very complicated
expressions, evaluation order, and side effects, you may want to consult the Java
Language Specification.

No comments:

Post a Comment

150+java interview questions and answers

Java Platform 1 . Why is Java so popular? 2 . What is platform independence? 3 . What is bytecode? 4 . Compare JDK vs JVM vs JRE 5 ....