You Don't know JAVA #EP5

Case 1(StringBuffer):

    public class Main{

    public static void main(String ... args){

    StringBuffer sb1= new StringBuffer("EP5");
    StringBuffer sb2= new StringBuffer("EP5");
    System.out.println(sb1==sb2);
    System.out.println(sb1.equals(sb2));

    }
}

Guess the Answer:

1. true true

2. false false

3. false true

4. true false

Answer: false false

if(gotIt())
  readBlog();
else
  readBlog();

Before Entering into blog you should know some of the things

  1. == operator check references
  2. equals() method of Object class also check reference
  3. You can override equals() method to check the content(data inside the object).
  4. We can override equals() method Because all classes parent is Object and we can override Parent class method into child class according to RunTime Polymorphism concept(Method Overriding)

Guess This Question Before Moving to the answer Explanation

Case 2(String):

public class Main{

    public static void main(String ... args){

    String s1= new String("EP5");
    String s2= new String("EP5");
    System.out.println(s1==s2);
    System.out.println(s1.equals(s2));

    }
}

Guess the Answer:

1. true true

2. false false

3. false true

4. true false

Answer: false true

Now the Explanation of answer will be the difference between Case 1(StringBuffer) and Case 2(String):

String and StringBuffer both are child of Object class which has 11 methods and one of them is equals and equals method check reference but String class override equals() method to check the content(data inside object) and StringBuffer didn't override.

CASE 1 Answer:

    String s1= new String("EP5");
    String s2= new String("EP5");

    System.out.println(s1==s2);//false 
    //both references are different

    System.out.println(s1.equals(s2));false 
    //here String class equals method calling to check content

CASE 2 Answer:

StringBuffer sb1= new StringBuffer("EP5");
StringBuffer sb2= new StringBuffer("EP5");

System.out.println(s1==s2);//false   
//both references are different

System.out.println(s1.equals(s2));//false 
//here StringBuffer class calls Object equals method to check ref

Summary:

  1. StringBuffer does not override equals(means object class equals method calling to check reference).
  2. String override equals(means String class equals method calling to check content(data inside object)).

Did you find this article valuable?

Support Hritik manbattulwar by becoming a sponsor. Any amount is appreciated!