GWT: String comparision is not working - java

I have the following code in my presenter in a GWT MVP application:
public void onFailure(ServerFailure error) {
String errCode = error.getMessage();
Window.alert(errCode);
Window.alert("Server Error: pleaseEnterQuestion");
if(errCode == "Server Error: pleaseEnterQuestion")
Window.alert("same");
else
Window.alert("different");
}
The first two alerts look exactly the same. The third alert is different. But I expect it to be same.

Use equals, not ==, to compare Strings:
if("Server Error: pleaseEnterQuestion".equals(errCode))
See this SO question for more information: How do I compare strings in Java?

Always use equals() when you want compare Strings. Moreover, you have to sometimes trim (left, right or just trim :)) Your String before compare, because it contains white spaces.

Use .equals()
In equals the content of the string are compared not the reference ID's of the string object.
In == the objects reference ID's are compared.
The equals() method is overridden in String and Wrapper classes in java elsewhere both equals and == have same functionality.

Related

Similar String comparison fails

I am trying the following code in Android Studio. When Debugging, I find out that even when Value of variable B is "(" my if statement does not execute and hovering over it, it shows it is false (please refer to image).
The value of ScreenText in this case is "6(".
Any help is appreciated.
.
You should compare strings with the .equals() method. In this case, and to prevent a null pointer exception in case that your B variable is null, you should do so like this:
if("(".equals(B)) {
...
}
The == operator is used for reference comparison, to check whether two object have the same reference.
You want to compare two Strings, use the boolean equals(String) method.
if( "(".equals(B)) {
// your logic
}
Here comparing B with "(" constant does not require you to make null checks.
I think a more generic way to compare strings in Android is:
TextUtils.equals(B, "(");
And by the way, in your code
String.valueOf(c).toString();
toString() is redundant.
If you want to compare the value or contents of two strings then use .equals().
if(string.equals("(")){
//Enter your code
}
But if you want to check that two object points to same reference then use ==

Difference in string comparison result b/w == and String#replace with == [duplicate]

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)){
...
}

Regarding programming logic on ==

I am having this strange behavior when performing a method which the if statement where both values are true but it fails to go over the if statement.
Here is the code and how it looks like. On top right where it is circled red is the value of className.
If anyone has an idea why this is occurring or might have a better way of doing it please respond or guide me to a better coding logic to that I am already using.
On debug className = "rwb"
public void ClassReturn(){
String tempName = getIntent().getExtras().getString("CLASS_NAME");
if(tempName == null){
Log.i("Intent Delivery", "Intent deliver has failed.");
}else{
String className = tempName; // This is return back to the correct class your in
if(className == "rwb"){
Intent intent = new Intent(BasicOption.this, ReadWholeBook.class);
startActivity(intent);
}
}
}
Use .equals() to check if two objects are logically equal, use == the check if they are the same object.
Strings in java can be more complicated because of interning but basically you want to use the .equals() or .equalsIgnoreCase() to check the contents of the two strings are the same.
You're using == to compare two Strings. Use the equals method instead.
Use className.equals("rwb") for string comparison, not ==
Don't use == comparison on Strings, use className.equals("anotherString");
Use String.equals() in this situation. == mainly is for checking if the object is the same exact object.
In Java you cannot overload operators therefore what you're doing is comparing the object ID instead of comparing the String's logical value. Switch to string.equals(other_string) and it will work as you expect.
Squinting at the code, you are comparing a String using ==
if (className == "rub")...
You should use equals() instead, i.e. (I put "rub" first cause I know that will never be null)
if ("rub".equals(className))...
use the equals method to validate Strings, but also you have to be sure about the content, so my recomendation is use this :
myString.trim().equals(myString2.trim());
you could turn to upper case the strings too.
Saludos

Weird Java Behaviour in string comparison [duplicate]

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"

Simple if statement problem

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

Categories

Resources