Captain  Tiger
Captain Tiger

Reputation: 37

Conditional Operator without if...else in java

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

Answers (3)

Bohemian
Bohemian

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

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

This is pretty easy using Math:

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

Upvotes: 0

Piyush Kumar
Piyush Kumar

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

Related Questions