Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array gives null value. Why?

public class abc {
        static int arr[];
        static char ch[];

        public static void main(String[] args) {
        System.out.println(ch); //it gives null pointer exception at run time
        System.out.println(arr); //it gives output as "null".
        }
    }
share|improve this question
4  
pretty sure because the char array version of println() is overloaded and tries to print the array as a string, whereas the int[] overload simply prints it as an array. Refer to C++'s std::cout::operator<< when called with char * or a generic void * pointer. –  user3477950 2 hours ago
    
Yep, all has to do with println overloading, and nothing to do with the arrays themselves. int[] and char[] are essentially identical save for the fact that int is 4-byte signed data and char is 2-byte unsigned data. –  Hot Licks 2 hours ago
    
I don't know why you felt it was necessary to ask a second question about this. The explanation is exactly the same as the explanation to your previous question -- you're calling two different methods which have different behavior. –  Boann 2 hours ago
add comment

4 Answers 4

up vote 7 down vote accepted

System.out is instance of PrintStream and this class has few overloaded println methods. In your case:

  1. System.out.println(ch); is using public void println(char x[])
  2. System.out.println(arr); is using public void println(Object x) (there is no public void println(int[] x) method so the closest available type for int[] which println can use is Object).

First method is using

String.valueOf(x);

to get string representation of object which we want to print and code of valueOf method looks like

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

so it is null-safe (will return "null" string if reference will hold null).

Second method is at some level using

public void write(char cbuf[]) throws IOException {
    write(cbuf, 0, cbuf.length);
                 //    ^^^^^^^ this throws NPE
}

and because cbuf is null cbuf.length will throw NullPointerExceltion because null doesn't have length (or any other) field.

share|improve this answer
    
Isn't this a library bug then? –  usr 1 hour ago
    
@usr It is hard to tell. Maybe Java authors think of print(Object) as method mostly used to print state of object (with help of its toString method) so printing null feel right, but from print(char[]) they expect to print exact characters from char array and since char[] is not so common type compared to String being it null feels more like bug than intended state, so they decide to inform programmer about it (and stop execution buggy program) by throwing NPE. But that doesn't have to be true. You would need to ask Java designers. –  Pshemo 1 hour ago
    
@usr, possibly, although if you wanted to use the Object overload then you could do System.out.println((Object) chr). –  ıɯɐƃoʇ ǝızuǝʞ 1 hour ago
    
@ıɯɐƃoʇǝızuǝʞ yes, but this would print result of toString() of array so we would see something like [C@1db9742 instead of content of array. In other words println(new char[]{'f','o','o'}) will print foo while println((Object)new char[]{'f','o','o'}) will print [C@1db9742. –  Pshemo 1 hour ago
add comment

The answer exists in the PrintWriter source code (of which System.out is an instance).

Start with the fact that the uninitialized arrays, as reference variables, are given the default of null.

The println(char[]) (eventually) attempts to call .length on the passed in array. It's null, resulting in the NullPointerException. println(char[]) (eventually) calls write(char[]):

public void write(char buf[]) {
    write(buf, 0, buf.length);
}

There is no overload of println matching int[], but there is a println(Object). There it (eventually) attempts String.valueOf, passing the null reference, so String.valueOf takes the null and returns the String "null". println(Object) calls print(Object):

public void print(Object obj) {
    write(String.valueOf(obj));
}
share|improve this answer
    
Exception handling is expensive.. why not just check if it is null? I know this is a question for the designers but I was curious –  staticx 2 hours ago
add comment

These are two different methods, and their APIs describe the behavior fully.

public void println(Object x) calls String.valueOf at first, which returns "null" if x is null.

See:

public void print(char[] c) calls the print(char[] c) method which throws NullPointerException if c is null.

See:

share|improve this answer
add comment

You are actually calling two separate, overloaded System.out.println() methods. public void println(char[] x) is overloaded as per the documentation. No specific overloading of println(Object x) exists for the int[] arrays.

So, when println() is called on an integer array, public void println(Object x) is called. According to the Javadocs:

This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

Since the value of the string is null, the method prints null.

The println() method works somewhat differently when it takes a character array as a parameter. Superficially, the method itself seems similar:

Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().

However, the print(char[]) method behaves quite differently in key ways:

Prints an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

Thus, it calls a different method. The documentation for print(char[]) explicitly states that in your situation, your exception is thrown:

Throws: NullPointerException - If [input parameter] s is null

Hence, the cause of the difference in behavior.

See Javadocs for more information about the println and print methods: http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println()

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.