Java if statement is skipped - java

In the following Java code, the if statement conditional does not evaluate to true and its block is skipped.
public void options(String input)
{
if(input == "x")
System.exit(0);
}
Input has the right value, so why is the System.exit(0) skipped?

You're comparing two string references for identity, not whether they refer to equal strings. It's not skipping the if statement - it's evaluating the condition, and finding that it's false, so it's not going into the body. Try this:
if (input.equals("x"))
Or if input might be null and you don't want that to cause an exception:
if ("x".equals(input))
This isn't just true of strings - whenever you have ==, it will compare the values of the two expressions... and if those values are references, it simply compares whether those two references are equal, i.e. whether they refer to the same object. equals, on the other hand, is applied polymorphically - so the object it's called on can determine what constitutes equality for that class.
As another example:
Integer x = new Integer(1000);
Integer y = new Integer(1000);
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

This is a classic. Don't use "==" for comparing Strings, use String.equals().

Try using
"x".equals(input)
== tests whether they refer to the same object not the content of the string.

Do not use == for comparing strings, use equals.
if(input.equals("x"))
System.exit(0);

Try "X".equals(input). For String comparison use equals method.

You need to use .equals(), not ==.
Using == will always fail: Unlike javascript, in java == tests if the two operands are the same exact object, which they aren't (one is a String constant, the other was user input)
.equals() test if the two objects "have the same value" (class-dependant implementation).

Use == for comparing primitives and object references.
equals for content comparisons(provided it is implemented). String has the equals implemented for content comparison and you should use that.

Related

Three different ways to compare strings in Java

Some months ago, I remember being in an interview and being asked for three different ways to compare strings in Java for their values. Out of curiosity, I'm going to ask it here for my own reference. I thought of two:
str1.equals(str2) or using compareTo, both counting as one in total
comparing character by character
Any idea? "==", equalsTo, compareTo, and any variations of them are not it I was told.
Edit: Fixed question a bit.
Since there was such a huge objection to using == I couldn't resist the temptation of posting an answer that does use it (and which is perfectly valid!) :)))
String s1 = new String("abc"); // create string object 1
String s2 = new String("abc"); // create a different string object 2
s1 = s1.intern();
s2 = s2.intern();
System.out.println(s1 == s2); // true!
So if we make sure to intern the strings we can count on ==.
Other than that, as I suggested in the comments above:
it sounds like the interviewer was looking for a "wiseass" solution, for example:
s1.contains(s2) && s2.contains(s1)
or
s1.matches(s2) && s2.matches(s1)
or
s1.replace(s2, "").isEmpty() && s2.replace(s1, "").isEmpty()
and etc.
I can think of a few of ways besides looking at each character yourself or using equals() or compareTo():
s1.startsWith(s2) && s2.startsWith(s1)
s1.contains(s2) && s2.contains(s1)
s1.indexOf(s2) == 0 && s2.indexOf(s1) == 0
Arrays.equals(s1.toCharArray(), s2.toCharArray())
s1.intern() == s2.intern()
To be frank, though, I don't really see the value of this as an interview question. (If the interviewer had the last one in mind, a better question in my opinion would be to identify all the cases when it was safe to use == to compare string values.)
I am guessing
1) using '==' operator' which compare strings reference
2) equals() method of String which compare exact string content
3) equalsIgnoreCase() method which compare string content in case incensitive manner
If I eliminate the ones that take into account casing, there are still plenty of ways, and I'm sure I'm missing some:
s1.equals(s2)
s1.compareTo(s2)
s1.contentEquals(s2)
Objects.equals(s1, s2)
Objects.deepEquals(s1, s2)
EDIT
Technically, this is also a way, but I think it's bad practice:
s1.intern() == s2.intern()
Some other options may be (look here for details)-
1. String comparison using equals method
2. String comparison using equalsIgnoreCase method
3. String comparison using compareTo method
4. String comparison using compareToIgnoreCase method
There are four ways:
==
.equals()
compareTo()
compare()
Read more

String.trim() returning false for same referenced object

