Java Operator Precedence Table and Examples

Author: Tatyana Milkina

Java has many operations, each performing a specific function. Operators differ in precedence, which determines the order of their execution in an expression. For example, multiplication and division, just like in mathematics, have higher precedence than addition and subtraction. Delimiters (parentheses, array indices) have the highest precedence, followed by unary operations, while the assignment operator has the lowest precedence.

Operators in Java can be classified into several types: arithmetic, logical, bitwise, comparison, and assignment operators. The table below presents their precedence order. Operators on the same row have the same precedence. The lower an operator is in the table, the later it is executed in an expression:

Java Operator Precedence Table
[] () .        
++ -- ~ ! +(unary) - (unary) (type casting)
* / %        
+ -          
>> >>> <<        
> >= < <= instanceof    
== !=          
&            

^

 

 

 

 

 

 

|            
&&            
||            
? :            
->            
=            

Example of Operator Precedence

Consider these two expressions:

int a = 5 + 3 * 2; // result: 11, since multiplication is performed first 
int b = (5 + 3) * 2; // result: 16, since addition is performed first due to parentheses

As shown in the example, using parentheses allows changing the order of operations, which can significantly affect the final result.

Example of Logical Operators

boolean result = (5 > 3) && (10 > 8); // true, since both conditions are true 
boolean result2 = (5 > 3) || (10 < 8); // true, since at least one condition is true

Logical operators && and || follow precedence rules: && is executed before ||. However, using parentheses improves readability.

Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments