According to Oracle I should be able to apply methods like .intValue()
and .compareTo()
to doubles but when I write dbl.toString()
in NetBeans, for example, the IDE tells me that doubles can't be dereferenced. I can't even cast them to Integers in the form (Integer) dbl
!
I have JDK 1.6 and NetBeans 6.9.1. What's the problem here?
The problem is your understanding of objects vs. primitives.
More than anything else, you just need to recognize that the capitalized names are object classes that act like primitives, which are really only necessary when you need to send data from primitives into a method that only accepts objects. Your cast failed because you were trying to cast a primitive (double) to an object (Integer) instead of another primitive (int).
Here are some examples of working with primitives vs objects:
The Double class has a static method toString():
double d = 10.0;
// wrong
System.out.println(d.toString());
// instead do this
System.out.println(Double.toString(d));
Other methods can use operators directly rather than calling a method.
double a = 10.0, b = 5.0;
// wrong
if( a.compareTo(b) > 0 ) { /* ... */ }
// instead you can simply do this:
if( a >= b) { /* ... */ }
int a = 0;
double b = 10.0;
// wrong
a = b.intValue();
// perform the cast directly.
a = (int)b;