1

Please refer to the following method:

public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

I always thought the first part of a Ternary operator must be a condition, but here it's a return statement instead and I'm confused.

Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
Brendon
  • 29
  • 2
  • 3
    The return keyword merely says "return the value of the following expression". Now, can you understand the expression that follows? – RealSkeptic Sep 12 '15 at 15:05

4 Answers4

3

Read it like this

return (b ? Boolean.TRUE : Boolean.FALSE);

does it make more sense now? You're just deciding what to return, depending on the value of your condition b.

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48
1

Its equivalent to :

if(b)
return Boolean.TRUE 
else
return Boolean.FALSE
Rahman
  • 3,755
  • 3
  • 26
  • 43
1

(boolean) b is a condition. What do You expect? Expression isn't required

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
1

Wikipedia suggest the following explanation:

In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.

And not only in Java, this syntax is available within PHP too.

In the following link it gives the following explanation, which is quiet good to understand it:

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

In Perl/PHP it works as:
boolean_condition?true_value:false_value

In C/C++ it works as:
logical expression? action for true : action for false

This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.

We can simplify the If-Else blocks with this Ternary operator for one code statement line. For Example:

if ( car.isStarted() ) {
     car.goForward();
} else {
     car.startTheEngine();
}

Might be equal to the following:

( car.isStarted() ) ? car.goForward() : car.startTheEngine();

So if we refer to your method:

public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

It is actually the 100% equivalent of the following:

public static Boolean valueOf(boolean b) {
    if (b == Boolean.TRUE) {
        return Boolean.TRUE;
    } else {
        return Boolean.FALSE;
    }
}

That's it!
Hope this was helpful to somebody!
Cheers!

Community
  • 1
  • 1
Randika Vishman
  • 7,983
  • 3
  • 57
  • 80