Java Reference
In-Depth Information
However, long to int and float to int assignments are not compatible and hence the following snippet of code
generates compile-time errors:
long big = 524L;
float f = 1.19F;
int i = 15;
i = big; // A compile-time error. long to int, assignment incompatible
i = f; // A compile-time error. float to int, assignment incompatible
In such a case where the right-hand operand's value is not assignment compatible with the left-hand variable's
data type, the value of the right-hand operand must be cast to appropriate type. The above pieces of invalid code,
which use assignment operators, can be rewritten with cast as follows:
i = (int)big; // Ok
i = (int)f; // Ok
An expression is a series of variables, operators, and method calls, constructed according to the syntax of the
Java programming language that evaluates to a single value. For example, num = 25 is an expression. The expression,
which uses the assignment operator, also has a value. The value of the expression is equal to the value of the right-hand
operand. Consider the following piece of code, assuming that num is an int variable:
num = 25;
Here, num = 25 is called an expression and num = 25; is called a statement. The expression num = 25 does two things.
Assigns the value 25 to the variable num.
Produces a value 25, which is equal to the value of the right-hand operand of the assignment
operator.
The second effect (producing a value) of using the assignment operator in an expression may seem strange at this
point. You may wonder what happens to the value 25 produced by the expression num = 25 . Do you ever use the value
returned by an expression? The answer is yes. You do use the value returned by an expression. Consider the following
expression, which uses chained assignment operators, assuming that num1 , and num2 are int variables:
num1 = num2 = 25;
What happens when the above piece of code is executed? First, the part of the expression num2 = 25 is executed.
As mentioned earlier, there will be two effects of this execution:
It will assign a value of 25 to
num2 .
It will produce a value of 25. In other words, you can say that after assigning the value 25 to
num2 , the expression num2 = 25 is replaced by a value 25, which changes the main expression
num1 = num2 = 25 to num1 = 25 .
Now, the expression num1 = 25 is executed and the value 25 is assigned to num1 and the value produced, which
is 25 , is ignored. This way, you can assign the same value to more than one variable in a single expression. There can
be any number of variables used in such a chained assignment expression. For example,
num1 = num2 = num3 = num4 = num5 = num6 = 219;
 
Search WWH ::




Custom Search