Hello.
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?

1

m != null ? m.name : getMName (files[i].getName 

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;
else
    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 ? :.

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) {
    someAction();
}
else {
    someOtherAction();
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.