0

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?

1
  • 3
    System.out.printf("%d is greater than %d%n", Math.max(a, b), Math.min(a, b)); Commented Oct 24, 2021 at 5:39

3 Answers 3

2

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");
}
Sign up to request clarification or add additional context in comments.

5 Comments

You cannot switch with the result of Math.signum(). It returns double or float. And a - b can overflow.
Math.signum(Integer.MIN_VALUE - Integer.MAX_VALUE) is 1.0.
@mokyade I actually don’t care about such edge cases, because it’s not necessary to convey the intent, but since you are persistent, see minor tweak to cater for this nevertheless.
I'm sorry for being persistent. I like Integer.compare.
@mokyade respect: Integer.compare() is better.
0

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

Comments

0

This is pretty easy using Math:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.