This week's book giveaways are in the Jython/Python and Object-Oriented programming forums. We're giving away four copies each of Machine Learning for Business: Using Amazon SageMaker and Jupyter and Object Design Style Guide and have the authors on-line! See this thread and this one for details.
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.
I think there is one more confusion here. Please note that
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.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors