Could someone translate this? I have yet to effectively use these expressions.

sometimes I use the if statement to evaluate if a var has a certain value. most of the times it works.
is the ternary expression used to handle other possibilities that could come up?


m != null ? m.name : getMName (files[i].getName 
4 Years
Discussion Span
Last Post by deceptikon

What you refer to as "ternary expression" is actually called the conditional operator in Java.
Terminology aside, you can use the conditional operator as a shorthand for the following:

int a;

if (condition)
    a = expression1;
    a = expression2;

Using the conditional operator, the above can be rewritten as follows:

int a = condition ? expression1 : expression2;

For more precise info about what condition, expression1, and expression2 can be, I refer to the Java Language Specification section 15.25 Conditional Operator ? :.

Edited by mvmalderen


You use a ternary when you want to use one of two different values depending on some boolean. The boolean and the values can be constants or expressions eg

if the language is French say "Bonjour", otherwize say "Hello"

String greeting = language.equals("French) ? "Bonjour" : "Hello";

I have yet to effectively use these expressions.

It's fairly straightforward when compared with an if..else statement. This:

x = (condition) ? foo : bar;

Becomes this:

if (condition) {
    x = foo;
else {
    x = bar;

IF you don't need to make an assignment and are instead just performing an action with a side effect, this:

(condition) ? someAction() : someOtherAction();

Becomes this:

if (condition) {
else {

That's really all the ternary operator does. A benefit is that it can be used in an enclosing expression where the if..else statement cannot.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.