源码:
public class Example{
String str;
char[] ch;
public static void main(String[] args){
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.print(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]= 'g';
}
}
main 函数没有问题报的是空指针异常
public class Example{
String str="ds";
char[] ch={'a','b'};
public static void main(String[] args){
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.print(ex.ch);
}
public void change(String str,char ch[]){
this.str="test ok";
this.ch[0]= 'g';
}
}
ex.change(ex.str,ex.ch);
其中ex对象是刚刚创建的,他的局部变量str和ch的值为null;
当你执行this.ch[0]= 'g';时就会报空指针错误了;
因为ch是数组,ch[0]是数组中的第一个元素。
它就相当于:list.get(0);其中list为null;典型的空指针
你怎么能在Example类里面new Example ,直接用ex.change(str,ch);就行了啊