This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Friday, January 15, 2010

15 - two ways to compare - level basic - Java 1.6.0_17 - NB 6.8

A) equals IS NOT OVERRIDDEN



public class Class1 {
    int value;
    Class1() {

    }
    Class1(int value) {
        this.value = value;
    }
}

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        System.out.println("ref1Class1 and ref2Class1");
        Class1 ref1Class1 = new Class1();
        Class1 ref2Class1 = ref1Class1;
        if(ref1Class1.equals(ref2Class1)) {
            System.out.println("Objects are equal");
        } else {
            System.out.println("Objects are not equal");
        }
        if(ref1Class1 == ref2Class1) {
            System.out.println("Objects are ==");
        } else {
            System.out.println("Objects are not ==");
        }

        System.out.println("ref3Class1 and ref4Class1");
        Class1 ref3Class1 = new Class1(5);
        Class1 ref4Class1 = new Class1(5);
        if(ref3Class1.equals(ref4Class1)) {
            System.out.println("Objects are equal");
        } else {
            System.out.println("Objects are not equal");
        }
        if(ref3Class1 == ref4Class1) {
            System.out.println("Objects are ==");
        } else {
            System.out.println("Objects are not ==");
        }

    }

}

run:
ref1Class1 and ref2Class1
Objects are equal
Objects are ==
ref3Class1 and ref4Class1
Objects are not equal
Objects are not ==



B) equals IS OVERRIDDEN



    public boolean equals(Object objectToCompare) {
        return this.value == ((Class1)objectToCompare).value;
    }

run:
ref1Class1 and ref2Class1
Objects are equal
Objects are ==
ref3Class1 and ref4Class1
Objects are equal
Objects are not ==

This is Java for Beginners and you should understand the meaning of these example by yourself... :-)




No comments:

Post a Comment

Followers