Compare two objects with .equals() and == operator

前端 未结 15 1556
礼貌的吻别
礼貌的吻别 2020-11-22 01:13

I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too

15条回答
  •  醉梦人生
    2020-11-22 01:37

    The "==" operator returns true only if the two references pointing to the same object in memory. The equals() method on the other hand returns true based on the contents of the object.

    Example:

    String personalLoan = new String("cheap personal loans");
    String homeLoan = new String("cheap personal loans");
    
    //since two strings are different object result should be false
    boolean result = personalLoan == homeLoan;
    System.out.println("Comparing two strings with == operator: " + result);
    
    //since strings contains same content , equals() should return true
    result = personalLoan.equals(homeLoan);
    System.out.println("Comparing two Strings with same content using equals method: " + result);
    
    homeLoan = personalLoan;
    //since both homeLoan and personalLoan reference variable are pointing to same object
    //"==" should return true
    result = (personalLoan == homeLoan);
    System.out.println("Comparing two reference pointing to same String with == operator: " + result);
    

    Output: Comparing two strings with == operator: false Comparing two Strings with same content using equals method: true Comparing two references pointing to same String with == operator: true

    You can also get more details from the link: http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1

提交回复
热议问题