Java - Interview Questions and Answers on String Comparison

Q1.  Difference between == and .equals() ?

Ans. "equals" is the member of object class which returns true if the content of objects are same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

Q2.  What will this code print ?

String a = new String ("TEST");
String b = new String ("TEST");

if(a == b) { 
       System.out.println ("TRUE"); 
} else {
       System.out.println ("FALSE"); 
}

Ans. FALSE. 

== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content. 

Q3.  public class a {
     public static void main(String args[]){
          final String s1="job";
          final String s2="seeker";
          String s3=s1.concat(s2);
          String s4="jobseeker";
          System.out.println(s3==s4); // Output 1
          System.out.println(s3.hashCode()==s4.hashCode()); Output 2
     }
}

What will be the Output 1 and Output 2 ?

Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.