char配列をnullで初期化するとprintできない件

byteの配列と、charの配列をnullで初期化してそれを
printlnで表示させようとすると、Java内部では
以下のような形でメソッドの呼び出しが行なわれる。

そのため、byteの場合はエラーにならないが、
charの場合はNullPointerExceptionが発生する。

◆byte

⇒PrintStream.class - println(Object x)

   public void println(Object x) {
       String s = String.valueOf(x);
       synchronized (this) {
           print(s);→→→→
           newLine();
       }
   }

⇒PrintStream.class - print(String s)

   public void print(String s) {
       if (s == null) {
           s = "null";
       }
       write(s);→→→→
   }

⇒PrintStream.class - write(String s)

   private void write(String s) {
       try {
           synchronized (this) {
               ensureOpen();
               textOut.write(s);→→→→
               textOut.flushBuffer();
               charOut.flushBuffer();
               if (autoFlush && (s.indexOf('\n') >= 0))
                   out.flush();
           }
       }
       catch (InterruptedIOException x) {
           Thread.currentThread().interrupt();
       }
       catch (IOException x) {
           trouble = true;
       }
   }

⇒Writer.class - write(String str)

   public void write(String str) throws IOException {
       write(str, 0, str.length());→→→→OK!
   }


◆char
⇒PrintStream.class - println(Object x)

   public void println(Object x) {
       String s = String.valueOf(x);
       synchronized (this) {
           print(s);→→→→
           newLine();
       }
   }

⇒PrintStream.class - print(char s[])

  public void print(char s[]) {
       write(s);→→→→
   }

⇒PrintStream.class - write(char buf[])

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

⇒Writer.class - write(char cbuf[])

   public void write(char cbuf[]) throws IOException {
       write(cbuf, 0, cbuf.length);→→→→エラー!!
   }




String str1 = String.valueOf(b);
System.out.println(str1);
String str = String.valueOf(c);
System.out.println(str);

と、コードを追加。
byteとcharでは、呼び出されるvalueOfメソッドが違うことが
わかった。

String.class

★byte[] の場合

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

★char[] の場合

   public static String valueOf(char data[]) {
       return new String(data);
   }




char[]は、nullとの比較ができないのか!?

if (c==null) {
        System.out.println("Hello, World!");
}

とやると、「Hello, World!」と表示されるので、それはないらしい。



タグ:

+ タグ編集
  • タグ:
最終更新:2012年12月11日 09:30