clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the = operator. For example:

In the above assignment statement, the result of x + 1 is assigned to the variable x. Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation x = 2 * x + 1 ≠ the Java expression x = 2 * x + 1

In Java, an assignment statement is an expression that evaluates a value, which is assigned to the variable on the left side of the assignment operator. Whereas an assignment expression is the same, except it does not take into account the variable.
Java Assignment Statement vs Assignment Expression
That’s why the following statements are legal:

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting.

What's Your Opinion?