What is different of IF BRANCH and AND as OPERATOR?

Viewed 23

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");
}
1 Answers

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");
}
Related