Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me what is conditional operators(?:) and how I can able to use it?

1 Answer

0 votes
by (26.7k points)
edited by

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!!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 17, 2021 in Java by Harsh (1.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...