Search code examples
javaconditional-operator

How to properly structure Java's ternary operator compared to if statements?


I have a simple question about two versions of the same code, one using the ternary operator and one using if statements, and why they differ in their answer.

Background information on the problem. I'm trying to easily sort an array of integers and get the range of the array as well (max & min)

array given: [6, 2, 3, 8]

If statement version:

public int range(int[] num_list) {
    int[] min_max = new int[2];
    for (int i : statues) {
         if (min_max[0] == 0) {
            min_max[0] = i;
        } else {
            if (i < min_max[0]) min_max[0] = i;
        }
         if (min_max[1] == 0) {
            min_max[1] = i;
        } else {
            if (i > min_max[1]) min_max[1] = i;
        }
  System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
    }
}

Console log:

6 | 6
2 | 6
2 | 6
2 | 8

Ternary operator version:

public int range(int[] num_list) {
    int[] min_max = new int[2];
    for (int i : statues) {
        min_max[0] = min_max[0] == 0 ? i 
               : (min_max[0] = i < min_max[0] ? i : i);
        min_max[1] = min_max[1] == 0 ? i 
               : (min_max[1] = i > min_max[1] ? i : i);
  System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
    }
}

Console log:

6 | 6
2 | 2
3 | 3
8 | 8

Why is the ternary operator version incorrect? To my knowledge, it should be a ternary-replica of the if statement version?


Solution

  • The entire thing can be rewritten using if conditions as:

    public int range(int[] num_list) {
        int[] min_max = new int[2];
        for (int i : statues) {
            if (min_max[0] == 0 || i < min_max[0]) {
                min_max[0] = i;
            }
    
            if (min_max[1] == 0 || i > min_max[1]) {
                min_max[1] = i;
            }
    
            System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
        }
    }
    

    If you really want to use ternary expressions:

    public int range(int[] num_list) {
        int[] min_max = new int[2];
        for (int i : statues) {
            min_max[0] = (min_max[0] == 0 || i < min_max[0]) ? i : min_max[0];
            min_max[1] = (min_max[1] == 0 || i > min_max[1]) ? i : min_max[1];
    
            System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
        }
    }