Friday, 30 September 2011

Interesting part of Java equality

public class JavaEqualty {
    public static void main(String[] args) {
        //-----------------------------------------
        // java language specification 3.0 $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.
        //-----------------------------------------
        /* auto-boxing */
        Integer int1 = 2;
        Integer int2 = 2;
        // print 'true'
        System.out.println(int1 == int2);

        Integer int3 = 200;
        Integer int4 = 200;
        // print 'false'
        System.out.println(int3 == int4);
        //------------------------------------------
        Integer int5 = new Integer(0);
        Integer int6 = new Integer(0);
        // The two objects are both equal to 0
        System.out.println(int5 == 0 && int6 == 0);
        // But they are not equal to each other
        System.out.println(int5 == int6);
        //print 'true', relational ops unboxing both sides
        System.out.println(int5 <= int6 && int5 >= int6);

        //-----------------------------------------
        // java language specification 3.0 $15.21.2 Boolean Equality
        // Operators == and !=
        //
        // If the operands of an equality operator are both of type
        // boolean, or if one operand is of type boolean and the
        // other is of type Boolean, then the operation is boolean
        // equality. The boolean equality
        // operators are associative.
        //
        // If one of the operands is of type Boolean it is subjected
        // to unboxing conversion
        //-----------------------------------------
        Boolean b1 = new Boolean(true);
        boolean b2 = true;
        // print 'true'
        System.out.println(b1 == b2);

        Boolean b3 = new Boolean(true);
        Boolean b4 = new Boolean(true);
        // print 'false', they are not equal to each other
        System.out.println(b3 == b4);
    }
}

No comments:

Post a Comment