0

I am struggling with a problem, which I can't understand why it doesn't work. How do I pass a variable through the double obj and convert to int?
Why does it not work in the top code snippet, but it works in the bottom code snippet below the line?

The only difference seems to be adding an extra variable, which is also typed as a double?

//Converting double to int using helper

//This doesn't work- gets error message
//Cannot invoke intValue() on the primitive type double

double doublehelpermethod = 123.65;
double doubleObj = new Double( doublehelpermethod);
System.out.println("The double value is: "+ doublehelpermethod.intValue());
//--------------------------------------------------------------------------
//but this works! Why?

Double d = new Double(123.65);
System.out.println("The double object is: "+ doubleObj);
A.H.
  • 63,967
  • 15
  • 92
  • 126
UKDataGeek
  • 6,338
  • 9
  • 46
  • 63
  • 1
    Just being a bit nit picky here but your variable name nomenclature should be consistent. If you are going to use camel casing for variable names do it through out. It is a bad idea to mix and match. Also appending the word "helpermethod" to a variable name may cause confusion later on.. – The Code Pimp Dec 25 '11 at 22:24

2 Answers2

3

The double is a primitive type, while the Double is a regular Java class. You cannot call a method on a primitive type. The intValue() method is however available on the Double, as shown in the javadoc

Some more reading on those primitive types can be found here

Robin
  • 36,233
  • 5
  • 47
  • 99
  • ok- I got that- so how would I get the top snippet code to work? I have tried this- System.out.println("The double value is: "+ doubleObj.intValue()); but that also doesn't work – UKDataGeek Dec 25 '11 at 23:40
  • Change the assignment to `Double doubleObj = new Double( doublehelpermethod);` – Robin Dec 26 '11 at 09:42
  • Amazing I can't believe I missed out on the capital! But thanks Robin for the superb explanation why- really enlightening. – UKDataGeek Dec 28 '11 at 10:23
1

You're in the top snippet, trying to assign a Double object to a primitive type like this.

double doubleObj=new Double( doublehelpermethod);

which would of course work because of unboxing (converting a wrapper type to it's equivalent primitive type) but what problem you're facing is dereferencing doublehelpermethod.

doublehelpermethod.intValue()

is not possible because doublehelpermethod is a primitive type variable and can not be associated using a dot . See... AutoBoxing

Lion
  • 18,729
  • 22
  • 80
  • 110