5

Can null be casted to any type? i.e. will the following code work

public <T> T foo(Object object){
    return (T) object;
}

Duck duck = foo(new Duck()); // this works

Duck duck2 = foo(null); // should this work?
Cat cat = foo(null); // should this work?

// if they are both null, should this be true?
boolean equality = duck2.equals(cat);

My question is, is null 'castable to anything'?

fernandohur
  • 7,014
  • 11
  • 48
  • 86
  • 6
    What happens when you try? (My guess: you can 'cast' it, but it's still `null`, so you get an exception with `equals`) – tobias_k Jun 13 '14 at 15:11
  • Check this out it might help http://stackoverflow.com/questions/2707322/what-is-null-in-java – jhobbie Jun 13 '14 at 15:12
  • 1
    yes you can cast `null` to any object but that object will be a null reference. for example : `String str=(String)null;` is fine. – Braj Jun 13 '14 at 15:19

2 Answers2

5

From Javadocs:

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

Vivin
  • 1,327
  • 2
  • 9
  • 28
1

Yes those both should work but the key is you need to make sure you don't try to reference those fields or methods later. (at least until you have assigned those variables to something else)

All objects inherit Object but since you assigned to null it won't actually have the methods or fields you would expect an Object to have. So you will get an error here when you try to call equals() because null does not have the methods you would normally inherit from object.

You can assign a variable you declare to null which can be very useful to prevent compiler errors if its actual value is defined in an if statement.

ford prefect
  • 7,096
  • 11
  • 56
  • 83