Sophie Sperner
Sophie Sperner

Reputation: 4546

Ternary if operator inside a regular if one

In Java, if I use a ternary if operator inside a regular if, for example:

if ((x > y - z) ? true : callLongWaitedMethod(many, parameteres)) {
        loveTeddyBear();
}

will it execute the callLongWaitedMethod if x > y - z is indeed true? I hope it is not and I can use this nice statement, slightly complicated at the first glance, but more attractive to compare with the extra boolean variable:

boolean b = (x > y - z) ? true : callLongWaitedMethod(many, parameteres);
if (b) {
        loveTeddyBear();
}

especially if I'm using this inside a big loop which iterates over and over, so creating boolean each time will not be nice from the performance point of view while if I declare the boolean outside the loop, I may miss the neat because of the big size of the loop.

Upvotes: 1

Views: 224

Answers (6)

Matt
Matt

Reputation: 11805

You should ask yourself as the coder, if you can't figure out what it's going to do, should you really be coding it that way? why not just this:

if ( (x>y-z) || 
     (x<=y-z && callLongWaitedMethod(many, parameteres))) {
    loveTeddyBear();
}

This will make much more sense to the novice programmer who is not familiar with your code.

Upvotes: 0

Brian J
Brian J

Reputation: 694

It seems like you have the answer you want. You could also just use debugging statements with a simple version of your code to see what gets executed as a way of verifying the behavior. Something like

if ((1 > 2) ? true : someSimpleMethod()) {
    System.out.println("true if");
}

And as your someSimpleMethod() have

public boolean someSimpleMethod() {
    System.out.println("calling someSimpleMethod()");
    return true;
}

From there you can swap 1 and 2 to see if the someSimpleMethod() would execute.

Upvotes: 0

assylias
assylias

Reputation: 328598

According to the Java Language Specification 15.25, the long method will only be evaluated if necessary:

The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.

Upvotes: 3

Don Roby
Don Roby

Reputation: 41137

This will work as you hope, but it would be clearer to simply use the normal || operator to accomplish exactly the same result:

if ((x > y - z) || callLongWaitedMethod(many, parameteres)) {
        loveTeddyBear();
}

Upvotes: 6

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11482

If you want to execute callLongWaitedMethod when (x > y - z) is true you actually have to swap the expression:

if ((x > y - z) ? callLongWaitedMethod(many, parameteres) : true ) {
        loveTeddyBear();
}

Upvotes: 0

legoscia
legoscia

Reputation: 41528

callLongWaitedMethod will not be called if x > y - z is true.

Upvotes: 2

Related Questions