0

When we are using System.out.println(null) then we get compilation error and to resolve this we typecast null like:

System.out.println((String)null) 

and then it starts working fine.

My questions is how we are allowed to typecast null when we say that null is something which is not pointing to any location and thus has no value in itself.

Also if null is not pointing to any location then the object which is null will get Garbage collected then why we are using it at first place? I know it is litle bit out of the topic but it came to my mind.

I have seen few answers in below link but they mostly talk about println method functionality and implementation but I want to know about null only.

No Exception while type casting with a null in java

Community
  • 1
  • 1
AalekhG
  • 361
  • 3
  • 8
  • Why are we using `null` in the first place? Because we made a billion-dollar-mistake to avoid having to explicitly handle missing or optional values in the type system. – Thilo Oct 09 '15 at 05:07
  • "the object which is null will get Garbage collected " There is no object at all. – Thilo Oct 09 '15 at 05:08
  • Yes , it will get Garbage collected. So we use null mostly for JVM that this object can be garbage collected now? – AalekhG Oct 09 '15 at 05:11
  • `System.out.println((String)null) ` does not create or garbage-collect any objects. If you assign `null` (or anything else, for that matter) to a variable or field, then the object that was previously referred to by that variable or field may become eligible for garbage collection. – Thilo Oct 09 '15 at 05:13

1 Answers1

2

In Java, "null" is a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type. That's why it does not throw error you can also do this null==null

Aniruddha K.M
  • 7,361
  • 3
  • 43
  • 52