This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String comparison and String interning in Java
I have small doubt regarding String comparisons in Java, consider the following code:
if("String".replace('t','T') == "String".replace('t','T')) {
System.out.println("true");
}
else {
System.out.println("false");
}
The above code always print's false, where as if I try like this:
if("STring" == "STring") {
System.out.println("true");
}
else {
System.out.println("false");
}
It will always print me true. Yes, I know String comparisons should be done with String.equals() or equalsIgnoreCase() method. But this is one of the question was asked in interview and I am confused. Can anyone guide me on this behavior?
As per my knowledge, in code snippet 1, "String.replace('t','T') is returning object, so object comparisons returns in false. Am I right?
"String.replace('t','T') is returning object, so object comparisons
returns in false. Am I right?
Yes, as for this case, you are right. String#replace(or any method of String class for that matter), will return a new String object (You can guess why? Immutability). And thus you would have to do the comparison using equals method, to compare their contents.
Now, in the second case: -
"STring" == "STring"
You are comparing two string literals. Now, since String literals are interned in Java, so both the literals are same (in the sense, they point to the same memory location), and hence == comparison gives you true.
The difference in comparison using == and equals is that, == compares the reference value - i.e value of memory location of objects, which will be different for two different string objects, as you are having in first case. Whereas, equals compares the actual content in those objects.
"String.replace('t','T') is returning object, so object comparisons
returns in false. Am I right?
Yes, == compares object references, and your first code is comparing two different objects.
As far as the second code is concerned its due to string interning.
ok lets do it like this, your both String objects "String" are referering to the same object.
So they are "basicly" equal. That is a thing the compiler does for you
but the method replace, does create and return a new String object, and that is why your second code is not equal.
Java always compares the basic types (int, byte, etc) or references for objects when using ==.
The java compiler optimizes the two string constants you entered to use the same object, thus the same reference, thus the == return true
DO this way
("String".replace('t','T').Tostring() == ("String".replace('t','T')).ToString()
This will solve your problem because the replace statement should be converted to string before eveluation.
You can also user the String.Equals for this or better you use ignore case as you mention in your question.
Try this:
if(string1.equals(string2)){
...
}
Related
This question already has answers here:
two unequal objects with same hashcode
(9 answers)
Closed 6 years ago.
public static void main(String[] args) {
String str1 = "java";
String str2 = str1.intern();
String str3 = new String(str1.intern());
System.out.println("hash1=" + str1.hashCode());
System.out.println("hash2=" + str2.hashCode());
System.out.println("hash3=" + str3.hashCode());
System.out.println("str1==str2==>>" + (str1 == str2));
System.out.println("str1==str3==>>" + (str1 == str3));
}
============================================output===>
hash1=3254818
hash2=3254818
hash3=3254818
str1==str2==>>true
str1==str3==>>false
=================================
Can anyone explain how == returns false even though s1 and s3 having same hashcode?
Despite the comments above, I suspect that you already understand that == determines if two references point to the same object (or are both null), and that you should use equals() if you want to compare two strings for data-equality.
Rather, I think what you're missing is that the hashCode() method corresponds to the equals() method in this respect; it's based on the data in an object, and in fact, it's specified that classes should always implement hashCode() in such a way that if a.equals(b), then a.hashCode() == b.hashCode(). (Of course, there's nothing in the language that enforces this.) The analogue of == that you're looking for is the System.identityHashCode() method.
However, even there it should be noted that System.identityHashCode() does not guarantee that distinct instances will have distinct identity hash codes. (It can't, because it's possible to have more than 232 objects in a JVM at the same time . . . granted, not all JVMs support that; but nothing in the Java language specification forbids it.)
In a correct implementation of equals and hashCode you have the following implications for two objects a and b (that are not null):
if a == b then also a.equals(b)
if a.equals(b) then also a.hashCode() == b.hashCode()
Both implications cannot be reversed in general.
For two Objects the == operator compares their pointer reference. So unless they are actually the exact same object it's never true.
When you do:
String a = "xyz"
while creating the string, the JVM searches in the pool of strings if there already exists a string value xyz, if so 'a' will simply be a reference of that string and no new String object is created.
But if you say:
String a = new String("xyz")
you force JVM to create a new String reference, even if "xyz" is in its pool.
and == compares the references. That's why you are getting the false result.
In Java, if one is to check if two Strings are equal, in the sense that their values are the same, he/she needs to use the equals method. E.g. :
String foo = "foo";
String bar = "bar";
if(foo.equals(bar)) { /* do stuff */ }
And if one wants to check for reference equality he needs to use the == operator on the two strings.
if( foo == bar ) { /* do stuff */ }
So my question is does the == operator have it's use for the String class ? Why would one want to compare String references ?
Edit:
What I am not asking : How to compare strings ? How does the == work ? How does the equals method work?
What I am asking is what uses does the == operator have for String class in Java ? What is the justification of not overloading it, so that it does a deep comparison ?
Imagine a thread-safe Queue<String> acting as a communication channel between a producer thread and a consumer thread. It seems perfectly reasonable to use a special String to indicate termination.
// Deliberate use of `new` to make sure JVM does not re-use a cached "EOT".
private static final String EOT = new String("EOT");
...
// Signal we're done.
queue.put(EOT);
// Meanwhile at the consumer end of the queue.
String got = queue.get();
if ( got == EOT ) {
// Tidy shutdown
}
note that this would be resilient to:
queue.put("EOT");
because "EOT" != EOT even though "EOT".equals(EOT) would be true.
What use is there for it? Not much in normal practice but you can always write a class that operates on intern()-ed strings, which can then use == to compare them.
Why it isn't overloaded is a simpler question: because there is no operator overloading in Java. (To mess things up a bit, the + operator IS sort of overloaded for strings, which was done to make string operations slightly less cumbersome. But you can argue that's just syntactic sugar and there certainly is no operator overloading in Java on the bytecode level.)
The lack of an overloaded == operator made the use of the operator much less ambiguous, at least for reference types. (That is, until the point autoboxing/unboxing was introduced, which muddies the waters again, but that's another story.) It also allows you to have classes like IdentityHashMap that will behave the same way for every object you put into it.
Having said all that, the decision to avoid operator overloading (where possible) was a fairly arbitrary design choice.
The == operator compares the reference between two objects. For example, if String x and String y refers to two different things, then the == operator will show false. However, the String.equals() method compares not if they refer to each other, but if the values (ex. "Hello", "World", etc.) are the same.
// A.java
String foo1 = "foo";
// B.java
String bar1 = "foo";
All String literals realized at compile time are added to String Constant Pool. So when you have two different String declarations in two different classes, two String objects will not be created and both foo1 & bar1 refer to the same String instance of value foo. Now that you have same String reference in two different variables, you can just check if those two strings are equal just by using == which is fast because all it does is compare the bit pattern, where as in equals() method, each character is compared and is generally used for two different String instances but same content.
In fact, if you look at equals() implementation in String class, the first check they do is Reference comparison using == because they might seem as different instances to you, but if they're String literals or if they're interned by someone else already, then all you have is a Single reference in two variables.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
// remaining code
}
Also, == is not just for Strings, it's used to compare any two bit patterns, be it primitives or references
1."=="operation of comparison are the values of the two variables are equal, for a reference type variables is expressed by the two variables in the heap memory address is the same, namely the stack have the same content.
2."equals"Whether the two operation variables represent references to the same object in the heap, i.e. whether the contents of the same.
String s = "string1"; creates 1 reference and 1 object in pool String
s1 = "string1"; creates just 1 reference and points to what s is
pointing to.
s == s1 // true
String s2 = new String("string1"); creates 1 object in heap, one in
pool and one reference.
//Since, s2 is pointing to different object so,
s2 == s // false
s1 == s // false
Problem :
So, suppose We want to check, how many unique String object is created and stored in pool by the application while it is running,
We can have a singleton object which can have all the String references stored in an array.
From the previous examples of s, s1 and s2, finally for s and s1, 1 object is created and for s2, 1 object (in total 2).
//If we use equals method, all
s.equals(s1) // gives true
s1.equals(s2) // gives true
//So, number of references present in the array of singleton object will be our
//total number of objects created which equals to 3 // doesn't match actual
//count which is 2
we can use == to check for equality of reference, so if reference is equal, we will not increment our count of unique String object in pool, and for every non equal result, we will increment the count.
here,
for
s // count = 1
s1 == s // count remains same
s2 == s // false, so count = 1 + 1 = 2
//We get total number of unique String objects created and got stored in pool using ==
Simple answer...
Why would one want to compare String references ?
Because they want to compare String values in a very fast way.
Strings are not always interned(). String constants are, but it is possible that the string was created manually on the heap. Using the intern() on a manually created string allows us to to continue using reference comparison on our strings for value comparison.
What is the justification of not overloading it, so that it does a deep comparison ?
Because Java does not have operator overloading as a design decision
Operator '==' is a reference operator always, and equals() is a value method always. In C++ you can change that, but many feel that simply obfuscates the code.
Checking references is Faster compared to checking the entire Strings' equality.
Assume you have Large Strings (URLs or DBMS queries), a have multiple references to them. To check if they are equal, either you can check character by character or you can check if they both refer to the same object.
In fact, equals method in java first checks if the references are same and only if not goes ahead and checks character by character.
Java is full of references and hence, you might need a case where you need to check if two variables are referring to the same String/Object rather than both having each copy of the same String so that you can update string at one place and it reflects in all variables.
To do so, equals method does not help as it checks the copies to be equal as well. you need to check if they both refer to the same object and hence == comes into picture.
It seems that this was asked before and received quite a popular answer here:
Why didn't == operator string value comparison make it to Java?
The simple answer is: consistency
I guess it's just consistency, or "principle of least astonishment".
String is an object, so it would be surprising if was treated
differently than other objects.
Although this is not the fundamental reason, a usage could be to improve performances: before executing a heavy computation, "internalize" your Strings (intern()) and use only == for comparisons.
What I am asking is what uses does the == operator have for String class in Java ?
What is the justification of not overloading it, so that it does a deep comparison ?
== and equals have altogether different uses.
== confirms if there is reference-equality
Equals confirms if the objects contains are same.
Example of reference-equality is IdentityHashMap.
There could be a case in which Only the object inserting something to IdentityHashMap has the right to get/remove the object.
overloading reference-equality can lead to unwanted complexity for java.
for example
if (string)
{
do deep equality
}
else
{
do reference-equality
}
/*****************************************************************/
public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
Using the standard loop, I compared a substring to a string value like this:
if (str.substring(i, i+3) == "dog" ) dogcount++;
and it broke the iteration. After the first increment, no further instances of "dog" would be detected.
So I used substring.equals, and that worked:
if (str.substring(i, i+3).equals("dog")) dogcount++;
My question is, why? Just seeking better understand, thx.
You should use equals() instead of == to compare two strings.
s1 == s2 returns true if both strings point to the same object in memory. This is a common beginners mistake and is usually not what you want.
s1.equals(s2) returns true if both strings are physically equal (i.e. they contain the same characters).
== compares references. You want to compare values using equals() instead.
For String comparison, always use equals() method. Because comparing on == compares the references.
Here's the link for further knowledge.
You might also want to read this for understanding difference between == and equals() method in a better way along with code examples.
== compares references(storage location of strings) of strings
and
.equals() compares value of strings
"String" is an object in Java, so "==" compares the references, as stated.
However, code like
String str1 = "dog";
String str2 = "dog";
if(str1==str2)
System.out.println("Equal!");
will actually print out "Equal!", which might get you confused. The reason is that JVM optimizes your code a little bit when you assign literals directly to String objects, so that str1 and str2 actually reference the same object, which is stored in the internal pool inside JVM. On the other hand, code
String str1 = new String("dog");
String str2 = new String("dog");
if(str1==str2)
System.out.println("Equal!");
will print out nothing, because you explicitly stated that you want two new objects.
If you want to avoid complications and unexpected errors, simply never use "==" with strings.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java string comparison?
I have encounter the following problem, I have an object called "lang", is a result from a method LanguageDetector.detect() which output a string.
lang = LanguageDetector.detect();
So I would want to check whether the language is english, so I am checking,
lang == "en"
The following screen is my debug screen, my lang is showing "en", however my lang == "en" is showing false and lang.toString() == "en" is false, does anyone encounter following problem before and have a possible solution?
Use equals() method of String object instead of direct comparison.
String first = new String("Hello");
String second = new String("Hello");
first == second will return false.
first.equals(second) will return true.
In Java, == always does a reference comparison. You need a value comparison though (with the equals() method for instance).
You're comparing the references to the Strings rather than the contents of the strings themselves. See here for more info.
Note that this issue doesn't apply just to Strings, but to all objects. As such, you may have to define appropriate equals() methods for any objects you create yourself.
Additionally String interning will confuse matters if you're not careful. See here for more details.
Use lang.equals("en") instead of lang == "en". The latter compares the two string references for equality, whereas the former compares the contents of the two strings.
See http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml for an overview of different string comparison methods in Java.
By using == you are checking that both string references point to the same object.
For strings that are created on the fly, and not interned, this will equal false.
To compare the strings for equality, letter by letter, use string1.equals(string2) or even string1.equalsIgnoreCase(string2).
Use "en".equals(lang) instead of lang == "en"
Its better to use the equals as said
but if its necessary for performance reasons you can try
the intern() function.
lang.intern() == "en"
I am trying to return a toString if something is true.
I have this code:
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = ("Hamburg");
if ((s.getDeparturePort()) == hamburg) {
System.out.println(s.toStringAdjusted());
}
}
}
However I get nothing when I run the method (when I should be getting something). I assume that I have somehow messed up the logic or not understood =,== and eq properly, I'm not too sure.
There is nothing wrong with the toString or the for loop, and I'm not getting any compiler or run time errors. It's just that the logic is wrong.
If someone could put me right that'd be appreciated. Thanks.
You should be using .equals() instead of == to check String equality. Try the following:
if ((s.getDeparturePort()).equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
In short, == checks to see if two strings are the exact same reference, and .equals() checks to see if two strings look the same.
It should also be said that you need to use .equals() for checking the equality of any Object type, not just strings. Only primitive types (int, double, char) should use == for equality.
To compensate for the fact that the departure might be null, simply switch the condition around. It would read - hamburg.equals(s.getDeparturePort())
Yup, you're relying on == comparing for equality rather than identity. Change the code to:
if (s.getDeparturePort().equals("hamburg")) {
System.out.println(s.toStringAdjusted());
}
For reference types, == in Java always means "compare the two references for equality". In other words, it returns whether two references refer to the same object.
You want to check whether the two strings are equal instead - i.e. whether they contain the same sequence of characters. That's what the overridden equals method is for.
(To give a real-world demonstration of this, I catch a number 36 bus every morning. To me those buses are equal because they take me on the same route, but I know there are several number 36 buses - I don't get on the exact same physical bus every day.)
Note that the code above will throw a NullPointerException if s.getDeparturePort() returns null. There are two ways of avoiding this. First, you can use a known-to-be-non-null reference as the target of the method call:
if ("hamburg".equals(s.getDeparturePort()))
Alternatively, you can perform an explicit nullity check:
String port = s.getDeparturePort();
if (port != null && port.equals("hamburg"))
Or you can leave it to throw an exception, if that's the most appropriate behaviour (i.e. if you really don't expect getDeparturePort() to return null, and want to blow up if you get such bad data rather than continuing and possibly propagating the problem).
You must compare strings using equals method.
In Java, String is a reference type. It means that your String hamburg, pointing to a variable in the stack, contains a reference to a managed heap object actually containing the string. A value type, conversely, is completely allocated into the stack.
The ==, read reference equals compares the stack values. Instead, all classes implement an equals method that is read value compare. It compares the real values of the object wherever they are allocated in.
The following code works for you:
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = ("Hamburg");
if (hamburg.equals(s.getDeparturePort())) { //First hamburg to prevent any possible NullPointerException
System.out.println(s.toStringAdjusted());
}
}
}
Just for your curiosity:
PHP only compares by value
C# redefines the == operator as a value equals operator, but only for the string class
In VB.NET, the default = operator is the value equals operator. The Is operator corresponds to the reference equals
In String, equality is checked either by equals() method or compareTo() method.
Your solution can be fixed by:
if (s.getDeparturePort().equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
To avoid receiving a null from s.getDeparturePort(), I would do the following.
if ("Hamburg".equals(s.getDeparturePort())) {
System.out.println(s.toStringAdjusted());
}
This is to avoid NullPointerException if s.getDeparturePort() is null (from your example code).
Alternatively, you can use the compareTo() method like so....
Your changed code (to using compareTo():
if (s.getDeparturePort().compareTo(hamburg) == 0) {
System.out.println(s.toStringAdjusted());
}
My alternate solution (using compareTo())
if ("Hamburg".compareTo(s.getDeparturePort()) == 0) { //Zero means that it is equal.
System.out.println(s.toStringAdjusted());
}
Btw...
String hamburg = ("Hamburg");
can be easily written as
String hamburg = "Hamburg";
if(hamburg.equals(s.getDeparturePort()))
Try
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = "Hamburg";
if (s.getDeparturePort().equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
}
}
== is comparing the object itself, you're better off using .equals() as it will compare the actual value of the String, such as :
if ((s.equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
Also make sure that Sailings has at least 1 value, otherwise you'll never enter that for loop anyway
Instead of simply providing the code...check this out, I am almost certain it will get you to where you need to go...
try if (s.getDeparturePort().equals(hamburg))
Instead of using == for String objects (or any objects), use .compareTo(), as in this example:
http://leepoint.net/notes-java/data/strings/12stringcomparison.html