Operator Precedence in Java
1 * 2 + 3 is treated as (1 * 2) + 3
Precedence and associativity of Java operators:
Figure:
Order of evaluation of subexpressions:
Exercises:
int x = 5;
int y = 10;
int z = ++x * y--;
System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));
System.out.println(1 + 2 + "abc");
System.out.println("abc" + 1 + 2);
- Java has well-defined rules for Operator Precedence.
- It is used in an expression are evaluated when the expression has several operators.
- For example, multiplication and division have higher precedence than addition and subtraction.
- When two operators share an operand the operator with the higher precedence goes first.
- For example:
1 * 2 + 3 is treated as (1 * 2) + 3
- Due, multiplication has a higher precedence than addition.
- When an expression has two operators with the same precedence, the expression is evaluated according to its associativity.
- For example:
- For Example:
Precedence and associativity of Java operators:
Figure:
Order of evaluation of subexpressions:
- In Java, subexpressions are evaluated from left to right.
- For Example:
- So, evaluated in the order A(), B(), D(), E(), and C()
- When using the conditional and or operators (&& and ||), Java does not evaluate the second operand unless it is necessary to resolve the result.
Exercises:
- Q - What is the result of the following code fragment?
int x = 5;
int y = 10;
int z = ++x * y--;
- Q - What is the result of the following code fragment? Explain.
System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));
- Q - What does the following code fragment print?
System.out.println(1 + 2 + "abc");
System.out.println("abc" + 1 + 2);
Tags:
Core java