Strange behaviour with Object.intValue()

南笙酒味 提交于 2019-12-01 13:08:57

问题


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);

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/8631652/strange-behaviour-with-object-intvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!