question 6

Posted Thursday, September 03, 2009 by SacrosanctBlood in

There is a small code snippet below. Obviously, you can execute and see
the result, I would request to you to try to answer it before executing
it. What will be the output of the below, obviously in a well written
class, with public static void main?

  int[] intArray = null;

        System.out.println(String.valueOf( intArray ));

        char[] charArray = null;

        System.out.println(String.valueOf( charArray ));



1 comment(s) to... “question 6”

1 comments:

SacrosanctBlood said...

The first sysout prints null.

The second one throws a null pointer exception.



The reason being, the valueOf() method in String class is overloaded. In
case of int array, it argument is considered as Object, and a null check
is done to return a string ‘null’ if the object is null.



When the char array argument is used, a new String instance is returned
with ‘new String(charArray)’ construct and the String constructor,
having no null checks, results in a null pointer.



Post a Comment