2

I would like to clear some doubts about the ternary operator in Java.

In Java, it looks like : x = (c ? a : b). From what I read and experienced, it seems to be executed as a branch if/else, meaning that only one statement is evaluated (either a or b, but never both). I would like to know if it's always true.

In C, it might be compiled into conditional moves, which evaluates both expressions a and b.

To be accurate, I would like to know if it's true for Android code as well. Knowing that the Java bytecode is actually translated into native instructions upon installation on devices with an recent OS (see Android Runtime(ART)). Is there a risk that conditional moves appear after ART ?

Let's take an example. A basic class which would contain :

//class content

int victoriesA = 0;
int nonVictoriesA = 0;
int totalCalls = 0;

//...class content

public int getIncrementedCounter(int goalsA,int goalsB){
    totalCalls++;
    return (goalsA > goalsB ? ++victoriesA : ++nonVictoriesA);
}

public boolean testOpertor(){
    return (totalCalls == victoriesA + nonVictoriesA);
}

If getIncrementedCounter is called multiple times during the execution of a program, will the function testOperator always return true ? (Assuming the code runs on a single thread)

I know that I should just use if/else branches to be sure to get out of troubles, but I still wonder....

Gordak
  • 2,060
  • 22
  • 32

1 Answers1

3

According to the Java Language Specification, chapter 15.25

At run time, the first operand expression of the conditional expression is evaluated first. If necessary, unboxing conversion is performed on the result.

The resulting boolean value is then used to choose either the second or the third operand expression:

If the value of the first operand is true, then the second operand expression is chosen.

If the value of the first operand is false, then the third operand expression is chosen.

Being compliant with the language specification would mean only 1 expression evaluated.

Community
  • 1
  • 1
Bartek Maraszek
  • 1,404
  • 2
  • 14
  • 31