47

Say I have the following three constants:

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:

// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);

Please let me know what I'm doing wrong.

Nateowami
  • 1,005
  • 16
  • 23
Drew Bartlett
  • 1,863
  • 5
  • 23
  • 37

12 Answers12

106

Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • 4
    There must be a better way when there are n values involved. – mlissner Apr 16 '13 at 23:27
  • 6
    @mlissner Yes, use a loop and a variable `max`, check for every variable whether or not they are larger than `max`, if so: set `max` to that variable. Assuming your n values are in an array of course. – Jochem Kuijpers Sep 20 '13 at 17:12
28

If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])

NumberUtils.max(int[])
Pang
  • 9,564
  • 146
  • 81
  • 122
eugene
  • 956
  • 1
  • 11
  • 13
28

you can use this:

 Collections.max(Arrays.asList(1,2,3,4));

or create a function

public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals)); 
}
shifu
  • 813
  • 8
  • 12
  • op asked for multiple primitive types.. int and double. This doesn't address that. But I do like the premise of this. – JGFMK Jun 10 '20 at 20:06
13

Math.max only takes two arguments, no more and no less.

Another different solution to the already posted answers would be using DoubleStream.of:

double max = DoubleStream.of(firstValue, secondValue, thirdValue)
                         .max()
                         .getAsDouble();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
10

Java 8 way. Works for multiple parameters:

Stream.of(first, second, third).max(Integer::compareTo).get()
Den Roman
  • 548
  • 7
  • 10
9

Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

In your example, max could be used like this

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
cba
  • 166
  • 1
  • 5
4

I have a very simple idea:

 int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.

Regards, Norbert

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
user5430588
  • 49
  • 1
  • 1
  • 5
    I'm pretty sure the question was about the max number... not the min number ;) – Edd Jun 16 '16 at 09:22
1

Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().

If you don't like that you can always create your own method for it...

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.

It might also be throwing an error since there is no such thing as "MY_DOUBLE2".

  • Now I'm just a noob myself, if anyone could help me clean that up it would be greatly appreciated... – Samuel Willems Jun 04 '13 at 21:34
  • This method leads to unnecessary boxing/unboxing and contains avoidable type checks and casts. It would be better to have several overloaded methods with a concrete type. – deamon Aug 23 '18 at 08:06
1
int first = 3;  
int mid = 4; 
int last = 6;

//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which  //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
kirshiyin
  • 141
  • 1
  • 9
1

You can do like this:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42
0

if you want to do a simple, it will be like this

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

and the output will be something like this

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

References Java™ How To Program (Early Objects), Tenth Edition

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
0

Simple way without methods

int x = 1, y = 2, z = 3;

int biggest = x;
if (y > biggest) {
    biggest = y;
}
if (z > biggest) {
    biggest = z;
}
System.out.println(biggest);
//    System.out.println(Math.max(Math.max(x,y),z));