字符数组的默认值

Nav*_*avi 24 java arrays

字符数组的默认值是给出一个空指针异常...可以告诉为什么这个异常仅适用于字符数组...即使其他dataype数组的默认值为null.例如

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

抛出空指针异常

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

输出:空

Era*_*ran 28

打印char[]行为与其他数组的行为不同,因为PrintStream(System.out实例的类型)具有打印char数组的特定方法public void println(char x[])- 而对于其他数组,Object则使用s 的一般方法- public void println(Object x).

println(Object x)向其传递null引用时打印字符串"null" .

/**
 * 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();
}
Run Code Online (Sandbox Code Playgroud)

println(char x[])NullPointerException当传递给它时引发一个null引用.

public void println(char x[])调用public void print(char s[])哪些调用public void write(char buf[]),抛出NullPointerExceptionwhen buf.length被评估:

/*
 * 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Javadoc print(char s[])是第一个被调用的方法public void println(char x[]),它提到了NullPointerException异常:

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

打印一个字符数组.根据平台的默认字符编码将字符转换为字节,这些字节的写入方式与write(int)方法完全相同.

参数:
s要打印的字符数组
抛出:
NullPointerException - 如果s为null