Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}
Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.
Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1; // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.
equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.
== operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.
Hope you understood the difference between == and <Object>.equals()
Thanks.
== tests for reference equality.
.equals() tests for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same Object.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.
Instead of
datos[0] == usuario
use
datos[0].equals(usuario)
== compares the reference of the variable where .equals() compares the values which is what you want.
Let's analyze the following Java, to understand the identity and equality of Strings:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
When the first line of code String str1 = "Hello world." executes, a string \Hello world."
is created, and the variable str1 refers to it. Another string "Hello world." will not be created again when the next line of code executes because of optimization. The variable str2 also refers to the existing ""Hello world.".
The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.
When code String str3 = new String("Hello world.") executes, a new instance of string with content "Hello world." is created, and it is referred to by the variable str3. And then another instance of string with content "Hello world." is created again, and referred to by
str4. Since str3 and str4 refer to two different instances, they are not identical, but their
content are same.
Therefore, the output contains four lines:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
You should use string equals to compare two strings for equality, not operator == which just compares the references.
It will also work if you call intern() on the string before inserting it into the array.
Interned strings are reference-equal (==) if and only if they are value-equal (equals().)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
Generally .equals is used for Object comparison, where you want to verify if two Objects have an identical value.
== for reference comparison (are the two Objects the same Object on the heap) & to check if the Object is null. It is also used to compare the values of primitive types.
== operator compares the reference of an object in Java. You can use string's equals method .
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}
If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
Example:
String a = "name";
String b = "name";
if(a == b) and (a.equals(b)) will return true.
But
String a = new String("a");
In this case if(a == b) will return false
So it's better to use the .equals operator...
The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.
I know this is an old question but here's how I look at it (I find very useful):
Technical explanations
In Java, all variables are either primitive types or references.
(If you need to know what a reference is: "Object variables" are just pointers to objects. So with Object something = ..., something is really an address in memory (a number).)
== compares the exact values. So it compares if the primitive values are the same, or if the references (addresses) are the same. That's why == often doesn't work on Strings; Strings are objects, and doing == on two string variables just compares if the address is same in memory, as others have pointed out. .equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.
The interesting part:
So why does == sometimes return true for Strings? Note that Strings are immutable. In your code, if you do
String foo = "hi";
String bar = "hi";
Since strings are immutable (when you call .trim() or something, it produces a new string, not modifying the original object pointed to in memory), you don't really need two different String("hi") objects. If the compiler is smart, the bytecode will read to only generate one String("hi") object. So if you do
if (foo == bar) ...
right after, they're pointing to the same object, and will return true. But you rarely intend this. Instead, you're asking for user input, which is creating new strings at different parts of memory, etc. etc.
Note: If you do something like baz = new String(bar) the compiler may still figure out they're the same thing. But the main point is when the compiler sees literal strings, it can easily optimize same strings.
I don't know how it works in runtime, but I assume the JVM doesn't keep a list of "live strings" and check if a same string exists. (eg if you read a line of input twice, and the user enters the same input twice, it won't check if the second input string is the same as the first, and point them to the same memory). It'd save a bit of heap memory, but it's so negligible the overhead isn't worth it. Again, the point is it's easy for the compiler to optimize literal strings.
There you have it... a gritty explanation for == vs. .equals() and why it seems random.
#Melkhiah66 You can use equals method instead of '==' method to check the equality.
If you use intern() then it checks whether the object is in pool if present then returns
equal else unequal. equals method internally uses hashcode and gets you the required result.
public class Demo
{
public static void main(String[] args)
{
String str1 = "Jorman 14988611";
String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
String str3 = str2.intern();
System.out.println("str1 == str2 " + (str1 == str2)); //gives false
System.out.println("str1 == str3 " + (str1 == str3)); //gives true
System.out.println("str1 equals str2 " + (str1.equals(str2))); //gives true
System.out.println("str1 equals str3 " + (str1.equals(str3))); //gives true
}
}
The .equals() will check if the two strings have the same value and return the boolean value where as the == operator checks to see if the two strings are the same object.
Someone said on a post higher up that == is used for int and for checking nulls.
It may also be used to check for Boolean operations and char types.
Be very careful though and double check that you are using a char and not a String.
for example
String strType = "a";
char charType = 'a';
for strings you would then check
This would be correct
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
would be incorrect, you would need to do the following
if(charType == 'a')
do something else
a==b
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object
"a".equals("b")
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.
Use Split rather than tokenizer,it will surely provide u exact output
for E.g:
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
After this I am sure you will get better results.....
I wanted to clarify if I understand this correctly:
== is a reference comparison, i.e. both objects point to the same memory location
.equals() evaluates to the comparison of values in the objects
In general, the answer to your question is "yes", but...
.equals(...) will only compare what it is written to compare, no more, no less.
If a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
Always remember to override hashCode if you override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.
With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.
There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...
Here is an example (you can run it):
public final class MyEqualityTest
{
public static void main( String args[] )
{
String s1 = new String( "Test" );
String s2 = new String( "Test" );
System.out.println( "\n1 - PRIMITIVES ");
System.out.println( s1 == s2 ); // false
System.out.println( s1.equals( s2 )); // true
A a1 = new A();
A a2 = new A();
System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true
B b1 = new B();
B b2 = new B();
System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
System.out.println( b1 == b2 ); // false
System.out.println( b1.getS() == b2.getS() ); // false
System.out.println( b1.getS().equals( b2.getS() ) ); // true
}
}
final class A
{
// static
public static String s;
A()
{
this.s = new String( "aTest" );
}
}
final class B
{
private String s;
B()
{
this.s = new String( "aTest" );
}
public String getS()
{
return s;
}
}
You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links:
==: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
.equals(...): http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
The difference between == and equals confused me for sometime until I decided to have a closer look at it.
Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.
The best way to answer this question will be by asking a few questions to yourself. so let's start:
What is the output for the below program:
String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);
if you say,
false
true
I will say you are right but why did you say that?
and If you say the output is,
true
false
I will say you are wrong but I will still ask you, why you think that is right?
Ok, Let's try to answer this one:
What is the output for the below program:
String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);
Now If you say,
false
true
I will say you are wrong but why is it wrong now?
the correct output for this program is
true
false
Please compare the above program and try to think about it.
Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)
String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));
can you just try to think about the output of the last three lines in the code above:
for me ideone printed this out (you can check the code here):
false
true
true
false
mango mango
false
true
17225372
17225372
5433634
Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)
Even though all the string variables - mango, mango2 and mango3 - have the same value, which is "mango", identityHashCode() is still not the same for all.
Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different.
Hmm that is a helpful hint
we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y
I am not sure how java works internally but I assume this is what happened when I said:
mango = "mango";
java created a string "mango" which was pointed(referenced) by the variable mango something like this
mango ----> "mango"
Now in the next line when I said:
mango2 = "mango";
It actually reused the same string "mango" which looks something like this
mango ----> "mango" <---- mango2
Both mango and mango2 pointing to the same reference
Now when I said
mango3 = new String("mango")
It actually created a completely new reference(string) for "mango". which looks something like this,
mango -----> "mango" <------ mango2
mango3 ------> "mango"
and that's why when I put out the values for mango == mango2, it put out true. and when I put out the value for mango3 == mango2, it put out false (even when the values were the same).
and when you uncommented the line // mango2 = "mang";
It actually created a string "mang" which turned our graph like this:
mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"
This is why the identityHashCode is not the same for all.
Hope this helps you guys.
Actually, I wanted to generate a test case where == fails and equals() pass.
Please feel free to comment and let me know If I am wrong.
The == operator tests whether two variables have the same references
(aka pointer to a memory address).
String foo = new String("abc");
String bar = new String("abc");
if(foo==bar)
// False (The objects are not the same)
bar = foo;
if(foo==bar)
// True (Now the objects are the same)
Whereas the equals() method tests whether two variables refer to objects
that have the same state (values).
String foo = new String("abc");
String bar = new String("abc");
if(foo.equals(bar))
// True (The objects are identical but not same)
Cheers :-)
You will have to override the equals function (along with others) to use this with custom classes.
The equals method compares the objects.
The == binary operator compares memory addresses.
== is an operator and equals() is a method.
Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.
String w1 ="Sarat";
String w2 ="Sarat";
String w3 = new String("Sarat");
System.out.println(w1.hashCode()); //3254818
System.out.println(w2.hashCode()); //3254818
System.out.println(w3.hashCode()); //3254818
System.out.println(System.identityHashCode(w1)); //prints 705927765
System.out.println(System.identityHashCode(w2)); //prints 705927765
System.out.println(System.identityHashCode(w3)); //prints 366712642
if(w1==w2) // (705927765==705927765)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
if(w2==w3) // (705927765==366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints false
if(w2.equals(w3)) // (Content of 705927765== Content of 366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
Both == and .equals() refers to the same object if you don't override .equals().
Its your wish what you want to do once you override .equals(). You can compare the invoking object's state with the passed in object's state or you can just call super.equals()
Here is a general thumb of rule for the difference between relational operator == and the method .equals().
object1 == object2 compares if the objects referenced by object1 and object2 refer to the same memory location in Heap.
object1.equals(object2) compares the values of object1 and object2 regardless of where they are located in memory.
This can be demonstrated well using String
Scenario 1
public class Conditionals {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println("is str1 == str2 ? " + (str1 == str2 ));
System.out.println("is str1.equals(str2) ? " + (str1.equals(str2 )));
}
}
The result is
is str1 == str2 ? false
is str1.equals(str2) ? true
Scenario 2
public class Conditionals {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
System.out.println("is str1 == str2 ? " + (str1 == str2 ));
System.out.println("is str1.equals(str2) ? " + (str1.equals(str2 )));
}
}
The result is
is str1 == str2 ? true
is str1.equals(str2) ? true
This string comparison could be used as a basis for comparing other types of object.
For instance if I have a Person class, I need to define the criteria base on which I will compare two persons. Let's say this person class has instance variables of height and weight.
So creating person objects person1 and person2 and for comparing these two using the .equals() I need to override the equals method of the person class to define based on which instance variables(heigh or weight) the comparison will be.
However, the == operator will still return results based on the memory location of the two objects(person1 and person2).
For ease of generalizing this person object comparison, I have created the following test class. Experimenting on these concepts will reveal tons of facts.
package com.tadtab.CS5044;
public class Person {
private double height;
private double weight;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(height);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
#Override
/**
* This method uses the height as a means of comparing person objects.
* NOTE: weight is not part of the comparison criteria
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (Double.doubleToLongBits(height) != Double.doubleToLongBits(other.height))
return false;
return true;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.setHeight(5.50);
person1.setWeight(140.00);
Person person2 = new Person();
person2.setHeight(5.70);
person2.setWeight(160.00);
Person person3 = new Person();
person3 = person2;
Person person4 = new Person();
person4.setHeight(5.70);
Person person5 = new Person();
person5.setWeight(160.00);
System.out.println("is person1 == person2 ? " + (person1 == person2)); // false;
System.out.println("is person2 == person3 ? " + (person2 == person3)); // true
//this is because perosn3 and person to refer to the one person object in memory. They are aliases;
System.out.println("is person2.equals(person3) ? " + (person2.equals(person3))); // true;
System.out.println("is person2.equals(person4) ? " + (person2.equals(person4))); // true;
// even if the person2 and person5 have the same weight, they are not equal.
// it is because their height is different
System.out.println("is person2.equals(person4) ? " + (person2.equals(person5))); // false;
}
}
Result of this class execution is:
is person1 == person2 ? false
is person2 == person3 ? true
is person2.equals(person3) ? true
is person2.equals(person4) ? true
is person2.equals(person4) ? false
Just remember that .equals(...) has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.
The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum
enum FooEnum {A, B, C}
You will never have more than one instance of A at a time, and the same for B and C. This means that you can actually write a method like so:
public boolean compareFoos(FooEnum x, FooEnum y)
{
return (x == y);
}
And you will have no problems whatsoever.
When you evaluate the code, it is very clear that (==) compares according to memory address, while equals(Object o) compares hashCode() of the instances.
That's why it is said do not break the contract between equals() and hashCode() if you do not face surprises later.
String s1 = new String("Ali");
String s2 = new String("Veli");
String s3 = new String("Ali");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println("(s1==s2):" + (s1 == s2));
System.out.println("(s1==s3):" + (s1 == s3));
System.out.println("s1.equals(s2):" + (s1.equals(s2)));
System.out.println("s1.equal(s3):" + (s1.equals(s3)));
/*Output
96670
3615852
96670
(s1==s2):false
(s1==s3):false
s1.equals(s2):false
s1.equal(s3):true
*/
The major difference between == and equals() is
1) == is used to compare primitives.
For example :
String string1 = "Ravi";
String string2 = "Ravi";
String string3 = new String("Ravi");
String string4 = new String("Prakash");
System.out.println(string1 == string2); // true because same reference in string pool
System.out.println(string1 == string3); // false
2) equals() is used to compare objects.
For example :
System.out.println(string1.equals(string2)); // true equals() comparison of values in the objects
System.out.println(string1.equals(string3)); // true
System.out.println(string1.equals(string4)); // false
Example 1 -
Both == and .equals methods are there for reference comparison only. It means whether both objects are referring to same object or not.
Object class equals method implementation
public class HelloWorld{
public static void main(String []args){
Object ob1 = new Object();
Object ob2 = ob1;
System.out.println(ob1 == ob2); // true
System.out.println(ob1.equals(ob2)); // true
}
}
Example 2 -
But if we wants to compare objects content using equals method then class has to override object's class equals() method and provide implementation for content comparison. Here, String class has overrided equals method for content comparison. All wrapper classes have overrided equals method for content comparison.
String class equals method implementation
public class HelloWorld{
public static void main(String []args){
String ob1 = new String("Hi");
String ob2 = new String("Hi");
System.out.println(ob1 == ob2); // false (Both references are referring two different objects)
System.out.println(ob1.equals(ob2)); // true
}
}
Example 3 -
In case of String, there is one more usecase. Here when we assign any string to String reference then string constant is created inside String constant pool. If we assign same string to new String reference then no new string constant is created rather it will refer to existing string constant.
public class HelloWorld{
public static void main(String []args){
String ob1 = "Hi";
String ob2 = "Hi";
System.out.println(ob1 == ob2); // true
System.out.println(ob1.equals(ob2)); // true
}
}
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Java API equals() method contract
Also note that .equals() normally contains == for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.
And == actually does look at values for primitive types, for objects it checks the reference.
== operator always reference is compared. But in case of
equals() method
it's depends's on implementation if we are overridden equals method than it compares object on basic of implementation given in overridden method.
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//fasle
obj==obj1 // fasle
}
}
in above code both obj and obj1 object contains same data but reference is not same so equals return false and == also.
but if we overridden equals method than
class A
{
int id;
String str;
public A(int id,String str)
{
this.id=id;
this.str=str;
}
public boolean equals(Object obj)
{
A a1=(A)obj;
return this.id==a1.id;
}
public static void main(String arg[])
{
A obj=new A(101,"sam");
A obj1=new A(101,"sam");
obj.equals(obj1)//true
obj==obj1 // fasle
}
}
know check out it will return true and false for same case only we overridden
equals method .
it compare object on basic of content(id) of object
but ==
still compare references of object.
== can be used in many object types but you can use Object.equals for any type , especially Strings and Google Map Markers.
public class StringPool {
public static void main(String[] args) {
String s1 = "Cat";// will create reference in string pool of heap memory
String s2 = "Cat";
String s3 = new String("Cat");//will create a object in heap memory
// Using == will give us true because same reference in string pool
if (s1 == s2) {
System.out.println("true");
} else {
System.out.println("false");
}
// Using == with reference and Object will give us False
if (s1 == s3) {
System.out.println("true");
} else {
System.out.println("false");
}
// Using .equals method which refers to value
if (s1.equals(s3)) {
System.out.println("true");
} else {
System.out.println("False");
}
}
}
----Output-----
true
false
true
It may be worth adding that for wrapper objects for primitive types - i.e. Int, Long, Double - == will return true if the two values are equal.
Long a = 10L;
Long b = 10L;
if (a == b) {
System.out.println("Wrapped primitives behave like values");
}
To contrast, putting the above two Longs into two separate ArrayLists, equals sees them as the same, but == doesn't.
ArrayList<Long> c = new ArrayList<>();
ArrayList<Long> d = new ArrayList<>();
c.add(a);
d.add(b);
if (c == d) System.out.println("No way!");
if (c.equals(d)) System.out.println("Yes, this is true.");
The String pool (aka interning) and Integer pool blur the difference further, and may allow you to use == for objects in some cases instead of .equals
This can give you greater performance (?), at the cost of greater complexity.
E.g.:
assert "ab" == "a" + "b";
Integer i = 1;
Integer j = i;
assert i == j;
Complexity tradeoff: the following may surprise you:
assert new String("a") != new String("a");
Integer i = 128;
Integer j = 128;
assert i != j;
I advise you to stay away from such micro-optimization, and always use .equals for objects, and == for primitives:
assert (new String("a")).equals(new String("a"));
Integer i = 128;
Integer j = 128;
assert i.equals(j);
In short, the answer is "Yes".
In Java, the == operator compares the two objects to see if they point to the same memory location; while the .equals() method actually compares the two objects to see if they have the same object value.
It is the difference between identity and equivalence.
a == b means that a and b are identical, that is, they are symbols for very same object in memory.
a.equals( b ) means that they are equivalent, that they are symbols for objects that in some sense have the same value -- although those objects may occupy different places in memory.
Note that with equivalence, the question of how to evaluate and compare objects comes into play -- complex objects may be regarded as equivalent for practical purposes even though some of their contents differ. With identity, there is no such question.
Since Java doesn’t support operator overloading, == behaves identical
for every object but equals() is method, which can be overridden in
Java and logic to compare objects can be changed based upon business
rules.
Main difference between == and equals in Java is that "==" is used to
compare primitives while equals() method is recommended to check
equality of objects.
String comparison is a common scenario of using both == and equals() method. Since java.lang.String class override equals method, It
return true if two String object contains same content but == will
only return true if two references are pointing to same object.
Here is an example of comparing two Strings in Java for equality using == and equals() method which will clear some doubts:
public class TEstT{
public static void main(String[] args) {
String text1 = new String("apple");
String text2 = new String("apple");
//since two strings are different object result should be false
boolean result = text1 == text2;
System.out.println("Comparing two strings with == operator: " + result);
//since strings contains same content , equals() should return true
result = text1.equals(text2);
System.out.println("Comparing two Strings with same content using equals method: " + result);
text2 = text1;
//since both text2 and text1d reference variable are pointing to same object
//"==" should return true
result = (text1 == text2);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);
}
}
Basically, == compares if two objects have the same reference on the heap, so unless two references are linked to the same object, this comparison will be false.
equals() is a method inherited from Object class. This method by default compares if two objects have the same referece. It means:
object1.equals(object2) <=> object1 == object2
However, if you want to establish equality between two objects of the same class you should override this method. It is also very important to override the method hashCode() if you have overriden equals().
Implement hashCode() when establishing equality is part of the Java Object Contract. If you are working with collections, and you haven't implemented hashCode(), Strange Bad Things could happen:
HashMap<Cat, String> cats = new HashMap<>();
Cat cat = new Cat("molly");
cats.put(cat, "This is a cool cat");
System.out.println(cats.get(new Cat("molly"));
null will be printed after executing the previous code if you haven't implemented hashCode().
In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
equals() method mainly compares the original content of the object.
If we Write
String s1 = "Samim";
String s2 = "Samim";
String s3 = new String("Samim");
String s4 = new String("Samim");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
The output will be
true
true
true
Because equals() method compare the content of the object.
in first System.out.println() the content of s1 and s2 is same that's why it print true.
And it is same for others two System.out.println() is true.
Again ,
String s1 = "Samim";
String s2 = "Samim";
String s3 = new String("Samim");
String s4 = new String("Samim");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s3 == s4);
The output will be
true
false
false
Because == operator mainly compare the references of the object not the value.
In first System.out.println(), the references of s1 and s2 is same thats why it returns true.
In second System.out.println(), s3 object is created , thats why another reference of s3 will create , and the references of s2 and s3 will difference, for this reason it return "false".
Third System.out.println(), follow the rules of second System.out.println(), that's why it will return "false".
This question already has answers here:
How do I compare strings in Java?
(23 answers)
What's the difference between ".equals" and "=="? [duplicate]
(11 answers)
Closed 9 years ago.
This is the piece of code I used from the SCJP book.
I understand that == compares the memory location of the objects to find the equality and .equals compares the hashcode to determine the equality.
My question is in the below snippet, in the overrided equals method we compare :
(((Moof)o).getMoofValue()) == this.getMoofValue()
in the above code, does the == compare the memory location of the string value? If it does then it should be false. But it returns true. How does the == work here?
public class EqualsTest {
public static void main(String args[]){
Moof one = new Moof("a");
Moof two = new Moof("a");
if(one.equals(two)){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
public class Moof {
private String moofValue;
public Moof(String i){
this.moofValue = i;
}
public String getMoofValue(){
return this.moofValue;
}
public boolean equals(Object o){
if((o instanceof Moof) && (((Moof)o).getMoofValue()) == this.getMoofValue()){
return true;
}
return false;
}
}
(Moof)o).getMoofValue()) == this.getMoofValue())
here..You are still comparing references to the same String object in the String pool. Because String literals are interned automatically.
Edit :
public class TestClass {
String s;
TestClass(String s) {
this.s = s;
}
public static void main(String[] args) {
String s1 = new String("a");
String s2 = new String("a");
System.out.println(s1 == s2);
TestClass t1 = new TestClass("a");
TestClass t2 = new TestClass("a");
System.out.println(t1 == t2); // here you are comparing t1 with t2, not t1.s with t2.s so you get false...
System.out.println(t1.s == t2.s); // t1.s and t2.s refer to the same "a", so you get true.
TestClass t3 = new TestClass(s1);
TestClass t4 = new TestClass(s2);
System.out.println(t3.s == t4.s); // false because s1 and s2 are 2 different references.
}
}
O/P :
false
false
true
false
The "a" string literals are interned. Each "a" is the same string in memory, so they compare equal with ==. Note that you can't rely on this for strings in general. If you did the following:
Moof two = new Moof("aa".substring(1));
the strings would be considered != to each other.
You are right that == compares if the references point to the same object. So, two different objects would evaluate to false with == even if equals() would evaluate to true.
S the following code
(((Moof)o).getMoofValue()) == this.getMoofValue()
checks if the objects are the same. However, in Java two equal string constants that are known at compile time must reference the same string object. Looking at
Moof one = new Moof("a");
Moof two = new Moof("a");
We could view this as
String theValue = "a";
Moof one = new Moof(theValue);
Moof two = new Moof(theValue);
However, making a new string must return a new object so you can try
Moof one = new Moof(new String("a"));
Moof two = new Moof(new String)"a");
which would cause the equality to evaluate to false. More specific example below:
String a1 = "a";
String a2 = "a";
String a3 = new String("a");
System.out.println(a1 == a2); // true
System.out.println(a1 == a3); // false
Equals does normally not use hashCode to check for equality but it could be used to make a quick check if more comparisons are needed. The hashCode is a numerical indicator of the object, which if you implemented a PersonId class could be a numerical value of the country phone prefix and age of the person. So a 27 year old person from Sweden would get hash code 4627. Now, when checking if two PersonId refers to the same person you might have to do a lot of comparisons, but if the hashCode is not the same then no more comparisons are needed (since either the country or age is different and the PersonIds must refer to different persons).
The hashCode is used in structures such as HashMap as a value for knowing which "bucket" to store the object in.
I understand that == compares the memory location of the objects to find the equality and .equals compares the hashcode to determine the equality.
No it doesn't. .equals() does whatever the guy who wrote it wrote. In the case of Object.equals(), it returns the result of ==. hashCode() has nothing to do with it.
in the above code, does the == compare the memory location of the string value?
Yes, you've already said that.
If it does then it should be false. But it returns true. How does the == work here?
Because both occurrences of "a" are pooled to the same value, with the same address.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java string comparison?
I was trying to do this:
boolean exit = false;
while(exit==false && convStoreIndex<convStoreLength) {
if(conversionStore[convStoreIndex].getInUnit()==inUnit) {
indexCount++;
exit=true;
}
convStoreIndex++;
}
but the if-condition never went true, even if the two Strings were the same(checked this in the debugger).
so I added some lines:
boolean exit = false;
while(exit==false && convStoreIndex<convStoreLength) {
Log.v("conversionStore["+String.valueOf(convStoreIndex)+"]", conversionStore[convStoreIndex].getInUnit()+"|"+inUnit);
String cs = conversionStore[convStoreIndex].getInUnit();
String iu = inUnit;
Log.v("cs", cs);
Log.v("iu", iu);
Log.v("Ergebnis(cs==iu)", String.valueOf(cs==iu));
if(conversionStore[convStoreIndex].getInUnit()==inUnit) {
indexCount++;
exit=true;
}
convStoreIndex++;
}
and here is the extract from LogCat:
09-15 11:07:14.525: VERBOSE/cs(585): kg
09-15 11:07:16.148: VERBOSE/iu(585): kg
09-15 11:07:17.687: VERBOSE/Ergebnis(cs==iu)(585): false
the class of conversionStore:
class ConversionStore {
private String inUnit;
[...]
public String getInUnit() {
return inUnit;
}
}
Who is going crazy, java or me?
Don't use == to compare String objects, use .equals():
if(conversionStore[convStoreIndex].getInUnit().equals(inUnit)) {
To compare Strings for equality, don't use ==. The == operator checks
to see if two objects are exactly the same object. Two strings may be
different objects, but have the same value (have exactly the same
characters in them). Use the .equals() method to compare strings for
equality.
Straight from the first link Google provided when searching "Java string comparison"...
Please use String.equals() to compare by string content instead of reference identity.
You are comparing your Strings using == : cs==iu.
But this will return true only if both Strings are actually the same object. This is not the case here: you have two distinct instances of String that contain the same value.
You should use String.compareTo(String).
use .equals(); method instread of ==
Becase ::
They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.
For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.
s1 = new String("abc");
s2 = new String("abc");
Now, if you use the "equals()" method to check for their equivalence as
if(s1.equals(s2))
System.out.println("s1.equals(s2) is TRUE");
else
System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.
Lets check the '==' operator..
if(s1==s2)
System.out.printlln("s1==s2 is TRUE");
else
System.out.println("s1==s2 is FALSE");
Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.
Try running the program without 'new String' and just with
String s1 = "abc";
String s2 = "abc";
You will get TRUE for both the tests.
Reson::
After the execution of String str1 = “Hello World!”; the JVM adds the string “Hello World!” to the string pool and on next line of the code, it encounters String str2 =”Hello World!”; in this case the JVM already knows that this string is already there in pool, so it does not create a new string. So both str1 and str2 points to the same string means they have same references. However, str3 is created at runtime so it refers to different string.
Two things:
You don't need to write "boolean==false" you can just write "!boolean" so in your example that would be:
while(!exit && convStoreIndex<convStoreLength) {
Second thing:
to compare two Strings use the String.equals(String x) method, so that would be:
if(conversionStore[convStoreIndex].getInUnit().equals(inUnit)) {
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 6 years ago.
I switched lecturers today and he stated using a weird code to me. (He said it's better to use .equals and when I asked why, he answered "because it is!")
So here's an example:
if (o1.equals(o2))
{
System.out.println("Both integer objects are the same");
}
Instead of what I'm used to:
if (o1 == o2)
{
System.out.println("Both integer objects are the same");
}
What's the difference between the two. And why is his way (using .equals) better?
Found this on a quick search but I can't really make sense of that answer:
In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!
Here x and y are references to the same string, because y is a compile-time constant equal to "hello".
The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.
If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...
myAccount.equals(yourAccount) is true because they have the same value, but
myAccount == yourAccount is false because they are not the same account.
(Assuming appropriate definitions of the Account class, of course. ;-)
== is an operator. equals is a method defined in the Object class
== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that
if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).
== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example
public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
}}
above example == is a reference comparison i.e. both objects point to the same memory location
String equals() is evaluates to the comparison of values in the objects.
public class EqualsExample1{
public static void main(String args[]){
String s = "Hell";
String s1 =new string( "Hello");
String s2 =new string( "Hello");
s1.equals(s2); //true
s.equals(s1) ; //false
}}
above example It compares the content of the strings. It will return true if string matches, else returns false.
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
System.out.println("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
Even though the strings have the same exact characters (“xyz”), The code above will actually output:
obj1==obj2 is FALSE
Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
System.out.printlln("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
This code will output the following:
obj1==obj2 is TRUE
public static void main(String[] args){
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
////
System.out.println(s1 == s2);
System.out.println("-----------------------------");
String s3 = "hello";
String s4 = "hello";
System.out.println(s3.equals(s4));
////
System.out.println(s3 == s4);
}
Here in this code u can campare the both '==' and '.equals'
here .equals is used to compare the reference objects and '==' is used to compare state of objects..
The equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1 refers to the String instance created by “Hello”. The object referred to by
s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical,
but they are distinct objects. This means that s1 and s2 do not refer to the same objects and
are, therefore, not ==, as is shown here by the output of the preceding example:
Hello equals Hello -> true
Hello == Hello -> false
Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values
public static void main(String [] args){
String s1 = "Hello";
String s1 = "Hello"; // This is not possible to assign multiple values to single object
if(s1 == s1){
// Now this retruns true
}
}
Now when this happens practically speaking, If its not happen then why this is == compares functionality....
(1) == can be be applied for both primitives and object types, but equals() method can be applied for only object types.
(2) == cannot be overridden for content comparison, but equals method can be overridden for content comparison(ex; String class, wrapper classes, collection classes).
(3) == gives incomparable types error when try to apply for heterogeneous types , where as equals method returns false.
Here is a simple interpretation about your problem:
== (equal to) used to evaluate arithmetic expression
where as
equals() method used to compare string
Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.