Differences among string comparisons in python, c++, c# and java - java

It seems that string comparison cannot simply be done by "==" operator as I read from explanation that in java and c#:
In Java I saw this explanation:
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
In c# I saw this code:
if (parametrii[0].Equals("teach"))// to check the equality of values
It makes sense to me that "==" is checking of addresses and .equal() is just checking values.
However I have been using "==" in python and c++ all the time and I have never encounter such errors for examples
In python:
string1 = "helloworld"
string2 = "helloworld"
print(string1 == string2)// result true
In c++:
while(getline(ifs, line2)){
stringstream ssm(line2);
string from_stop;
string to_stop;
getline(ssm, from_stop, ',');
getline(ssm, to_stop, ',');
if(from_stop == to_stop){
adjList[from_stop].push_back(to_stop);
}
}
or
bool stop124 = false;
bool stopA24 = false;
bool stop126 = false;
for (int i = 0; i < adjVec.size(); i++) {
if (adjVec[i] == "124") stop124 = true;
else if (adjVec[i] == "A24") stopA24 = true;
else if (adjVec[i] == "126") stop126 = true;
}
Those code will successfully compile and get the correct results of comparing value. I know there is a strcmp() function in c++ but I rarely use it and don't quite know when to use it rather than == in checking whether two strings are equal in value.
So my question is that is this because there is a difference among those programming languages or it is just for me to be lucky that I did not run into those errors?

Since Java does not allow operator overloading, they had to resort to creating a function (Equals) to compare for 'true' objects equality - and leave operator == to perform pointer comparison. This choice can not be really justified by any other reason, as it warrants for illogical code, more typing in generalized case (people usually compare for true equality, not pointer equality) and steeper learning curve.
C++ with a clear distinction between pointer and an object is not constraint by Java limitations, and thus allows proper value-semantics for classes and intuitive forms of comparison.

Python compares string lexicographically i.e using ASCII value of the characters, so you can use the == operator. Java creates a string object, and thus you have to use the .equals() method to check the value.
So to answer you questions it's the language that are different. If you are trying to compare 2 strings in C++ I'd use the compare method.

Related

== operator to compare Strings [duplicate]

This question already has answers here:
String equals and == with String concatenation [duplicate]
(4 answers)
Closed 7 years ago.
I wrote the following code:
String s="Rahul";
String s2=s.concat(" Shukla");
String s3="Rahul Shukla";
System.out.println(s2==s3);
I was expecting true as the output of s2==s3, but it becomes false. As I think s2 and s3 are pointing to the same object in the string constant pool, so s2==s3 should evaluate to true. Can anyone please tell me what is really going on here?
First of all, unless you care about JVM internals and unreliable "guarantees", don't use ==. Just don't.
Secondly, when calling concat with " Shukla", the result is not in the constant pool. Rahul and Shulka are, but their concatenation is a new String on the heap:
Strings computed by concatenation at run time are newly created and therefore distinct.
+ as an operator is different since it's not a method call, in the case where both of its operands are known to be constant (by being a string literal):
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
Literal strings within the same class (§8 (Classes)) in the same package (§7 (Packages)) represent references to the same String object (§4.3.1).
All quotes are from the JLS, Version 8, section 10.3.5.
If you did create every string using new String(somestring).intern() then you can use the == operator to compare two strings, otherwise equals() or compareTo methods can only be used. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects.
Check this link : How do I compare strings in Java?
Since String is immutable concat() method will create new string object. but s3 will refer to an object which is in string pool. So s2==s3 it will return false
The s3 variable is created in the pool and s2 in the heap since == compare the reference the are not equal which gave you false.
String s3="Rahul Shukla";
Is creatd in the poot as s3 value can be determined at compiletime
String s2=s.concat(" Shukla");
is created in the heap because if you see the source code of concat() it returns new String()
Interestingly, the specification of concat has changed between Java 7 and Java 8.
The Java 7 Specification says:
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created...
Whereas the Java 8 Specification says:
If the length of the argument string is 0, then this String object is returned. Otherwise, a String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
However, the implementation doesn't seem to have changed. Here is the code.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
This means that if you use == to compare the result of s.concat(" Shukla") with s3 you will get false, but this is not strictly speaking guaranteed by the specification.
However, as others have pointed out, you do not need to care about this. You should just compare strings using .equals and forget about the details.

