Monday, 30 December 2013

Most frequently asked interview question on String in java

Most frequently asked interview question on String in java

 Here we describe difference between (==) and .equals() :-

Both of them very much differ in their significance and working as equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.
Let us see an example we have two String objects and they are being pointed by two different reference variables as a1 and a2.

 a1 = new String("xyz");
 a2 = new String("xyz");
Now, if you use the "equals()" method to check for their equivalence as

      System.out.println("a1.equals(a2) is TRUE");
      System.out.println("a1.equals(a2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.
Lets check the '==' operator..

     System.out.printlln("a1==a2 is TRUE");
     System.out.println("a1==a2 is FALSE");
Now you will get the FALSE as output because both a1 and a2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.
Try running the program without 'new String' and You will get TRUE for both the tests. 

   String a1 = "xyz";
   String s2 = "xyz";


Posted By:M@ndeep R@w@t

Read More
Posted on 12:23:00 am