syntaxbooleanboolean-logicboolean-expressionboolean-operations

What is different of IF BRANCH and AND as OPERATOR?


Sometimes I used to use if branch, sometimes AND operand. But I feel they are both the same. What's the difference, actually? Any example case in which I must use that one of them only?

For example:

//Defining variable
a=2
b=3
if(a==2){
 if(b==3){
 println("OK");
 }
}

It's equal with:

if (a==2 && b==3){
 println("OK");
}

Solution

  • You might use the first doubly-nested if condition when the inner if had an else branch, e.g.

    if (a == 2) {
        if (b == 3) {
            println("OK");
        }
        else {
            println("not OK")
        }
    }
    

    If you don't have this requirement, then the second more concise version is probably what most would choose to use:

    if (a == 2 && b == 3) {
        println("OK");
    }