Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Tuesday, January 27, 2009

Difference Between equals() and ==

/**

* Please write a program to state the difference between .equals and ==

*

* @author Ritesh

*

*/

public class Equals {

// used for checking object

private int intNum;

/**

* constructor to initialize member variables

*

* @param no

* sets member variable

*/

Equals(int no) {

// sets intNum

setIntNum(no);

}

/**

* overriding method Object class for equal operation

*/

public boolean equals(Object obj) {

// check if input obj is null

if (obj == null)

return false;

// check if obj is instance of Equals

if (obj instanceof Equals) {

if (((Equals) obj).getIntNum() == getIntNum())

return true;

}

return false;

}

/**

* returns intNum value

*

* @return intNum

*/

public int getIntNum() {

return intNum;

}

/**

* sets intNum value

*

* @param intNum

* sets intNum

*/

public void setIntNum(int intNum) {

this.intNum = intNum;

}

/**

* execution begin from here

*

* @param args

* commandlline arguments

*/

public static void main(String[] args) {

equalsDemo();

}

public static void equalsDemo() {

// creating object 1 of Equals

Equals eqObj1 = new Equals(1);

// creating object 2 of Equals

Equals eqObj2 = new Equals(1);

// creating reference variables and sets it to reference object 1

Equals eqTemp = eqObj1;

// checking eqObj1 and eqObj2

System.out.println("Checking eqObj1 and eqObj2 :: ");

if (eqObj1 == eqObj2)

System.out.println("eqObj1 and eqObj2 references to single object");

else

System.out

.println("eqObj1 and eqObj2 references to different objects");

if (eqObj1.equals(eqObj2))

System.out.println("eqObj1 and eqObj2 have same values");

else

System.out.println("eqObj1 and eqObj2 have different values");

// checking eqObj1 and eqTemp

System.out.println("\nChecking eqObj1 and eqTemp :: ");

if (eqObj1 == eqTemp)

System.out.println("eqObj1 and eqTemp references to single object");

else

System.out

.println("eqObj1 and eqTemp references to different objects");

if (eqObj1.equals(eqTemp))

System.out.println("eqObj1 and eqTemp have same values");

else

System.out.println("eqObj1 and eqTemp have different values");

}

}

No comments:

Post a Comment

Followers