Java comparison with == of two strings is false? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String parts is String[6]:
["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]
But when I compare parts[0] with "231":
"231" == parts[0]
the above result is false,
I'm confused, so could anybody tell me why?

The == operator compares the object references, not the value of the Strings.
To compare the values of Strings, use the String.equals method:
"231".equals(parts[0]);
This is true with any other object in Java -- when comparing values, always use the equals method rather than using the == operator.
The equals method is part of Object, and should be overridden by classes which will be compared in one way or another.

If the strings are not interned, then == checks reference identity. Use:
"231".equals(parts[0]);
instead.

== in Java compares the address of the objects (strings in this case).
What you want is parts[0].equals("231")

The following prints out "true";
String s = "231";
if(s == "231")
{
System.out.println("true");
}
else
{
System.out.println("false");
}
This is because Strings are not mutable and java will try and save as much space as possible, so it points both to the same memory reference.
However, the following prints out "false":
String s = new String("231");
if(s == "231")
{
System.out.println("true");
}
else
{
System.out.println("false");
}
new will force it to store the string in a new memory location.
By the way, you should ALWAYS use .equals() to compare strings (for cases just like this one)

Use equals method: parts[0].equals("231"). == operator compares object references.

"==" compares object references, in your case "231" is a different object than parts[0].
You want to use String.equals.
parts[0].equals("231")

The answer is very simple: when you compare strings through == operator, you actually compare if two different variables refer to a single String object. And they don't, the string in the array and newly created "231" are different String objects with the same contents.
The right thing to do is to use the folllowing expression: "231".equals(parts[0]) or "231".equalsIgnoreCase(parts[0]). This will give you what you need and return true if these String objects contain the same values.

I thought it might be helpful to express the answer in a test case:
public class String231Test extends TestCase {
private String a;
private String b;
protected void setUp() throws Exception {
a = "231";
StringBuffer sb = new StringBuffer();
sb.append("231");
b = sb.toString();
}
public void testEquals() throws Exception {
assertTrue(a.equals(b));
}
public void testIdentity() throws Exception {
assertFalse(a == b);
}
}

You may also use compareTo(String) method:
String str = "test";
if( str.compareTo("test") == 0)
//the argument string is equal to str;
else
//the argument string is not equal to str;

Use the equals method to compare objects:
String[] test = {"231", "CA-California", "Sacramento-155328", "aleee",
"Customer Service Clerk", "Alegra Keith.doc.txt"};
System.out.println("231".equals(test[0]));
The comparison '==' compares references, not values.

Here's really nice example. The '==' operator with string can be really tricky in Java.
class Foo {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = "h";
c = c + "ello";
String operator = null;
if(a == b) {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + b);
if(a == c) {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + c);
if(a == "hello") {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + "hello");
if(c == "hello") {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(c + operator + "hello");
}
}
Which will produce following output:
hello == hello
hello != hello
hello == hello
hello != hello

As many others have already explained, you try to compare with equality operator, but then it would relies on Object.equals() instead of String.equals().
So you can do the job by explicitly calling String.equals(), but instead of writing
parts[0].equals("blahblah")
I would prefer such :
"blahblah".equals(parts[0])
As it avoids testing potential nullity of parts[0] (but be careful that parts variable itself could be null...)
Another way is using String.intern() :
if (parts[0].intern() == "blahblah") ...
See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern() for more info on that.

Related

When am comparing objects through == operator java sop command not printed appended text why?

My code below
public class EqualsComMetod_Operator {
public static void main(String[] args) {
String s1=new String("Raja");
String s2=new String("Raja");
System.out.println("s1==s2::"+s1==s2);
// Here the text s1==s2:: not printed on my console why??
}
}
Output:
false
Am comparing the objects as reference/address and try to print like this:
s1==s2::false
but directly showing false. Why?
The operator + is evaluated before the ==.
So if you examine the expression "s1==s2::"+s1==s2:
First "s1==s2::"+s1 is evaluated. It results in "s1==s2::Raja".
Then, "s1==s2::Raja"==s2 is evaluated, and obviously results in false.
You can control the precedence using brackets:
public static void main(String[] args) {
String s1 = new String("Raja");
String s2 = new String("Raja");
System.out.println("s1==s2::" + (s1 == s2));
}
Statement should be
System.out.println("s1==s2::" + (s1 == s2));
When you create two strings using new, they are different objects. The equality operator will always return false even if the strings contain the same content. This differs from literal strings, which the compiler will optimize to refer to the same object.
String s1 = new String("Raja");
String s2 = new String("Raja");
System.out.println(s1 == s2); // false
String s3 = "Raja";
String s4 = "Raja";
System.out.println(s3 == s4); // true

iBeacon.getProximityUuid() can't equal to string?

I try to compare iBeacon.getProximityUuid() with the custom string, but it can't work.
I'm very sure the first char is "a", but the result always return false!
I use the RadiusNetwork's iBeacon library.
String tempstr = iBeacon.getProximityUuid().substring(0, 1);
if (tempstr == "a") {
return true;
}
else {
return false;
}
You must change Change if (tempstr == "a") to if (tempstr.equals("a")). In Java, the == operator is used for object equality. Because the two objects aren't the same instance, tempstr == "a" always returns false. Using the .equals method actually compares the strings.

Method is not returning String?

Doing some beginner problems for Java:
Given two strings, append them together (known as "concatenation") and return the result.
However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
My code:
public static String conCat(String a, String b) {
//abc (c) == cat (c)
if (a.substring(a.length()-1,a.length()) == b.substring(0,1)) {
//return (ab) + (cat)
return a.substring(0,a.length()-2) + b;
//cat (c) == abc (c)
} else if(b.substring(0,1) == a.substring(a.length()-1,a.length())) {
//return (abc) + (at)
return a + b.substring(2,b.length());
} else if (a.equals("") || b.equals("")) {
return a + b;
}
}
I don't understand why Eclipse can't recognise the String returns.
First of all, you are comparing Strings with ==, which compares them by reference. This means that equal Strings might not return true. To avoid this problem, always use .equals() to compare Strings.
Second, keep in mind that your if statements are checked in the order specified. Since you want to check for empty strings first, you should put that one on top.
Third, you have to return something on all codepaths. If all of the if statements are false, you don't return anything. If you add else return a + b; you should get the desired behavior.
Furthermore, I suggest using a slightly different approach:
public static String conCat(String a, String b) {
//If either String is empty, we want to return the other.
if (a.isEmpty()) return b;
else if (b.isEmpty()) return a;
else {
//If the last character of a is the same as the first character of b:
//Since chars are primitives, you can (only) compare them with ==
if (a.charAt(a.length()-1) == b.charAt(0))
return a + b.subString(1);
//Otherwise, just concatenate them.
else
return a + b;
}
}
Note that you can omit the else blocks, since return will end the execution of the method there, so this will also work:
public static String conCat(String a, String b) {
if (a.isEmpty()) return b;
if (b.isEmpty()) return a;
if (a.charAt(a.length()-1) == b.charAt(0)) return a + b.subString(1);
return a + b;
}
actually, it can. but all your return statements are depending on a condition, so there 'll be cases for which you haven't provided a return statement.
in those cases, the method won't return anything, even while it should return a String.
add:
return "";
or
return null;
to the end of your method and try again.

If statement returns only the result from the "else" statement

I am trying to make a script that compares the user input with another string. The problem is with my if statement. I don't get errors but it always returns the result that is in the "else" statement. Here is the code:
String [] lessons_titles = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","30","40","50","60","70","80","90"};
final TextView dan_view = (TextView)findViewById(R.id.DanText);
final int position = getIntent().getExtras().getInt("position");
final String title = lessons_titles[position];
check_b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textField = check_text.getText().toString();
if (textField == title){
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
}
});
Use equals() method instead of == operator when you compare String. In case of String, two string will be equal if their reference are same and to find out that both of them referencing to the same point, you have to use equals() method. == operator can only compare primitive type value but instance of String is object.
So, your condition should be as follows...
if (textField.equals(title)){
dan_view.setTextColor(Color.GREEN);
} else {
dan_view.setTextColor(Color.RED);
}
== is for testing whether two strings are the same object; - reference equality.
You want to check the value so should use .equals()
Take a look at:
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
for further clarification.
Your error is here:
if (textField == title){ //<--
textField is a string, you need to check string equality using .equals(), e.g.
if (textField.equals(title)){ //<--
use this
if (textField.compareTo(title) == 0)
{
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
"textField == title" Using == will check that they are the exact same, not just value wise but also stored in the same memory location.
Instead try using
if (textField.equals(title)){
A good example is shown here http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

If statement with String comparison fails [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I really don't know why the if statement below is not executing:
if (s == "/quit")
{
System.out.println("quitted");
}
Below is the whole class.
It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.
Thanks for looking :)
class TextParser extends Thread {
public void run() {
while (true) {
for(int i = 0; i < connectionList.size(); i++) {
try {
System.out.println("reading " + i);
Connection c = connectionList.elementAt(i);
Thread.sleep(200);
System.out.println("reading " + i);
String s = "";
if (c.in.ready() == true) {
s = c.in.readLine();
//System.out.println(i + "> "+ s);
if (s == "/quit") {
System.out.println("quitted");
}
if(! s.equals("")) {
for(int j = 0; j < connectionList.size(); j++) {
Connection c2 = connectionList.elementAt(j);
c2.out.println(s);
}
}
}
} catch(Exception e){
System.out.println("reading error");
}
}
}
}
}
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>
Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().
However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b would be true. Why?
Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.
You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.
You can use
if("/quit".equals(s))
...
or
if("/quit".compareTo(s) == 0)
...
The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.
If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Categories

Resources