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,605
  • 3
  • 37
  • 68
  • 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).

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • technically, == compares objects by value too. it just so happens that an object's value is memory location (ie. reference). Hence why java is also always pass by value (and never pass by reference). – Matt Sep 21 '12 at 16:39
  • @Matt: agreed, the references are passed by value. – Nathan Hughes Sep 21 '12 at 16:54
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
  • 43,109
  • 15
  • 131
  • 205
1

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

kosa
  • 65,990
  • 13
  • 130
  • 167
1

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

Forte L.
  • 2,772
  • 16
  • 25