How does the toString(), ==, equals() object methods work differently or similarly on reference and primitive types?

后端 未结 3 780
不知归路
不知归路 2020-12-11 04:49

How does the toString() method, == operator, and equals() method work differently or similarly on reference and primitive types?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 05:31

    For reference types, == will compare the actual reference (where in memory the object resides) where as the equals method performs a comparison of the data.

    The JVM will sometimes "String intern" your immutable strings for performance reasons. Causing this:

    String a = "abc";
    String b = "abc";
    if (a == b){ 
        //The if statement will evaluate to true, 
        //if your JVM string interns a and b, 
        //otherwise, it evaluates to false. 
    }
    

    http://en.wikipedia.org/wiki/String_interning

提交回复
热议问题