tags:

views:

105

answers:

3

Could anyone please tell me why the following casting is resulting in compile time error:

Long l = (Long)Math.pow(5,2);

But why not the following:

long l = (long)Math.pow(5,2);
+4  A: 

You can't cast a primitive type (like double) directly to an object. That's just not how Java works. There are some situations where the language can apply the appropriate object creation for you, like function call arguments.

Pointy
The browser? You mean the Java Runtime Engine?
Software Monkey
you can cast primitive double directly to object Double.
Carl
oops thanks @Monkey! Also yes there's boxing/unboxing now, but it's marginally evil and I prefer to keep my head in the sand :-)
Pointy
+7  A: 

Math.pow(5,2) is a double, which can be cast to long. It can not be cast to Long.

This would however work fine, thanks to autoboxing which converts between long and Long:

Long l = (long)Math.pow(5,2);

To summarize, you can convert double --> long and long --> Long, but not double --> Long

Martin
Math.pow(a,b) is a double. Autoboxing does the trick as you mention.
Dan
@Martin - Just a random type of question (+1 to answer, BTW) - would this work in C# since primitives derive from objects?
JasCav
+1  A: 

Because primitive types are not object at all effects also if java added some workarounds (like implicit unboxing of these types).

You can sole it in various ways, like:

Long l3 = ((Double)Math.pow(5, 2)).longValue();

This works because Java is able:

  • to implicit cast from a primitive type to another one when you refer to them just with normal type declaration eg: int to long
  • to implicit cast from a boxed type to another one eg. Int to Long
  • to switch between boxed and unboxed type when they are the same type eg long to Long
Jack