q1612749
q1612749

Reputation: 47

converting an if statement to a conditional operator in Java

How do I simplify this code with a conditional operator in Java? This is from dr. Liang's Introduction to Java.

public class Test {
    public static void main(String[] args) {
        int i = 3;
        int j = 4;
        int k = max(i, j);
        System.out.println("The max int is " + k);
    }

    public static int max(int num1, int num2) {
        int result;

        if (num1 > num2) {
            result = num1;
        }

        else {
            result = num2;
        }

        return result;

    }
}

Upvotes: 3

Views: 1196

Answers (4)

Nikhil Pathania
Nikhil Pathania

Reputation: 821

This would be one way to modify your example to use the ternary operator.

You should generally keep the values in the operator short otherwise they get hard to read.

public class Test {
    public static void main(String[] args) {
        int i = 3;
        int j = 4;
        int k = max(i, j);
        System.out.println("The max int is " + k);
    }

    public static int max(int num1, int num2) {
        int result;

        result = (num1 > num2) ? num1 : num2;
        return result;

    }
}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201439

While you could use the conditional operator ? : to implement this

public static int max(int num1, int num2) {
    return num1 > num2 ? num1 : num2;
}

But, I would prefer Math.max(int, int) like

public static int max(int num1, int num2) {
    return Math.max(num1, num2);
}

You might also choose to use varargs and support an arbitrary number of int(s). Using an IntStream you could do

public static int max(int... nums) {
    return IntStream.of(nums).max().getAsInt();
}

Upvotes: 4

GhostCat
GhostCat

Reputation: 140427

You can turn things into a one-liner using the conditinal ternary operator:

return (num1 > num2) ? num1 : num2;

But just for the record: it would be better to keep that max method around; simply for the sake of readability. It helps to have that functionality in its own method.

But of course: you want to read about java.lang.Math.max() which already provides exactly that functionality (not only for int, but all the other numerical primitive types as well)!

So, the real answer is: yes, use a method for that check; but don't create your own version; use the one that is already coming with Java by default. In other words: do not re-invent the wheel. Even when it is just a small wheel like this one.

Upvotes: 5

Edmundo Santos
Edmundo Santos

Reputation: 8287

You can use a conditional ternary operator.

int k = (i > j) ? i : j;

This expression evaluates to:

If i is greather than j, assign i to k. If not, assign j to k.

Upvotes: 3

Related Questions