Why is == not working but .equals() is? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm only new to java and trying to make an equals code, but it won't work with ==, only with .equals() not sure why.
import java.lang.*;
import java.util.*;
public class password
{
public static void main(String args[])
{
Scanner Keyboard = new Scanner(System.in);
String guess = Keyboard.newLine();
String password = "1password";
if (guess == password) {
System.out.println("Welcome");
} else {
System.out.println("Login Failed");
}
}
}

I'm only new to java and trying to make an equals code, but it won't work with ==, only with .equals() not sure why
because == compares object references NOT the contents of the string.
You can find a great explanation at theJavaGeek
== checks whether two variables refer to the same object.
equals() method checks whether the contents of the object are same or not.
so If == returns true, then equals() method also returns true because they are referring to the same object hence they are equal(By equals() contract one object should be equal to itself)

Use the String.equals(String otherString) function to compare strings, not the == operator.
The reason is that == just compares object references,where as .equals() checks equality.

Strings should only be compared with .equals(), because with == you compare the Objects which are different.

trying to do == with string is checking reference equals. if the strings are exactly the same, meaning referenced to the same place, then it will be true, otherwise false
doing equals() check if the string matches, so if the strings contains the same values then you'll get true

Related

What is the logic behind == returning false [toString()] when two reference variables are referring to same Object having same hashCode? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
What is the logic behind == returning false when two reference variables are referring to same Object having same hash code values?
public class One {
public static void main(String[] args) {
One o = new One();
One o1 = o;
System.out.println(o.toString());
System.out.println(o1.toString());
System.out.println(o.hashCode());
System.out.println(o1.hashCode());
// Why does it print false ?
System.out.println(o.toString()==o1.toString()); // false
System.out.println(o.hashCode()==o1.hashCode()); // true
System.out.println(o.equals(o1)); // true
System.out.println(o.toString().hashCode()==o.toString().hashCode()); // true
}
}
The line with
System.out.println(o.toString()==o1.toString()); // false
has a toString(). Each toString() creates a new String Object, which are different Objects that have their own memory locations. So the == actually checks the memory addresses between those new String Objects.
Always compare strings with String#equals, not with ==.
== sign checks the memory addresses of objects being compared. In your case, toString() method creates two different String objects stored in two different places. That's why you get false when you try to compare them.
On the other hand, equals() checks the equality of contents of the objects. For your own data types, you should override this method to use it.
hashCode is some sort of a unique identification number for the contents of the objects. That is to say, objects that are equal to each other must return the same hashCode.

can someone explain why this returns the "else" value and not the "then" value? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
the java subSequence is clearly true but only returns the false value. why?
trying to see if a sequence is equal to a subsequence of a bigger string
package testifthen;
public class TestIfThen {
public static void main(String[] args) {
String result = "01900287491234567489";
String result1 = "90028749";
if (result.subSequence(2, 10) == result1) {
System.out.println("excel");
}else {
System.out.println("not found");
}
}}
It's hard to say without more information (for example what language is this in).
Assuming this is Java, I would say your problem is using == with strings instead of the .equals function.
== doesn't check the contents of the string, only if they are referencing the same object. .equals should be used instead as it actually checks whether the characters match in the two strings
Try using
if (result.subSequence(2, 10).equals(result1)) {
System.out.println("excel");
} else {
System.out.println("not found");
}
The == symbol might be the one causing it to return false because of the different references.
This post should explain more about differences between == and equals(): What is the difference between == vs equals() in Java?
In Java, the .equals method should be preferred to the == operator when checking for semantic equality. .equals should be used when you are checking if two values "mean" the same thing, whereas == checks if they're the same exact object.

Wrong results while String comparison [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal.
Here's the code with its problem:
//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
if(it.next() == args[0])
{
deal += it.next();
it.hasNext();
break;
}
}
Thank You!!!
To compare two strings u should use the method equals() or equalsIgnoreCase().
in your case:
if(it.next().equals(args[0]))
the operator == returns true if the two object are the same object, same address in memory.
You use .equals when comparing two strings. So use
(it.next()).equals(args[0])
You have to use .equals method:
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
String next = it.next();
if(next.equals(args[0]))
{
deal += next;
break;
}
}
Be careful, .next() returns the value once and move its internal cursor to the next value.
The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.
There are two ways of comparing strings.
Comparing the value of the strings (achieved using .equals ).
Comparing the actual object (achieved using == operator).
In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).
if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.
If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.

