Home > Back-end >  Conditional Operator without if...else in java
Conditional Operator without if...else in java

Time:10-24

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?

CodePudding user response:

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(a - b)) {
    case 1:
        System.out.println("a is greater");
        break;
    default:
        System.out.println("b is greater");
}

CodePudding user response:

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

CodePudding user response:

This is pretty easy using Math:

int max = Math.max(a, b);
  • Related