thinkinterview » interview questions
« Previous

interview Questions

next »
question

What is the difference between == and ‘equals’ operator?

Answer Description: The == operator compares two objects to determine whether they are the same object in memory i.e. present in the same memory location or not. It is possible for two String objects to have the same value, but located in different areas of memory.== operator compares references while ‘.equals’ operator compares the contents. The method public boolean equals (Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
 public class TestEquals {
               
               public static void main(String[] args) {
 
                               String s1 = "xyz";
                               String s2 = s1;
                               String s5 = "xyz";
                               String s3 = new String("xyz");
                               String s4 = new String("xyz");
                               System.out.println("== comparison : " + (s1 == s5));
                               System.out.println("== comparison : " + (s1 == s2));
                               System.out.println("equals method : " + s1.equals(s2));
                               System.out.println("== comparison : " + s3 == s4);
                               System.out.println("equals method : " + s3.equals(s4));
               }
}

Output
== comparison : true
== comparison : true
equals method : true
== comparison : false
equals method : true



Next Queston » What is oracle thin driver and why is it named so?...
What is oracle thin driver and why is it named so?View full queston »

Posted in: Java(30) |