0

I cant under stand when do i use equals() and when do i use == in java

21st Jun 2017, 6:46 PM
Ishaq Za'rour
5 Réponses
+ 4
Generally, use == for primitive data-types. Use .equals() for Objects. Primitive data-types in java are luckily easy to see as they have a lower case letter in the front. Primitives: int, double, long, short, byte, boolean, float, and char.
21st Jun 2017, 7:03 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Usually we use == to get a Boolean. But recently I have learned that: String s1 = "myString"; String s2 = new String("myString"); s1 == s2. ---> False. Shocking right? In this case we would use s1.equals(s2); ---> True.
21st Jun 2017, 6:57 PM
Limitless
Limitless - avatar
+ 1
== is to compare the object/primitive in memory .equals() is for comparing the value. Basically, if you want to compare Strings or other non-primitives use .equals(). For primitives use ==.
21st Jun 2017, 6:58 PM
Jonathan S
Jonathan S - avatar
+ 1
thx guyz very helpful
21st Jun 2017, 7:25 PM
Ishaq Za'rour
+ 1
As far as I now, the == operator compares the reference of an object? Correct me if i'm wrong.
22nd Jun 2017, 6:20 PM
Jonas Schröter
Jonas Schröter - avatar