This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal.
Here's the code with its problem:
//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
if(it.next() == args[0])
{
deal += it.next();
it.hasNext();
break;
}
}
Thank You!!!
To compare two strings u should use the method equals() or equalsIgnoreCase().
in your case:
if(it.next().equals(args[0]))
the operator == returns true if the two object are the same object, same address in memory.
You use .equals when comparing two strings. So use
(it.next()).equals(args[0])
You have to use .equals method:
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
String next = it.next();
if(next.equals(args[0]))
{
deal += next;
break;
}
}
Be careful, .next() returns the value once and move its internal cursor to the next value.
The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.
There are two ways of comparing strings.
Comparing the value of the strings (achieved using .equals ).
Comparing the actual object (achieved using == operator).
In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).
if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.
If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
the java subSequence is clearly true but only returns the false value. why?
trying to see if a sequence is equal to a subsequence of a bigger string
package testifthen;
public class TestIfThen {
public static void main(String[] args) {
String result = "01900287491234567489";
String result1 = "90028749";
if (result.subSequence(2, 10) == result1) {
System.out.println("excel");
}else {
System.out.println("not found");
}
}}
It's hard to say without more information (for example what language is this in).
Assuming this is Java, I would say your problem is using == with strings instead of the .equals function.
== doesn't check the contents of the string, only if they are referencing the same object. .equals should be used instead as it actually checks whether the characters match in the two strings
Try using
if (result.subSequence(2, 10).equals(result1)) {
System.out.println("excel");
} else {
System.out.println("not found");
}
The == symbol might be the one causing it to return false because of the different references.
This post should explain more about differences between == and equals(): What is the difference between == vs equals() in Java?
In Java, the .equals method should be preferred to the == operator when checking for semantic equality. .equals should be used when you are checking if two values "mean" the same thing, whereas == checks if they're the same exact object.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I tried with the following class :
public class EqualMethodTestWithNew {
public static void main(String[] args) {
String value = "xxx";
String name = new String("xxx") ;
System.out.println("hascode : value : "+value.hashCode());
System.out.println("hascode : name : "+name.hashCode());
if (value == name) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
}
}
though the hasCode is same for the both variable it prints the false == 1. could some one explain the reason why?
thanks
You need to understand what exactly is happening when you execute the 2 string statements.
String value = "xxx";
The above line creates a new compile time constant string which does into the String intern pool.
String name = new String("xxx") ;
But in this case, since you're using the new operator, it creates a new String object which goes in the object heap. It does not have the same address as the one which was created in the previous statement.
The hashCode() method is based on the contents of the String which are the same, but that doesn't mean that they both refer to the same String object in the memory.
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // would return same value for all String objects having the same content
To compare the values, you need to use equals() method.
And if you want to compare the object references use the == operator. In your case, since both refer to difference objects, you get the output as false.
Alternatively, you can ask the compiler to check and fetch the reference of a String with the same value already existing in the String pool by using the intern() method.
String value = "xxx";
String name = new String("xxx");
name = name.intern(); // getting reference from string pool
Now you'll get the output as equal == 1 when your do if (value == name) {.
You should be using equals method instead of == opertaor.
if (value.equals(name)) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
Note that:
== tests for reference equality.
.equals() tests for value equality.
Please see here for more information.
The reason why your code is not working is that == tests whether the reference to the object is the same, and that is not your case. To compare the value of the string, you need to use the .equals(String str) method.
if (value.equals(name)) {
...
}
String should be compared with equals() method, not ==. You are trying the check the equality of the memory address of both instances (actually they are not) instead of the value in the String instances. So, use
if(value.equals(name)) {
System.out.println("equal == 1");
}
Strings are compared using equal() method. == compares the two objects are equal are not.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
i have a small of a problem. I have to String Lists with the same size and a string to compare. meaning i want to compare the string with the first list to get the index of the compared string in the list and then get another string from the other list on this index.
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
} else {
return "nope";
}
}
}
Is it wrong to compare two strings like that. or should i use the operator ==. I know the style with to string lists is not nice but its just a temporary solution. thx for any help :)
To answer your specific question on "string comparison", what you are doing is correct. String content comparison should be done using equals(). Using operator == is only checking for the equality of the reference, not the content.
For the work you are doing now, it looks like a key-value lookup to me. You may consider some redesign and, instead of storing 2 lists, make a Map<String, String>
== operator in Java compares the Object References, to compare strings you should use equals().
if (list1.get(i).matches(elem))....
always use equals method to compare two string. If you are comparing references then use == operator. Here discussion can be useful How do I compare strings in Java?
== operator work fine only if the String variable is not instanciated new keyword.
Suppose:
String s1 = "abc";
String s2 = "abc";
Then s1==s2 works good.
If:
String s1 = new String("abc");
String s2 = new String("abc");
Then you must use equals method to compare the values.
Finally, it is always better to use equals method to compare the String values.
Use the equals() method to compare the value of the object,where as == operator will compare object reference.
The problem is not equals (that is the correct method), you must remove else expression, if not you will stop always at first iteration, solution:
private String getStringOnIndex(List<String> list1, List<String> list2,String elem)
{
String elem2;
for (int i = 0; i<list1.size();i++) {
if(list1.get(i).equals(elem)){
elem2 = list2.get(i);
return elem2;
}
}
return "nope";
}
...in other words:
let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true".
This is because the String class overrides the equals() method to implement a content level equality.
However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two.
How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?
If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.
String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
Java String.equals versus ==
Use simple == comparison. However to avoid String interning you have to create your Strings using char arrays such as: String me = new String(new char[] { 'm', 'e' }); instead of using String literals "me" such as String me = new String("me");.
if (one == two)
System.out.println("one and two are the same object");
The only this you need is "==" equality operator.
Why it print the wrong output?
ArrayList<String> loc = new ArrayList<String>();
This arraylist stored the value of:
[topLeft, topLeft, topLeft, bottomLeft, topLeft, bottomLeft, topLeft, topLeft, Left, topLeft]
the firs index 0 is = topLeft
if(loc.get(1)=="topLeft")
System.out.println("same")
else {
System.out.println("not same")
}
This program print the wrong output not same instead of same
Use the equals(Object) method, not the == operator, for example loc.equals("topLeft")
The == operator returns true if two references point to the same Object in memory. The equals(Object o) method checks whether the two objects are equivalent, so will return true if two Strings contain only the same characters in the same order.
String comparison is done by calling str1.equals(str2) rather than using ==.
equals(..) compares the strings' contents
== compares the references, and they are not the same.
There is a little more to know, however. String objects that are initialized as literals, i.e.
String str = "someString"
instead of via construction (String str = new String("some")) are all the same object. For them == would work.
And finally, for any String, calling intern() returns a String that is the same object as all other strings with the same content. (read intern()'s documentation for more info)
But the best practice here is to use equals(), while being careful if the object you are calling it on (the first string) is not null.