package com.xujin;class Hello {
String title;
int value;
public Hello() {
title = title+ " World";
}
public Hello(int value) {
this();
this.value = value;
title += "Hello";
}
}
public class Test{
public static void main(String [] args){
Hello c = new Hello(5);
System.out.println(c.title);
String s;
//s = s + "Hello!";//The local variable s may not have been initialized
}
}我还没初始化title就用它了,居然没报错!
而s却报错了!奇怪了!stringjava
String title;
int value;
public Hello() {
title = title+ " World";
}
public Hello(int value) {
this();
this.value = value;
title += "Hello";
}
}
public class Test{
public static void main(String [] args){
Hello c = new Hello(5);
System.out.println(c.title);
String s;
//s = s + "Hello!";//The local variable s may not have been initialized
}
}我还没初始化title就用它了,居然没报错!
而s却报错了!奇怪了!stringjava
成员变量会在创建对象的时候赋值,开始赋默认值,象上面代码title为null.追溯完父类后,在执行构造方法前,再显示赋值,上面代码没有显示赋值,仍旧是null.
方法里必需声明赋值。
String title;
int value;
public Hello() {
if(title == "null") System.out.println("one");
else System.out.println("two");
if(title == null) System.out.println("three");
else System.out.println("four");
//two three
title = title+ "World";//nullWorldHello
}
public Hello(int value) {
this();
this.value = value;
title += "Hello";
}
}
public class Test{
public static void main(String [] args){
Hello c = new Hello(5);
System.out.println(c.title);
String s;
//s = s + "Hello!";//The local variable s may not have been initialized
}
}
上面代码我又加了几句,根据上面的输出
我不明白为什么会输出//nullWorldHello
title = title+ "World";
当执行这一句时,null转换成字符串"null"再连接上World