Why is autoboxing/unboxing failing here?
Asked Answered
R

4

8

In the program below, the result is that 0.0 is considered less than Double.MIN_VALUE. Why?

We have a solution (work with Doubles only and use compareTo) and I want to understand why unboxing is failing here.

import java.util.Date;
import java.util.Calendar;
import java.math.BigDecimal;

public class Test {

  public static void main(String[] args) {
    double max = 99999.9999;
    double min = Double.MIN_VALUE;
    Double test = 0.0;

    System.out.println(max > test); // expect true; is true
    System.out.println(test > min); // expect true; is false
  }
}
Rabbit answered 23/7, 2011 at 13:5 Comment(1)
Going to add a link to a previous SO question that has an excellent answer from @aioobe. IMO Sun should have named this constant something more intuitive but that ship has sailed. #3885293Heavyweight
D
11

According to the Javadocs :

MIN_VALUE

A constant holding the smallest positive nonzero value of type double, 2-1074.

In other words, it is bigger than 0.

Denominative answered 23/7, 2011 at 13:8 Comment(0)
C
5

You should read the Double.MIN_VALUE specification. It's a minimum possible but positive Double value which means it's larger than 0.0.

A constant holding the smallest positive nonzero value of type double, 2-1074.
It is equal to the hexadecimal floating-point literal 0x0.0000000000001P-1022
and also equal to Double.longBitsToDouble(0x1L). 
Consumable answered 23/7, 2011 at 13:9 Comment(0)
D
2

Double.MIN_VALUE = 4.9E-324 which is still a positive number. I think you are looking for min = - Double.MAX_VALUE

Dedal answered 23/7, 2011 at 13:13 Comment(0)
T
2

According to me autoboxing has no problems. Perhaps you simply need to use something like Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY that should work well with the < and > operators. For example note that

-Double.MAX_VALUE > Double.NEGATIVE_INFINITY
is true!
Tourane answered 23/7, 2011 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.