-1
System.out.println((long)(new Object()!=null ? 0 : new Object()));

On execution this gives a class cast exception as follows

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

This maybe a lame question but I'm not able to understand as to why this is happening even after we are explicitly casting the 0 returned to long.

Sachin Malhotra
  • 1,211
  • 2
  • 11
  • 24

3 Answers3

5

Your problem is that you are trying to assign an int to a long which results in a ClassCastException.

To get the correct result you will need to define the value 0 that you are trying to cast to a long as an actuall long value.

In that case every non floating number that you are trying to assign is actually handelt to be an int if you don´t explicity define the type of the value.

This can easily be seen if you just write long i = 11111111111;. Your compiler should tell you that the range for this number is out of the scope for an int. To tell the compiler that this value should be handelt as a long you simply need to add an L after the number: long i = 11111111111L;.

In your case your statement should be

System.out.println((long)(new Object()!=null ? 0L : new Object()));

Some additional information:

A similiar scenario happens with the double aswell. float f = 0.; wont work because you would need to define it as a float by adding a F after the value. float f = 0.F;

EDIT:

Your value 0 should get wrapped into Integer because it is possible that it could return an Object. if you write it as System.out.println((long)(new Object()!=null ? 0 : 1)); this would compile again.

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
1

Why don't you try using;

System.out.println((long)(new Object()!=null ? 0L : new Object()));

You are getting Exception because the ternary returns Integer 0 for true and that can't be cast to Long.

Shivam
  • 649
  • 2
  • 8
  • 20
0

Just adding on to what already has been told. According to java specifications for ternary operator,

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

Also a similar question to this one which is due to yet another rule for ternary operators.

Similar tricky autoboxing question

Apologies for adding a duplicate question. :)

Community
  • 1
  • 1
Sachin Malhotra
  • 1,211
  • 2
  • 11
  • 24