Two string's which (I think) are identical do not return true when checking if the same [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have two strings, one is inputted by the user and one is the name of a thread. I inputted the name which should be the same as the thread. To verify this I have the program output
System.out.println("DS:" + DeamonMain.threadNameFinal + "CN:" +getName());
Which prints
DS:Thread-66CN:Thread-66
Now these appear to be the same string. However, when I have it test the validity of this using
boolean factChecker = DeamonMain.threadNameFinal == getName();
System.out.println(factChecker);
it prints false...
Why is this? Does this have to do with getName()? How are the string different and why so?
You need to use String.equals to compare String equality, not the == sign.
As in:
boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
The == operator checks for reference equality, while the equals method checks for the equality of your String values.
See also here for an older thread on the matter.
Again, and again...
Strings in Java are compared with equals(), not with ==.
Change your comparison to:
boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
You should use the .equals() method to compare strings, rather than ==
boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
The reason is that the .equals() tests for value equality (the strings have the same characters), while the == tests for reference equality.
You need to use equals() method instead of ==
Like this:
DeamonMain.threadNameFinal.equals(getName())
Use equals() for String comparision instead of == operator
boolean factChecker = DeamonMain.threadNameFinal.equals(getName());
System.out.println(factChecker);
equals() method is used for content comparison where as == is reference comparison.

having trouble find a certain string function

if
"blah".equals(string);
is equivalent to
x == y;
what is the string comparison equivalent to
X != y;
sorry if this is extremely basic. searching proved a bit difficult so far.
"blah".equals(string) is NOT equivalent to x == y. The first is a function, the second is a built-in java operator. The default implementation for strings works because stings in java are handled in a special way. But if someone overrides the default implementation of equals in a class, you can have a.equals(b) but a != b.
First of all, equals is not equivalent to == in Java, if I remember what I was taught back in college correctly :P. equals determines whether two objects have the same "content", while == simply compares the two "references".
And I'll try to answer your question, !"blah".equals(string); maybe?
"blah".equals(string);
evaluates to a boolean, either true if they are equal or false if they are not.
By appending a ! to the front, we take the inverse of that, true if they are not equal, false if they are. This is what you want:
!("blah".equals(string));
On a more pedantic node, for strings, "blah".equals(string) is not the same as "blah" == string, due to complications you probably don't need to know. Also, I suggest you read up on your Boolean logic.
Also your example of x != y is shorthand for !(x == y)
The correct way of writing it is:
if(!"blah".equals(string))
Does !x.equals(y) performs the inequality test you want?

String comparison in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am working with Java code in JSP and I am trying to compare strings and I am having problem with that.
I have declared two strings
s1 = "din";
s2 = "din";
However, the if (s1 == s2) never executes. Can someone help me?
The operator == for Strings compares for reference equality, not value equality.
Try calling equals instead of using ==:
if (s1.equals(s2)) { ... }
When comparing strings you should always use the equals method, not ==:
if(str1.equals(str2))
...would be the correct way to do things.
Where confusion arises is cases like the following:
String str1 = "hello";
String str2 = "hello";
System.out.println(str1==str2);
The above will actually print out true. However, save for academic purposes like the above, you shouldn't ever use it. If you're using == you're checking if the values are physically the same object on the heap. If you're using .equals() you're checking that they're meaningfully equal, even if they're actually two separate objects.
Sometimes, especially where literals are involved such as above (or when you manually call the intern() method) Java will automatically make two separate string objects point to the same object for performance reasons. However, there's no logical guarantee this will happen (unless you want to bother yourself with explicit details of the JLS, and even then it's only guaranteed sometimes) and most of the time it won't. Take the following for example:
String str1 = "hello";
String str2 = "he";
str2 += "llo";
System.out.println(str1 == str2);
Now it prints false, because despite being meaningfully equal we haven't hit the same optimisation that Java was providing previously.
In both cases above, using ,equals() would return true.
You use 'equals' when you compare strings.
if(s1.equals(s2)) { true }
What are you trying to achieve?
Compare String's or their values?
If you are expecting that your (if) condition should return true then use
s1.equals(s2);

Strings don't seem to be equal in Java on Android, even though they print the same

I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }

Categories

Resources