-4

I know this: When you use == to compare two objects it will compare the two instances of the object and check if they are the equal. When you use .equals() it will compare the states of the 2 objects.

Let's say this is my code:

String string1 = new String("abc");
String string2 = new String("abc");
Integer integer1 = new Integer(5);
Integer integer2 = new Integer(5);
int int1 = new Integer(6);
int int2 = new Integer(6);

if (string1 == string2)
    System.out.println("The strings are equal");
if (integer1 == integer2)
    System.out.println("The integers are equal");
if (int1 == int2)
    System.out.println("The ints are equal");

Why will this code only print "The ints are equal"?

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • 7
    Everyone on the milky way galaxy, stop asking this question. – Maroun Mar 09 '14 at 11:36
  • 2
    Try it with Integers greater than 127... – BobTheBuilder Mar 09 '14 at 11:37
  • == operator checks for object reference in case of Object such as String, Integer but for primitive it checks for their value. Use `equals` to check for object value equality. – Braj Mar 09 '14 at 11:38
  • 1
    @MarounMaroun And stop answering it over and over too! – devnull Mar 09 '14 at 11:38
  • 2
    @whoAmI hit the nail on the head. If you try with Integers greater 127, you have a greater chance of running into the same problem as other reference variables because the objects have a greater chance of not being `==`. – Hovercraft Full Of Eels Mar 09 '14 at 11:42

4 Answers4

1

Because the value of an object is the memory location which holds the object values, and the value of primitive types is its value itself. If you're using == on objects of type String for example, you are comparing their memory locations.

Alexander Cogneau
  • 1,286
  • 4
  • 12
  • 25
0

== compares references because string is an Reference type while int is a value type.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
0

That's because in Java strings are objects, and objects will only be equal if their reference is. (They are the same object)

Jeroen
  • 15,257
  • 12
  • 59
  • 102
0

For string, you have to use equals() instead of == because it is an object.

Scott
  • 21,211
  • 8
  • 65
  • 72