ICSE Class 10 Computer Applications
Question 36 of 36
String Handling — Question 4
Back to all questions 4
Question Question 4
Given the code
String s1 = "yes" ;
String s2 = "yes" ;
String s3 = new String(s1) ;Which of the following would equate to False ?
- s1 == s2
- s3 == s1
- s1.equals(s2)
- s3.equals(s1)
s3 == s1
Reason — Each of the four comparisons are explained below:
- The first comparison uses the
==operator to compares1ands2.==operator checks for reference equality, i.e., whether both variables refer to the same object in memory. Sinces1ands2have the same value and were created using the same string literal, they will refer to the same object in memory. Therefore, this comparison returnstrue. - The second comparison uses the
==operator to compares3ands1. Sinces3was created using thenewkeyword and is therefore a different object in memory thans1, this comparison returnsfalse. - The third comparison uses the
equalsmethod to compares1ands2. This method checks for value equality, i.e., whether both objects have the same value regardless of their memory location. Sinces1ands2have the same value, this comparison returnstrue. - The fourth comparison uses the
equalsmethod to compares3ands1. This method also checks for value equality, so it returnstruebecauses3ands1have the same value, even though they are different objects in memory.