Basically, a conditional operator is a one-line statement of if-else statement. Given below is an example of it:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Orange Juice");
} else {
serveDrink("Beer");
}
This code can be shortened by using conditional operator as:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
I hope this will help.
Want to know more about Java? Prefer this tutorial on Learn Java.
Want to become a Java Expert? join Java Course now!!