More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know.
Core Java - Interview Questions and Answers for 'String comparison' - 4 question(s) found - Order By Newest
Very frequently asked. Among first few questions in almost all interviews. Among Top 5 frequently asked questions. Frequently asked in Indian service companies (HCL,TCS,Infosys,Capgemini etc based on multiple feedback ) and Epam Systems
Ans. "equals" is the method of object class which is supposed to be overridden to check object equality, whereas "==" operator evaluate to see if the object handlers on the left and right are pointing to the same object in memory.
x.equals(y) means the references x and y are holding objects that are equal. x==y means that the references x and y have same object.
Sample code:
String x = new String("str");
String y = new String("str");
System.out.println(x == y); // prints false
System.out.println(x.equals(y)); // prints true
Q2. 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
}
}
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.
Help us improve. Please let us know the company, where you were asked this question :
Just like Strings, java maintains an integer constant pool too. So 1 will be maintained in integer constant pool and hence reference int2 will point to same integer in pool.
String pool is only for string literals ( defined by "" ) and not for newly created objects and hence str1 == str2 will return false as they are separate objects in memory.
String pool is used for storing string literals so that they can be reused and str3 and str4 will point to same string literal in string pool.
Help us improve. Please let us know the company, where you were asked this question :
LikeDiscussCorrect / Improve  string pool  integer constant pool  string comparison  integer comparison