What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3));

  1. false false false dar

  2. false true false Poddar

  3. Compiler Error

  4. true true false dar


Correct Option: A

AI Explanation

To answer this question, let's go through each line of code and analyze the output:

StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2 = new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1 == sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));
  1. StringBuffer sb1 = new StringBuffer("Amit"); creates a StringBuffer object sb1 with the value "Amit".
  2. StringBuffer sb2 = new StringBuffer("Amit"); creates another StringBuffer object sb2 with the value "Amit".
  3. String ss1 = "Amit"; creates a String object ss1 with the value "Amit".
  4. System.out.println(sb1 == sb2); compares the references of sb1 and sb2. Since they are two different objects, the comparison returns false.
  5. System.out.println(sb1.equals(sb2)); compares the contents of sb1 and sb2. Although they have the same value ("Amit"), the StringBuffer class does not override the equals method, so the comparison returns false.
  6. System.out.println(sb1.equals(ss1)); compares the contents of sb1 and ss1. They have different types (StringBuffer and String), so the comparison returns false.
  7. System.out.println("Poddar".substring(3)); extracts a substring from the string "Poddar" starting from index 3. The output is "dar".

Therefore, the correct answer is option A. The output will be:

false
false
false
dar

Find more quizzes: