The Conditional (ternary) operator, cleaning up if-else assignments since 1996…
The conditional operator, or ternary operator as it is otherwise known is a great way for assigning variables based on boolean tests. For example you may have seen the following :
public class MonkeySniffer
{
public static void main(String[] args)
{
int x = 5;
String s;
if (x < 10)
{
s = "Its less than 10";
}
else
{
s = "its greater than 10";
}
System.out.println(s);
}
}
Pretty simple right? However that if-else statement is a bit messy considering all we’re doing is checking a condition and then using the output of that to assign a literal to our String reference.
A ternary operator allows us to perform the conditional check AND the assignment all in one line, it looks a bit like this in its psuedo code format
condition ? value if true : value if false
Lets modify the above sample to use the ternary operator. In plain English, we say that s is going to be assigned from either the true or the false condition based on the condition.
public class MonkeySniffer
{
public static void main(String[] args)
{
int x = 5;
String s;
s = x < 10 ? "Its less than 10" : "its greater than 10";
System.out.println(s);
}
}
How much neater is that?! What happens is, the condition is evaluated, i.e., the “x < 10" part. If this equates to true then we assign s the first value, if its false, we assign s the second value.
That is pretty much all there is to it, lets have a look at some other examples, paste the following into your IDE and have a play.
public class MonkeySniffer
{
public static void main(String[] args)
{
int x = 5;
String s;
s = x < 10 ? "Its less than 10" : "its greater than 10";
System.out.println(s);
s = x == 5 ? "x is 5" : "x is not 5";
System.out.println(s);
s = (x > 0 && x < 10) ? "bigger than zero, but less than 10" : "smaller than 0 or bigger than 10";
System.out.println(s);
}
}
Thats it, if you've got any comments please let me know!
Happy coding!
Further Reading :
Wikipedia conditional operator


Hi James,
Let me give you a “Friday night computer club” type of hint.
What’s up with the String s declaration? Why not replace:
String s;
s = x < 10 ? "Its less than 10" : "its greater than 10";
System.out.println(s);
with:
String s = x < 10 ? "Its less than 10" : "its greater than 10";
System.out.println(s);
Or even go "crazy" and limit the scope of the String (if your only desire is to print it) and do:
System.out.println(x < 10 ? "Its less than 10" : "its greater than 10");
Reusing same variable for different things is baaad. m'kay?
Cheers,
Dalibor a.k.a. Slovene coding machine