Reputation: 521
This code, which should return the smaller of the two numbers, returns a negative number similar to the greater number:
Math.min(15, 21474836477) --> returns -2147483642
I suspected this had something to do with the range of int's
, so I changed the values to long
and the program worked fine.
I don't quite understand the seemingly random number it returns- why is it -2147483643
and not the actual number I put in, -21474836477
? Is the difference caused by the amount it overflowed, or is it influenced by the other parameter of Math.min in some way?
Upvotes: 1
Views: 1567
Reputation: 26175
The stated result, -2147483642, is 5-Integer.MAX_VALUE and also 7+Integer.MAX_VALUE. I suspect that the Math.min argument is actually that value, possibly resulting from evaluation of one of those expressions. Being very negative, it is definitely less than 15.
This program:
public class Test {
public static void main(String[] args) {
System.out.println(Math.min(15, Integer.MAX_VALUE));
System.out.println(Math.min(15, 7+Integer.MAX_VALUE));
System.out.println(Math.min(15, 5-Integer.MAX_VALUE));
}
}
outputs:
15
-2147483642
-2147483642
Upvotes: 2
Reputation: 1268
Math.min is overloaded as shown below.
static double min(double a, double b) Returns the smaller of two double values. static float min(float a, float b) Returns the smaller of two float values. static int min(int a, int b) Returns the smaller of two int values. static long min(long a, long b) Returns the smaller of two long values.
therefore you can even use it with long values for example
long x = 98759765l;
long y = 15428764l;
// print the smaller number between x and y
System.out.println("Math.min(" + x + "," + y + ")=" + Math.min(x, y));
However, your long range is also out of range
Upvotes: 0
Reputation: 279880
This
Math.min(15, 21474836477)
cannot possibly have returned
-2147483642
The code itself would not have compiled because the integer literal 21474836477
is outside the int
value range.
It's possible you ran
Math.min(15L, 21474836477L)
in which case you would be running the overloaded Math.min(long, long)
method.
Upvotes: 0