Wednesday, November 4, 2009

Casting an object if the object is NULL?

If you are casting an object which is null, then java will not throw any exceptions. What does is, it will simply assign the null to the casted reference type variable.

Object obj = null;

String a = (String) obj;

In above example "a" will be assigned as NULL.

ava.util.ArrayList al = session.get("xyzObject");

Object o = (Object) al;

String a = (String) o;

System.out.println(a);

If session.get("xyzObject") != NULL:

    If we are getting an arraylist object from session then the above code will throw Class Cast Exception.

If session.get("xyzObject") == NULL:

    If we are getting a null value from session then the above code will not throw any exceptions. The reasons because null can be cast to any object references.

What's a big thing in it:

    The main thing is if we are sending null to an object reference most of time, and some time if we are start sending a value in it, it may break the code...

Hope this post may give some thoughts. Please leave your comments if any.

2 comments:

ppow said...

There is no reason why an exception would be thrown, as NULL references are valid parts of the language.

If in your code you want the passed object not to be null you should check that yourself and manually throw NullPointerException if necessary.

Jobs said...

sounds good...

Post a Comment

 

This content comes from a hidden element on this page.

The inline option preserves bound JavaScript events and changes, and it puts the content back where it came from when it is closed.
Click me, it will be preserved!

If you try to open a new ColorBox while it is already open, it will update itself with the new content.

Updating Content Example:
Click here to load new content