Quick Intro to the Ternary Operator
The Ternary Operator
The ternary operator is a source of confusion for many beginning programmers. In case you don’t know what the ternary operator is, it looks something like
String message = (isvalid?"Valid":"Invalid");
The ? represents the thought that goes through their head when they see it and they probably won’t get to the : .
One of the reasons why this operator is so confusing is that the symbols have no logical connection to the actual function. Everyone knows that + means addition same with – , /, and *. It’s all pretty basic math/computer stuff, even ++ isn’t too hard to figure out, but what in god’s name does ? : do? Adding to the confusion the operator is not widely used or taught in books or tutorials, so beginners are never exposed to it.
Lucky you, I’m here to teach you all about them (or maybe unlucky you? I don’t know you decide). Let’s start by pulling an example out of the big black hat of code…
Say you have created a virtual world and you need to write a code that determines whether your character buys a car or a bicycle based on how much money he has. If he has less than $20,000 he will buy a bike, else he will by a used car.
The first way to write this would be an if else statement:
Item itemToBuy;
if(amountOfMoney > 20000) {
itemToBuy = new UsedCar();
} else {
itemToBuy = new Bicycle();
}
itemToBuy.purchase();
That looks okay, but that it can be cut down considerably with our operator.
Item itemToBuy = (money > 20000 ? new UsedCar() : new Bicycle() ); itemToBuy.purchase();
or even
(money > 20000 ? new UsedCar() : new Bicycle()).purchase();
Using the ternary operator allowed it to be much more compact than a usual if/else statement (also much more confusing).
Now that we have something to work with, let’s break it into pieces.
- money > 20000
- ?
- new UsedCar()
- :
- new Bicycle()
This is the if statement of the operator. The result of the boolean comparison will determine what gets returned.
This is what signals that it is a ternary operator. It separates the ‘if statement’ from the return clauses.
This is the first return clause. If the expression evaluated to true then the value here, will be returned.
This is the second separator. It separates the ‘then’ clause from the ‘else’ clause.
And finally there is the ‘else’ clause. The value here is returned if the expression evaluated to false.
Notice how it is worded that it ‘returns’ the value. This is the main difference between the ternary operator and an if/else statement. So a better representation of a ternary operator is an if/else statement within a method.
public Item makeDecision(boolean canAfford) {
if(canAfford) {
return new UsedCar();
} else {
return new Bicycle();
}
}
public void someMethod(...) {
...
makeDecision(money > 20000).purchase();
...
}
All right so hopefully you know how the ternary operator works now. Let’s go over some ways that you can use it.
Almost forgot, for extra confusing boolean logic you can use nested ternary operators.
(money > 20000 ? (money > 40000 ? (money > 100000 ? new SuperFancyCar() : new NewCar() : new UsedCar()) : new Bicycle()).purchase();
Using the ternary operator
Unless you actually believe it will make your code cleaner, don’t. While it is nifty feature and good for showing off your coding skills, it will just confuse anybody reading your code (including you).
The few times I have seen it put to good use is with strings. Situations where similar to the first one I posted where you need to print a response based on a variable and an if/else would be cumbersome.
Whatever you do, don’t use it to return a boolean value. I didn’t believe my eyes when I saw this
if (speed > speedLimit ? true : false;) {
pullEmOver();
}
on the first result when Googling ternary operator. It is adding useless code that is especially confusing. What would have been the problem with the following?
if (speed > speedLimit) {
pullEmOver();
}
Ranting aside, I hope you learned something from this tutorial/short intro (600 words is short right?), now go out there and show off/confuse people with your new awesome coding skillz!!!!










