本章提到的关于==的部分,一个完整的实验如下:
1 class Test { 2 public static void main(String[] args) { 3 Integer i = new Integer(47); 4 Integer j = new Integer(47); 5 Integer i1 = 47; 6 Integer j1 = 47; 7 int i2 = new Integer(47); 8 int j2 = new Integer(47); 9 int i3 = 47; 10 int j3 = 47; 11 12 System.out.println( i == j ); //false 13 System.out.println( i1 == j1 ); //true 14 System.out.println( i2 == j2 ); //true 15 System.out.println( i3 == j3 ); //true 16 System.out.println( i1 == j2 ); //true 17 System.out.println( i1 == j3 ); //true 18 System.out.println( i2 == j3 ); //true 19 20 String s = new String("java"); 21 String s1 = new String("java"); 22 String s2 = "java"; 23 String s3 = "java"; 24 System.out.println( s == s1 ); //false 25 System.out.println( s2 == s3 ); //true 26 } 27 }
还有一点:虽然局部变量在定义之后必须初始化,否则会编译出错。但是对于数组,行为却不一样:
1 class Test { 2 public static void main(String[] args) { 3 int i = 7; 4 System.out.println("i = " + i); 5 6 int[] a = new int[10]; 7 System.out.println("a[0] = " + a[0]); //0 8 } 9 }