Java豆知識 その1

class Boxing {

    static void sample1() {
	Integer i1 = 100;
	Integer i2 = 100;
    
	if (i1 == i2)
	    System.out.println(i1 + " == " + i2);

	if (i1.equals(i2))
	    System.out.println(i1 + " equals " + i2);
    }	

    static void sample2() {
	Integer i1 = 200;
	Integer i2 = 200;
    
	if (i1 == i2)
	    System.out.println(i1 + " == " + i2);

	if (i1.equals(i2))
	    System.out.println(i1 + " equals " + i2);
    }	

    public static void main(String[] args) {
	System.out.println("sampel1");
	Boxing.sample1(); 

	System.out.println("sampel2");
	Boxing.sample2(); 
    }

}

sample1ではi1==i2となるが、sample2ではi1==i2が成り立たない。何故そうなるかは「5.1.7 Boxing Conversion」の最後に書かれている。

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.