How to find the median of 3 numbers in Java?

To find the median of 3 numbers in Java, you need to compare all of them with each other.

Here's how you do it:

public class FindMiddle {

  public static void main(String[] args) {
    // 1
    System.out.println(middleOfThree(1, -5, 10));

    // 15
    System.out.println(middleOfThree(100, 1, 15));

    // 50
    System.out.println(middleOfThree(49, 50, 51));
  }

  public static int middleOfThree(int first, int second, int third) {
    if (second < first && first < third || third < first && first < second) {
      return first;
    }

    if (first < second && second < third || third < second && second < first) {
      return second;
    }

    return third;
  }
}