Priority of && and || in java

In Java, the logical AND (&&) operator has higher precedence than the logical OR (||) operator.


Operator Precedence:

  1. && (Logical AND): Higher precedence.
  2. || (Logical OR): Lower precedence.

This means that expressions involving both && and || will evaluate && first, unless you explicitly use parentheses to change the order of evaluation.


Example:

public class LogicalOperators {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;
        boolean c = true;

        // Without parentheses
        boolean result = a || b && c;
        System.out.println("Result without parentheses: " + result);

        // With parentheses to change precedence
        boolean resultWithParentheses = (a || b) && c;
        System.out.println("Result with parentheses: " + resultWithParentheses);
    }
}

Output:

Result without parentheses: true
Result with parentheses: true

Explanation:

  1. Without Parentheses:

    • b && c is evaluated first because && has higher precedence.
    • Then, the result of b && c is combined with a using ||.
  2. With Parentheses:

    • (a || b) is evaluated first because parentheses override operator precedence.
    • Then, the result of a || b is combined with c using &&.

Summary:

Operator Precedence (High to Low)
&& Higher
` ` Lower

Recommendation:

  • Always use parentheses to make your code easier to read and avoid confusion about precedence.

댓글

이 블로그의 인기 게시물

Install and run an FTP server using Docker

Using the MinIO API via curl

PYTHONPATH, Python 모듈 환경설정

Elasticsearch Ingest API

오늘의 문장2

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Fundamentals of English Grammar #1

To switch to a specific tag in a Git repository

You can use Sublime Text from the command line by utilizing the subl command

티베트-버마어파 와 한어파(중국어파)의 어순 비교