Computer Applications
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)
Java String Handling
10 Likes
Answer
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.
Answered By
4 Likes
Related Questions
The length of a String object s1 can be obtained using the expression s1 length. (T/F)
Which of the following methods belong to the String class ?
- length()
- compareTo()
- equals()
- substring()
- All of these
- None of them
Suppose that s1 and s2 are two strings. Which of the statements or expressions are incorrect ?
- String s3 = s1 + s2;
- String s3 = s1 - s2;
- s1.compareTo(s2);
- int m = s1.length( );
Given the code :
String s = new String("abc");Which of the following calls are invalid ?
- s.trim( )
- s.replace('a', 'A')
- s.substring(3)
- s.toUpperCase( )
- s.setCharAt(1, 'A')