字符数组的默认值

2022-09-01 20:53:47

字符数组的默认值给出一个空指针异常...谁能说出为什么这个例外只是针对字符数组...即使其他 dataype 数组的默认值为 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);
    }
}

输出:空


答案 1

打印 a 的行为与其他数组不同,因为(这是实例的类型)具有用于打印数组的特定方法 - - 而对于其他数组,则使用 s 的通用方法 - 。char[]PrintStreamSystem.outcharpublic void println(char x[])Objectpublic 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[])在向它传递引用时抛出 。NullPointerExceptionnull

public void println(char x[])调用哪些调用 ,其中抛出的 when 被计算:public void print(char s[])public void write(char buf[])NullPointerExceptionbuf.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;
  }
}

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

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

打印一个字符数组。这些字符根据平台的默认字符编码转换为字节,并且这些字节完全按照 write(int) 方法的方式写入。

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


答案 2

第一个是使用,第二个是使用内部使用和打印而不是println(char[] x)println(Object obj)String.valueOf(x)nullNullPointerException

检查String.valueOf()

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

并且根据java文档将抛出如果是.println(char[] x)NullPointerExceptionchar[] arrnull