Similar String comparison fails - java

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 ==

Related

== or equals when comparing final static fields

I've returned back to Java after a little break with C# and I'm already tired of writing stuff like a.equals(b) so I was wondering if is there a way to use the == operator without breaking my program.
Here's my situation:
public static class A {
public final static A STATIC_FIELD = new A(prop1, prop2);
public A method(int param){
return (param > 0.5) ? STATIC_FIELD : new A(prop1, prop2);
}
}
Now, can I replace equals with == in the following snippet since I'm referring to the same object or is it wrong?
....
private bool method(){
A aInstance = getAInstance();
int param = Math.Random();
return aInstance.method(param).equals(A.STATIC_FIELD);
}
....
And what if the STATIC_FIELD in a value taken from an enum?
This depends on what do you want to do.
If you need to check if this is exactly the same object, use the direct comparison. If you need to check if the object wraps the same content (like string or number), then .equals should be used.
Most common errors with these methods seem coming from string comparison, where .equals returns true if the strings have the same content but == only returns true if this is the same instance of string.
You should avoid == (ok, let's agree that you know it :-)), also in relation to singleton instances as you may "forget" later that it is created via singleton. But I will give you a hint. Instead of:
if ((var != null) && (var.equals(A.STATIC_FIELD)))
you may write:
if (A.STATIC_FIELD.equals(var))
just like many people do not realize that to compare strings they may use:
if ("static string".equals(varString))
You may also use java.util.Objects.equals to compare objects without all this checking nulls burden.
no you cant use == instead of equals() becuase when we use == in java we are actually comparing the memory address of the object , so if the method returns STATIC_FIELD then it will work properly as its a static object and the address will be same everywhere.
But when method will return new object of A then the address wont match even if the content is same within the class because the new A(param1, param2) insists JVM to create a new object at a different memory location
== checks if two objects are the same instance. If you want to check if two variables are holding the same instance (as they may well be if you are assigning your variables to class constants), == is fine to use. It also won't error if your variable happens to hold null, so it has that benefit over .equals().
Instances of an enum are always constant, and two different instances will never be equal, so == is fine to use for those too.
If you don't override the equals() method, equals() and == do the same thing, check the equality of the references. You can make the replacement in this case, since method() will return the same reference as A.STATIC_FIELD when it is true. See this answer.

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

java if statement error

It seems to me that this if statement is not working.
I'm new in java, but i know C# and C++ pretty well, but I've never seen such a thing before:
today=edit[0].substring(0,10);
if (today == edit[0].substring(0,10))
{
pars_prog.addView(name_prog[i]);
}
And it doesn't get into the IF function?
Are if statements different in Java (Android)?
When you use == for any object references (whether strings or any other non-primitive type) it simply compares whether the references are equal - i.e. whether they refer to the exact same object, or whether they're both null.
In this case, you want to determine whether the strings are equal - i.e. whether they represent the same sequence of characters. You should use the equals method for that:
if (today.equals(edit[0].substring(0,10)))
However, in general when doing this you should be careful that the target of the equals call is non-null, or you'll get a NullPointerException.
Note that C# is similar - except that the == operator can be overloaded, and is overloaded for string. If the compile-time types of the operands aren't both string, you'll still get reference comparison:
object text1 = new StringBuilder("hello").ToString();
object text2 = new StringBuilder("hello").ToString();
Console.WriteLine(text1 == text2); // False
You are trying to compare strings with ==, which is identity comparison - it will check if the two are the same instance (in the JVM) rather than comparing their contents.
Use today.equals(..) instead.
That said, if appears you are working with dates, so a String is not the best way to handle this. Use Calendar, Date (a bit obsolete) or joda-time DateTime
You have to use the equals method when comparing strings.. Right now you are comparing references and thats why you never enter the if block

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