Muhammad Ikhwan Perwira
Muhammad Ikhwan Perwira

Reputation: 1052

What is the difference between IF BRANCH and AND as operators?

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

Upvotes: 2

Views: 83

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522396

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

Upvotes: 1

Related Questions