0
0
Javaprogramming~5 mins

Operator precedence in Java

Choose your learning style9 modes available
Introduction
Operator precedence tells the computer which math or logic operation to do first when there are many in one line.
When you write math calculations with many operators like +, -, *, / in one line.
When you combine logic checks like &&, ||, and ! in one condition.
When you want to avoid mistakes in how your program calculates or decides things.
When you read code and want to understand how the computer will solve the expression.
When you use parentheses to change the order of operations.
Syntax
Java
result = expression_with_operators;
Operators like *, /, % have higher precedence than + and -.
Parentheses () can change the order to make some parts calculate first.
Examples
Multiplication (*) happens before addition (+), so 3*4=12, then 2+12=14.
Java
int result = 2 + 3 * 4;
Parentheses make 2+3 happen first, so 5*4=20.
Java
int result = (2 + 3) * 4;
&& has higher precedence than ||, so false && false = false, then true || false = true.
Java
boolean check = true || false && false;
Parentheses change order: true || false = true, then true && false = false.
Java
boolean check = (true || false) && false;
Sample Program
This program shows how operator precedence works with math and logic operators. It prints the results to see the order of calculation.
Java
public class OperatorPrecedenceDemo {
    public static void main(String[] args) {
        int a = 5 + 2 * 3; // 2*3=6, then 5+6=11
        int b = (5 + 2) * 3; // 5+2=7, then 7*3=21
        boolean c = true || false && false; // false && false = false, then true || false = true
        boolean d = (true || false) && false; // true || false = true, then true && false = false

        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println("d = " + d);
    }
}
OutputSuccess
Important Notes
Always use parentheses if you want to be sure about the order of operations.
Remember that multiplication, division, and modulus have higher precedence than addition and subtraction.
Logical AND (&&) has higher precedence than logical OR (||).
Summary
Operator precedence decides which operation runs first in an expression.
Use parentheses to control or clarify the order.
Knowing precedence helps avoid bugs and understand code better.