Search code examples
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 same. What their different actually? Any there example case which i must use that ONE 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");
    }