Forums Register Login
Confusion with == and equals.
why doesn't this code is giving "here" as output? If I am using equals rather than == operator it is giving output "here"?
The == operator checks if the two operands on the left and right side of the == refer to the exact same object. It does not check if the content of the objects is the same. So, if you have two separate String objects, then == will return false, even if the two String objects have the same content.

Using == instead of equals() to compare strings is a very well-known mistake that almost everybody makes when learning Java.
==:Comparison of the two variable itself value--Two objects first address in memory.
equals():The comparison of strings have the same content
so it is sure !

let us make friends! let us together to learn java
Hi Gautam,

I think there is one more confusion here. Please note that

String s1=Thread.currentThread().getName();

will give you the name of current thread which is "main" and not Thread1 which i think you are assuming.
And regarding == so it is should be used for comparing references and not the content and if you want to check for equality then you should use equals(Object anObject)method.
However you will notice that in some cases == returns correct result, which is again due to another concept known as String Pooling in Java. For e.g:-
Suppose you have 2 strings declared as,
String s1 = "testString";
String s2 = "testString";

In this case s1==s2 will return true and which is because of String Pooling.
But i would say the best practice to check for equality should be using public boolean equals(Object anObject) method.
think of reference variables as notecards that hold the address of a house. Objects are the actual house. so, a variable holds the address of the object.

when you use ==, you are saying "Do these two notecards have the EXACT SAME ADDRESS written down on them?" In other words, if you went to the address on one, and I went to the address on the other, would we bump into each other?

when you use .equals, you are saying "Are the houses at these addresses basically the same?". Your address may be in Cleveland, and mine may be in St. Louis, but if the builder used the same blueprint, painted all the rooms the same colors, and put the same furniture in each, then yes, they are. However, if yours is a split-level and mine is a ranch, then no they are not.
Have a look at the Campfire Story Cup Size for a detailed description of how variables work in Java.

This thread has been viewed 630 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 10, 2018 10:06:58.