String comparison in java does not gives the desired results [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I tried with the following class :
public class EqualMethodTestWithNew {
public static void main(String[] args) {
String value = "xxx";
String name = new String("xxx") ;
System.out.println("hascode : value : "+value.hashCode());
System.out.println("hascode : name : "+name.hashCode());
if (value == name) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
}
}
though the hasCode is same for the both variable it prints the false == 1. could some one explain the reason why?
thanks
You need to understand what exactly is happening when you execute the 2 string statements.
String value = "xxx";
The above line creates a new compile time constant string which does into the String intern pool.
String name = new String("xxx") ;
But in this case, since you're using the new operator, it creates a new String object which goes in the object heap. It does not have the same address as the one which was created in the previous statement.
The hashCode() method is based on the contents of the String which are the same, but that doesn't mean that they both refer to the same String object in the memory.
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // would return same value for all String objects having the same content
To compare the values, you need to use equals() method.
And if you want to compare the object references use the == operator. In your case, since both refer to difference objects, you get the output as false.
Alternatively, you can ask the compiler to check and fetch the reference of a String with the same value already existing in the String pool by using the intern() method.
String value = "xxx";
String name = new String("xxx");
name = name.intern(); // getting reference from string pool
Now you'll get the output as equal == 1 when your do if (value == name) {.
You should be using equals method instead of == opertaor.
if (value.equals(name)) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
Note that:
== tests for reference equality.
.equals() tests for value equality.
Please see here for more information.
The reason why your code is not working is that == tests whether the reference to the object is the same, and that is not your case. To compare the value of the string, you need to use the .equals(String str) method.
if (value.equals(name)) {
...
}
String should be compared with equals() method, not ==. You are trying the check the equality of the memory address of both instances (actually they are not) instead of the value in the String instances. So, use
if(value.equals(name)) {
System.out.println("equal == 1");
}
Strings are compared using equal() method. == compares the two objects are equal are not.

Comparing java Strings with == [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
Is it possible to compare Java Strings using == operator?
Why do I often see, that equals() method is used instead?
Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?
there is no custom operator overloading in java. [so you cannot overload it to call equals()]
the equals() ensures you check if 2 Objects are identical,while == checks if this is the exact same object. [so no, using == does not invoke equals()].
== checks if the two objects refer to the same instance of an object, whereas equals() checks whether the two objects are actually equivalent even if they're not the same instance.
No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).
In Java, you cannot overload operators. The == operator does identity equality. The equals(...) method, on the other hand can be be overridden to do type-specific comparisons.
Here's a code snippet to demonstrate:
String a = "abcdef";
String b = a;
String c = new String(a);
println(a == b); // true
println(a.equals(b)); // true
println(a == c); // false
println(a.equals(c)); // true
The one complication is with equals(...) you need to care about null, too. So the correct null-safe idiom is:
(a == null ? b == null : a.equals(b))
This is a loop you don't have to jump through in say C#
To expand on #amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)
String is a class.So if you try to compare a String with its object that holding a string value you can't use == as it is looking for an object.For comparing the contents of the object you have to use equals
Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.
From what I know the '==' operator is used to check whether or not to objects are identical.
The presumable compared strings might have the same value(nr of chars etc), but be in fact two totally different objects, thus rendering the comparison false.
== returns true if the memory address is equal on both sides, except for primitive types.
equals should be used on everything that isn't a primitive. classes for the main part.
== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.
String str1=new String("abc");
String str2=new String("abc");
System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" .
System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.
As amit already said, == checks for being the same object whereas equals() checks for the same content (ok, the basic implementation is equal to == but String overrides this).
Note:
"Hello" == "Hello" //most probably would be true
"Hello".equals( "Hello" ) //will be true
String s1, s2; //initialize with something different than a literal, e.g. loading from a file, both should contain the same string
s1 == s2 //most probably will NOT be true
s1.equals( s2) //will be true, if both contain the same string, e.g. "Hello"
Besides that, the same holds true for object wrappers of primitives, e.g.
Long l1 = 1L;
Long l2 = 1L;
l1 == l2 //will most likely be true for small numbers, since those literals map to cached instances
l1.equals(l2) //will be true
new Long(1) == new Long(1) //will NOT be true
new Long(1).equals(new Long(1)) //will be true

Categories