3

Possible Duplicate:
Why are these == but not equals()?

I know in Java, "==" is used to compared reference not values while "equals" to is used to compare values.

Then if

int a=100;
int b=100;
boolean c=(a==b);

Then c will be false? But I remember in my previous project, it seems to be true....

Community
  • 1
  • 1
Hao Shen
  • 2,395
  • 2
  • 34
  • 66
  • equals compare references when you have objects. – Renato Lochetti Sep 20 '12 at 20:26
  • The most common mistake is to use == for Strings, which is not correct because String is not a primitive type. (All datatypes that by default have boldtext in Eclipse is primitive) – Simon Forsberg Sep 20 '12 at 20:29
  • @Simon André Forsberg I see. So Strings and other kind of classes are not primitive. Types like int are primitive:> – Hao Shen Sep 20 '12 at 20:32
  • int, double, float, boolean... and more are primitive. Primitive types are not classes. See the answer by Jake King for more information on which data types are primitive. – Simon Forsberg Sep 20 '12 at 20:34

4 Answers4

8

c is true, because you're comparing primitives, not references. == compares primitives by value (since the value is all you've got).

3

Using == works on all primitive data types to compare values, since primitives do not contain references. Objects contain object references instead, so using == compares those instead.

The int value of 100 does equal 100, so c will be true.

Alexis King
  • 41,872
  • 14
  • 128
  • 201
1

c will be true because a and b are primitives and their values are same.

kosa
  • 64,776
  • 13
  • 121
  • 163
1

Integers are value types. So in this case it just compares the values, so c will be true.

Forte L.
  • 2,742
  • 15
  • 25