字符数组的默认值是什么?

24

字符数组的默认值会导致空指针异常...有人可以解释为什么只有字符数组会出现这种异常,即使其他数据类型的数组的默认值也是null。 例如:

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

抛出空指针异常

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

输出:null

3个回答

28

打印char[]的行为与其他数组不同,因为PrintStream(即System.out实例的类型)具有用于打印char数组的特定方法 - public void println(char x[]),而对于其他数组,则使用Object的通用方法 - 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();
}

println(char x[]) 在传递给它一个 null 引用时会抛出 NullPointerException

public void println(char x[]) 调用 public void print(char s[]),该方法又调用 public void write(char buf[])。当评估 buf.length 时,会抛出 NullPointerException

/*
 * 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;
  }
}

顺便提一下,print(char s[]) 方法是 public void println(char x[]) 调用的第一个方法,在文档注释中提到了 NullPointerException 异常:

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

打印字符数组。根据平台默认的字符编码将字符转换为字节,并按照 write(int) 方法的方式精确地写入这些字节。

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


相当奇怪的设计选择。毕竟,print((String)null)不会抛出异常;char[]应该表现得一样。这可能是早期实现中的一个错误,他们必须保留。 - ZhongYu
1
@bayou.io 但是你可以说print(char[])已经与print(Object)有所不同,因为后者总是表现得像使用了toString或类似的方法,而前者实际上并没有。也许这个糟糕的设计选择是使方法名称相同的原因。 - ajb

4

第一种方法是使用println(char[] x),第二种方法是使用println(Object obj),后者在内部使用String.valueOf(x)并打印null而不是NullPointerException

请检查String.valueOf()函数。

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

根据Java文档,println(char[] x)会在char[] arrnull时抛出NullPointerException

0

当应用程序试图在需要对象的情况下使用null时,会抛出NullPointerException。这些情况包括:

  1. 调用空对象的实例方法。
  2. 访问或修改空对象的字段。
  3. 将null的长度视为数组。
  4. 访问或修改null的插槽,就像它是一个数组一样。
  5. 将null作为Throwable值抛出。

要了解有关NullPointerException的更多信息,请参阅Oracle文档。以上来源取自NullPointerException


OP对与char[]相关的情况特别感兴趣,尤其是不同的行为。您的回答似乎没有涉及到这个方面。 - Panther
1
@Panther,我知道之前的帖子中有一些对这个问题有用的答案,但我们还需要说明为什么会出现NullPointerException。由于没有人分享这个问题,所以我想回答一下。 - Coding Bad
这是一件好事,但也是 OP 所问的事情。否则你会被踩。顺便说一句,我不是那个踩了你的人。 - Panther

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接