The Java ternary operator (Java ternary examples)

Summary: This tutorial shares examples of the Java ternary operator syntax.

Interested in saying a lot while writing a little? In a single line of code, the Java ternary operator let's you assign a value to a variable based on a boolean expression — either a boolean field, or a statement that evaluates to a boolean result.

At its most basic, the ternary operator, also known as the conditional operator, can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.

Back to top

Simple ternary operator examples

One use of the Java ternary operator is to assign the minimum (or maximum) value of two variables to a third variable, essentially replacing a Math.min(a,b) or Math.max(a,b) method call. Here’s an example that assigns the minimum of two variables, a and b, to a third variable named minVal:

minVal = (a < b) ? a : b;

In this code, if the variable a is less than b, minVal is assigned the value of a; otherwise, minVal is assigned the value of b. Note that the parentheses in this example are optional, so you can write that same statement like this:

minVal = a < b ? a : b;

I think the parentheses make the code a little easier to read, but again, they’re optional, so use whichever syntax you prefer.

You can take a similar approach to get the absolute value of a number, using code like this:

int absValue = (a < 0) ? -a : a;
Back to top

General ternary operator syntax

Given those examples, you can probably see that the general syntax of the ternary operator looks like this:

result = testCondition ? value1 : value2

As described in the Oracle documentation, this statement can be read as “If testCondition is true, assign the value of value1 to result; otherwise, assign the value of value2 to result.”

Here are two more examples that demonstrate this very clearly. To show that all things don’t have to be ints, here’s an example using a float value:

// result is assigned the value 1.0
float result = true ? 1.0f : 2.0f;

and here’s an example using a String:

// result is assigned the value "Sorry Dude, it's false"
String result = false ? "Dude, that was true" : "Sorry Dude, it's false";

As shown in these examples, the testCondition can either be a simple boolean value, or it can be a statement that evaluates to a boolean value, like the (a < 0) statement shown earlier.

Finally, here’s one more example I just saw in the source code for an open source project named Abbot:

private static final int subMenuDelay = Platform.isOSX() ? 100 : 0;

Back to top

More power: Using the ternary operator on the right hand side of a Java statement

As Carl Summers wrote in the comments below, while the ternary operator can at times be a nice replacement for an if/then/else statement, the ternary operator may be at its most useful as an operator on the right hand side of a Java statement. Paraphrasing what Carl wrote:

The “IF (COND) THEN Statement(s) ELSE Statement(s)” construct is, itself, a statement.

The “COND ? Statement : Statement” construct, however, is an expression, and therefore it can sit on the right-hand side (rhs) of an assignment.

Carl then shared the following nice examples. Here’s his first example, where he showed that the ternary operator can be used to avoid replicating a call to a function with a lot of parameters:

myFunc( (COND ? defaultValue : getMyFuncParameter()) );

Next, here’s an example where the conditional operator is embedded into a String, essentially used to construct the String properly depending on whether x is singular or plural:

returnString = "There " + (x > 1 ? " are " + x + " cookies" : "is one cookie") + " in the jar.";

And finally, here’s one more of his examples, showing a similar operation within a String, this time to print the salutation properly for a person’s gender:

returnString = "Thank you " + (person.isMale() ? "Mr. " : "Ms. ") + person.getLastName() + ".";

(Obviously, many thanks to Carl Summers for these comments. He initially shared them as comments below, and I moved them up to this section.)

Back to top

Java ternary operator test class

As a final note, here’s the source code for a Java class that I used to test some of the examples shown in this tutorial:

public class JavaTernaryOperatorExamples
{
  /**
   * Examples using the Java ternary operator
   * @author alvin alexander, devdaily.com
   */
  public static void main(String[] args)
  {
    // min value example
    int minVal, a=3, b=2;
    minVal = a < b ? a : b;
    System.out.println("min = " + minVal);
    
    // absolute value example
    a = -10;
    int absValue = (a < 0) ? -a : a;
    System.out.println("abs = " + absValue);

    // result is assigned the value 1.0
    float result = true ? 1.0f : 2.0f;
    System.out.println("float = " + result);
 
    // result is assigned the value "Sorry Dude, it's false"
    String s = false ? "Dude, that was true" : "Sorry Dude, it's false";
    System.out.println(s);
    
    // example using the ternary operator on the rhs, in a string
    int x = 5;
    String out = "There " + (x > 1 ? " are " + x + " cookies" : "is one cookie") + " in the jar.";
    System.out.println(out);

  }
}
Back to top

Thanks to everyone for your comments on this tutorial. You were right, the old tutorial was at best outdated (putting it nicely), so I finally took the time to rewrite it today. I think everyone will agree that it's greatly improved, so I removed all the old comments that are no longer relevant.

That being said, if you have any other comments or questions about this tutorial, as usual, feel free to add them here.

Permalink

This tutorial is great but I would've liked you to show what each example would look like with "if", "else" etc.

Permalink

Great Examples, took them to illustrate to my students. Thank you. grateful

Permalink

It's worth pointing out, that ternary operator should only be used where it results in clearer code. They can be used to write totally unreadable and unmaintainable code that breaks with the slightest change done a bit wrong.

General guidelines to be broken only when really necessary:
Don't nest them. Avoid using them as parts of more complex expressions. Use parentheses liberally, especially when they're part of a more complex expression.

If you need to modify code with ?:-expressions (your own or somebody else's) and it takes time to understand what it actually does, then just rewrite it as if-else statemant if you need to change it. It takes far less time to write the long if-else, than it takes to write compact ?:-expression and then do a few test/debug runs to get it working right.

Thanks for your comments. I agree, I've seen a few uses of the ternary operator that resulted in code that was hard to read. (And as I seem to work with more programming languages every year, I really appreciate code that is easy to read.)

Well for me if we are talking about this tutorial, this tutorial is good. But in terms of comparing ternary and if else statements, both have an advantage to each other. It is right that ternary operator are difficult to read or debug than if else so it should not be over used. It will always depends to the programmer the readability of his codes. As long as it is readable, it's better to use ternary operator.o(-_-)o

Permalink

Another thing that should be mentioned is you should be aware of the consequences of using different types.
For instance if you do something like:

int x=1;
System.out.println((x<1)?9.9:9);

You can expect to see '9.0' as the result and not '9' because the ternary operator will promote the second value to a double.

Permalink

Helpful, but you have these comments/results wrong in your test class-

// result is assigned the value 1.0
float result = false ? 1.0f : 2.0f;
System.out.println("float =" + result);

// result is assigned the value "Sorry Dude, it's false"
String s = true ? "Dude, that was true" : "Sorry Dude, it's false";
System.out.println(s);

Permalink

thank you so much.. was very useful!!

Permalink

Thanks for the great writeup. :)

Permalink

Excellent tutorial. My colleague and I were just discussing this and I came upon this because I forgot the syntax to it. It's cool but I dont use it as it is very hard to read when you combine some other logic with it, and that's why I dont really keep this thing in mind when I write my codes. But this is an excellent tutorial nonetheless.

Permalink

Great explanation.. it helped me when looking at some code my colleagues wrote. However, I hate this syntax. It just forces me to think extra hard when I'm trying to understand somebody's code, and it detracts from the flow. Yes, you can write more functionality with less code, which was great when we were writing in assembly language -- but that practice is often discouraged today. Sure you can still use variable names like a4 and b9 and you would be writing less code, but they are really hard to understand. My money is on "if then else", case statements, or other more verbose methods unless there is a scenario where you really need to use the ternary. I think its evil.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.