char和int数组的区别 [英] char and int array difference

查看:433
本文介绍了char和int数组的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试打印未初始化的静态字符数组时,它会给出运行时错误(空指针异常),而未初始化的静态int数组会给出空值。为什么?

When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array gives null value. Why?

public class abc {
    static int arr[];
    static char ch[];

    public static void main(String[] args) {
        System.out.println(ch); //it gives null pointer exception at run time
        System.out.println(arr); //it gives output as "null".
        }
    }


推荐答案

System.out PrintStream 的一个实例,这个类有一些重载 println 方法。在您的情况下:

System.out is an instance of PrintStream and this class has a few overloaded println methods. In your case:


  1. System.out.println(ch); 正在使用 public void println(char x [])

  2. System.out.println(arr); 正在使用 public void println(Object x)(没有 public void println(int [] x)方法所以 int [] 最接近的可用类型 println 可以使用的是对象)。

  1. System.out.println(ch); is using public void println(char x[])
  2. System.out.println(arr); is using public void println(Object x) (there is no public void println(int[] x) method so the closest available type for int[] which println can use is Object).

第二种方法是使用

String.valueOf(x);

获取我们要打印的对象的字符串表示以及<$ c $的代码c> valueOf 方法看起来像

to get a string representation of the object we want to print and the code of the valueOf method looks like

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

所以它是空的安全(将返回字符串null如果引用保持 null )。

so it is null-safe (will return the string "null" if the reference holds null).

第一种方法是在某种程度上使用

The first method is at some level using

public void write(char cbuf[]) throws IOException {
    write(cbuf, 0, cbuf.length);
                 //    ^^^^^^^ this throws NPE
}

因为 cbuf null cbuf.length 将抛出NullPointerException因为 null 没有长度(或任何其他)字段。

and because cbuf is null cbuf.length will throw NullPointerException because null doesn't have length (or any other) field.

这篇关于char和int数组的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