24

default value for character array is giving a null pointer exception...can any tell why is this exception just for character array ...even though the default value for other dataype arrays is null. eg

class  Test{  
    char[] x;
    public static void main(String[] args) {
        Test t=new Test();
        System.out.println(t.x);    
    }
}

throwing null pointer exception

class  Test{
    int[] x;
    public static void main(String[] args) {
        Test t=new Test();
        System.out.println(t.x);
    }
}

output:null

0

3 Answers 3

28

Printing a char[] behaves differently than other arrays, since PrintStream (which is the type of the System.out instance) has a specific method for printing char arrays - public void println(char x[]) - while for other arrays the general method for Objects is used - public void println(Object x).

println(Object x) prints the String "null" when passing to it a null reference.

/**
 * Prints an Object and then terminate the line.  This method calls
 * at first String.valueOf(x) to get the printed object's string value,
 * then behaves as
 * though it invokes <code>{@link #print(String)}</code> and then
 * <code>{@link #println()}</code>.
 *
 * @param x  The <code>Object</code> to be printed.
 */
public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

/**
 * Returns the string representation of the <code>Object</code> argument.
 *
 * @param   obj   an <code>Object</code>.
 * @return  if the argument is <code>null</code>, then a string equal to
 *          <code>"null"</code>; otherwise, the value of
 *          <code>obj.toString()</code> is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

println(char x[]) throws a NullPointerException when passing to it a null reference.

public void println(char x[]) calls public void print(char s[]) which calls public void write(char buf[]), which throws the NullPointerException when buf.length is evaluated:

/*
 * The following private methods on the text- and character-output streams
 * always flush the stream buffers, so that writes to the underlying byte
 * stream occur as promptly as with the original PrintStream.
 */

private void write(char buf[]) {
  try {
    synchronized (this) {
      ensureOpen();
      textOut.write(buf);
      textOut.flushBuffer();
      charOut.flushBuffer();
      if (autoFlush) {
        for (int i = 0; i < buf.length; i++)
        if (buf[i] == '\n')
            out.flush();
      }
    }
  }
  catch (InterruptedIOException x) {
    Thread.currentThread().interrupt();
  }
  catch (IOException x) {
    trouble = true;
  }
}

BTW, the Javadoc of print(char s[]), which is the first method called by public void println(char x[]), mentions the NullPointerException exception :

void java.io.PrintStream.print(char[] s)

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.

Parameters:
s The array of chars to be printed
Throws:
NullPointerException - If s is null

Sign up to request clarification or add additional context in comments.

2 Comments

pretty odd design choice tho. after all, print((String)null) does not throw exception; char[] should behave the same. It could be a bug in earlier impl, that they have to keep.
@bayou.io But you could say that print(char[]) already behaves differently from print(Object), in that the latter always behaves as if a toString or similar method were used, while the former really doesn't. Perhaps the poor design choice was making the method names the same.
4

First one is using println(char[] x) and the second one is using println(Object obj) which is internally using String.valueOf(x) and print null instead of NullPointerException

Check String.valueOf()

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

and according to java doc println(char[] x) will throw NullPointerException if char[] arr is null.

Comments

0

NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.

To understand more about NullPointerException refer to Oracle docs. Above source taken from NullPointerException

3 Comments

OP is interested in case related to char[] and specially the different behaviors. Your answer doesnot seems to cover that aspect
@Panther I know and above posts are some useful answers to the question but we also need to state as to why NullPointerException actually occurs. Since no body shared that so I thought of answering it.
Which is good thing however also things that OP has asked. Else you will get downvotes. On same note I am not one who have downvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.