Tuesday 29 October 2013

Difference between == and .equals in java

package com.karthik;

/**
* @author karthik
*
*/
public class SimpleDifference {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "karthik";
String name1 = "karthik";
String a = new String("karthi");
String b = new String("karthi");
/*
* In Java, when the “==” operator is used to compare 2 objects, it
* checks to see if the objects refer to the same place in memory. In
* other words, it checks to see if the 2 object names are basically
* references to the same memory location. A very simple example will
* help clarify this:
*/
if (name == name1) {
System.out.println("success");// compare the memory location
} else {
System.out.println("failure");
}

if (a == b) {
System.out.println("success1");
} else {
System.out.println("failure1");//compare the memory location
}

/*
* Now that we’ve gone over the “==” operator, let’s discuss the
* equals() method and how that compares to the “==” operator. The
* equals method is defined in the Object class, from which every class
* is either a direct or indirect descendant. By default, the equals()
* method actually behaves the same as the “==” operator – meaning it
* checks to see if both objects reference the same place in memory.
* But, the equals method is actually meant to compare the contents of 2
* objects, and not their location in memory.
*/
if (name.equals(name1)) {
System.out.println("success2");//compare the contents of 2 objects
} else {
System.out.println("failure2");
}

if (a.equals(b)) {
System.out.println("success3");//compare the contents of 2 objects
} else {
System.out.println("failure3");
}

}



}

No comments:

Post a Comment