Consider following three statements. I. StringBuilder sb =new StringBuilder("OCAJP");II. StringBuilder sb0 =new StringBuilder("OCAJP ");III. String s =new String ("OCAJP");Which of the following will result true?*sb == sb0s.equals(sb)sb.equals(sb0)sb.toString().equals(s.toString())s == sb
Question
Consider following three statements. I. StringBuilder sb =new StringBuilder("OCAJP");II. StringBuilder sb0 =new StringBuilder("OCAJP ");III. String s =new String ("OCAJP");Which of the following will result true?*sb == sb0s.equals(sb)sb.equals(sb0)sb.toString().equals(s.toString())s == sb
Solution
The correct answer is sb.toString().equals(s.toString()).
Here's why:
-
sb == sb0: This is false becausesbandsb0are two different objects in memory. -
s.equals(sb): This is false becausesis a String andsbis a StringBuilder. The equals() method checks for equality of the values and the types. Since the types are different, this will return false. -
sb.equals(sb0): This is false because StringBuilder does not override the equals() method from the Object class. Therefore, it uses the Object's equals() method, which
Similar Questions
Which of the following are output by the following code? (Choose all that apply)public class StringBuilders { public static StringBuilder work(StringBuilder a, StringBuilder b) { a = new StringBuilder("a"); b.append("b"); return a; } public static void main(String[] args) { StringBuilder s1 = new StringBuilder("s1"); StringBuilder s2 = new StringBuilder("s2"); StringBuilder s3 = work(s1, s2); System.out.println("s1 = " + s1); System.out.println("s2 = " + s2); System.out.println("s3 = " + s3); } }*A. s1 = aB. s1 = s1C. s2 = s2D. s2 = s2bE. s3 = aF. s3 = nullG. The code does not compile.
Which of these method of String class can be used to test to strings for equality?ans.isequal()equals()isequals()equal()
State whether the following is true or false:When String objects are compared using ==, the result is true if the Strings containthe same values.a.Falseb.True
What is the output of the following code snippet? String str1 = "Java"; String str2 = new String("Java"); System.out.println(str1 == str2);
Find the output of the below Java program?public class Test { public static void main(String[] args) { Test t1 = new Test(); Test t2 = t1; System.out.println(t1.equals(t2)); }}A) trueB) falseC) nullD) error
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.