What will be the output of the following code?

class Main {
  public static void main (String[] args) {
    String str = "hello";
    StringBuffer sb = new StringBuffer(str);
    System.out.print(sb.equals(str) + "," + str.equals(sb));
  }
}
Explanation
In both cases, we are comparing non-null reference values of different types, hence the result will be false.
The StringBuffer class does not override the equals method, hence it uses the restrictive Object.equals() method, which returns true only if comparing references to the same object in memory.
The String class does override the equals method, but a toString() method is not automatically called on sb variable, hence the result is also false.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback