KnowledgeBoat Logo
|

Computer Applications

Given the code

String s1 = "yes" ;
String s2 = "yes" ;
String s3 = new String(s1) ;

Which of the following would equate to False ?

  1. s1 == s2
  2. s3 == s1
  3. s1.equals(s2)
  4. s3.equals(s1)

Java String Handling

10 Likes

Answer

s3 == s1

Reason — Each of the four comparisons are explained below:

  1. The first comparison uses the == operator to compare s1 and s2. == operator checks for reference equality, i.e., whether both variables refer to the same object in memory. Since s1 and s2 have the same value and were created using the same string literal, they will refer to the same object in memory. Therefore, this comparison returns true.
  2. The second comparison uses the == operator to compare s3 and s1. Since s3 was created using the new keyword and is therefore a different object in memory than s1, this comparison returns false.
  3. The third comparison uses the equals method to compare s1 and s2. This method checks for value equality, i.e., whether both objects have the same value regardless of their memory location. Since s1 and s2 have the same value, this comparison returns true.
  4. The fourth comparison uses the equals method to compare s3 and s1. This method also checks for value equality, so it returns true because s3 and s1 have the same value, even though they are different objects in memory.

Answered By

4 Likes


Related Questions