Why is this false?
String str1 = new String("Java ");
String str2 = str1;
System.out.println(str1.trim()==str2.trim()); //false
Initially str2 was referencing str1 object. So, comparing with == will return true for str1==str2
Then why is this false with .trim() method?
Even it returns false for literals (without new keyword)
String str1 = "Java "; //this is now without new keyword
String str2 = str1;
System.out.println(str1.trim()==str2.trim());
Note: I know how to use .equals method. But want to know == behavior especially in case of .trim() with above given two example.
use equal instead of ==
System.out.println(str1.equals(str2.trim()));
Use the equals() or equalsIgnoreCase() methods to compare Strings. == compares object identity.
Strings are immutable in Java.
Also string literals are interned i.e. java maintains a pool of string literals.
With the first 2 lines you are creating one object and 2 references str1 and str2 to the same object.
When trim() is applied on a string it forms a new string object and assigns the current reference to the new object.
But since new is used while object creation str1.trim() and str2.trim(), both end up creating 2 separate objects.
Refer: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim%28%29
trim() method creates a new object. Since you applied trim() individually on same object (though referred to by multiple references str1 and str2) hence 2 new objects are created.
This is the reason why reference equality is not working.
String are compared with equals, not ==
"=="
works on refrences function trim creates a new object that will have new refrence. that is the reason it will allways return false
If you wanna compare the content of a string, you need .equeals.
Your (modified) example
String str1 = new String("Java ");
String str2 = str1;
System.out.println(str1.trim().equals(str2.trim())); //is now true
For string comparison you should use str1.equals(str2) or str1.equalsIgnoreCase(str2).
For more points check this question.
Since you are using String str1=new String("Java ");
You cannot use == operator
If you used String str1="Java ";, you could use ==
So here either change code to String str1="Java ";
or change
System.out.println(str1.trim().equals(str2.trim()));
You have two different Strings so two different references. To compare the content use equals().
== will compare the if reference of tow object are the same, as it check if both object are the same without checking the content of the object.
As string is an object == will work only with the same Object of type string without checking the content of the string.
to check the content of the String
use
equals() or equalsIgnoreCase
You are using == sign for comparison. In java this will compare the actual objects, that is, whether the two variables point to the same physical object in memory, the same memory location.
If you want to compare the actual content of the strings, then you need to use method equals of String class (or equalsIgnoreCase) if you don't care about the case.
The same applies to any other types of objects. If you compare them using ==, you will be comparing the physical memory location of two variables. You would use equals method to compare the actual content of the objects (provided the class actually implements this method).

Comparing two strings in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!

condition == between string and constant [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Someone can tell me why this condition
if (lista.getString(0)=="username")
do not return true? I've used to try
if (lista.getString(0)==lista.getString(0))
and dont work, and i have understand that is a language problem.
== tests for reference equality.
.equals tests for value equality.
Threfore you should use:
if (lista.getString(0).equals("username"))
See How do I compare strings in Java?
For String comparison always use equals().
if (lista.getString(0).equals("username"))
Using == , you will end up comparing references, not values.
A simple snippet to clarify further:
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // true because values are same
System.out.println((s1 == s2)); // false because they are different objects
From Java Techniques
Since Strings are objects, the equals(Object) method will return true if two Strings have
the same objects. The == operator will only be true if two String references point to the
same underlying String object. Hence two Strings representing the same content will be
equal when tested by the equals(Object) method, but will only be equal when tested with
the == operator if they are actually the same object.
Use
if (lista.getString(0).equals("username"))
The correct way to compare objects is with,
object1.equals(object2)
And String is an object in Java, so it implies same for String too
s1.equals(s2)
eg :
if (lista.getString(0).equals("username"))

java operator == uses [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Strings in Java : equals vs ==
Comparing strings in java
is == can be apply to Strings ?
if so then what is the use of it for String's data type?
in other words although we should use equal method for comparing two string java, what is the use of == operator for String in java?
== will not compare the value of the String but its addresse. If you want to compare the value use the method equals().
When you want to compare objects in Java, you should use the equals() method. The operator == is used to compare references, not values, in Java objects.
For example:
String s1 = "hello";
String s2 = new String("hello");
boolean comp = s1.equals(s2); // correct, returns true
comp = s1 == s2; // wrong, returns false
The '==' operator compares two Object references. So, in the case of two Strings, it is examining those objects, and seeing if they represent the same location in memory.
The .equals() method compares the Strings' contents to each other.
Comparing objects, == operator compares if the references are the same. In primitive types (int, float, double, boolean) it actually compares the value. Since Strings are objects, it's better to use the equals() method. == will compare if both references of strings are the same, which may not. equals() method is also used by Java Collections.

Categories