• Post Reply Bookmark Topic Watch Topic
  • New Topic

The "==" operator  RSS feed

 
C Law
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm new to Java.

I think the following code should output false.

public class Test{
public static void main(String[] args){
int a = 1;
int b = 1;
System.out.println(a == b);
}
}

In reality, it produces true. If a and b were objects,
the result would be false. But a and b here as integers
should have different addresses, meaning the "==" operator
should see they are equal in content but different in
address and returns false.

Any comment is welcome. Thanks.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the == when used between primitives tests their values.

When the == operator is used between object references, it tests whether or not they point to the same object.
[ March 05, 2006: Message edited by: Keith Lynn ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi "C",

Welcome to JavaRanch!

Keith is right, but his statement actually doesn't go far enough.

The equals operator always compares values.

If a variable refers to an object, its value is a reference to the object. "==" returns false if two objects are distinct because these references will be, of course, not the same.

If a variable is a primitive type, then its value is its value. "==" still compares precisely what the variable contains, but in this case, the variable contains the primitive's actual value.

See these two entertaining stories and this will all be crystal clear.
 
C Law
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies.
I think I mistakened "reference" for
"memory address", a side effect of
learning C
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good reply and examples Earnest.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!