Reputation: 37
So recently I got a question that how to perform the function of if...else without if...else.
Like if a program is to find the greater between integer a
and b
, one would easily write that
if (a>b) {
System.out.println("a is greater");
} else {
System.out.println("b is greater");
}
Is there any other way to do this without if...else
method?
Upvotes: 0
Views: 786
Reputation: 424993
Use the ternary:
System.out.println((a > b ? "a" : "b") + " is greater");
Note: Both this code and your code assumes that a
is not equal to b
.
A more contrived solution would be:
switch ((int) Math.signum(Integer.compare(a, b))) {
case 1:
System.out.println("a is greater");
break;
default:
System.out.println("b is greater");
}
Upvotes: 2
Reputation: 51
we can use the Java Ternary Operator.
System.out.println((a > b ? "a" : "b") + " is greater);
for more follow this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Upvotes: 0