Lesson 7 | Evaluating Expressions |
Objective | Evaluate expressions in Java. |
Evaluating Expressions in Java
Following is an example of a simple expression:
x = 13 + 7;
In this expression, x is a variable, = is the assignment operator, 13 and 7 are integer literals, and + is the addition operator.
This expression specifies that the number 13 is added to the number 7, with the result being assigned to the variable x.
Java always evaluates expressions from left to right, with one exception involving operator precedence. The multiplication and division operators (*, /) have a higher precedence than addition and subtraction (+, -),
which means that you always perform a multiplication or division before an addition or subtraction.
Let us take a look at a more complex expression:
x = 7 * 5 + 33 / 11;
Applying the rule of operator precedence, the equation resolves into:
x = 35 + 3;
Now you can use the left to right rule and simply add 35 and 3, which results in a value of 38 being stored in x.
Operator precedence should be carefully observed when creating expressions because it is easy to make mistakes if you do not account for it.
Assignment Operators
The assignment operators that you need to know for the exam are =, +=, -=, *=, and /=.
The simple assignment operator, =, is the most frequently used operator. It is used to initialize variables with values and to reassign new values to them. The +=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication and division with assignment.
The += operator can be read as
first add and then assign,
and -= can be read as first subtract and then assign. Similarly, *= can be read as
first multiply and then assign
and /= can be read as
first divide and then assign.
If you apply these operators to two operands, a and b, they can be represented as follows:
a -= b is equal to a = a - b
a += b is equal to a = a + b
a *= b is equal to a = a * b
a /= b is equal to a = a / b
Examples of Code:
double doubleVal = 10.3;
/*OK to assign literal 10.3 to variable of type double*/
int a = 10;
int b = a;
float float1 = 10.3F;
/* OK to assign literal 10.3F to variable of type float*/
float float2 = float1;