Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (6.5k points)
Is there a shorter way to do simple if-else statement in terms of value assignment of a variable based on that condition?

1 Answer

0 votes
by (11.3k points)
edited by

For this, we use ternary operators in JAVA. 

If there is an if-else statement as follows:

int a=2;

if (a==2)

a=3;

else

a=1;

We can also implement the above conditional logic via the following method:

a=a==2?3:1;

Here, the boolean condition, a==2 is checked, if it's true, then the first value '3' is assigned to a. Otherwise, the value '1' is assigned to a.

Browse Categories

...