Using "==" in Java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 3 years ago.
public class Test {
public static void main(String[] args)
{
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
}
}
But when I use :
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); // false
}
}
Can anybody please explain the difference here? Thankyou!

In the first example
String s1 = "HELLO";
String s2 = "HELLO";
the values of s1 and s2 are compile-time constants. Thus, the compiler does only generate a single String-object, holding the value "HELLO" and assings it to both s1 and s2. This is a special case of Common Subexpression Elimination, a well-known compiler optimization. Thus s1 == s2 returns true.
In the second example, two different Strings are constructed explicitly through new. Thus, they have to be separate objects per the semantics of new.
I created an Ideone demo a while back that highlights some cases that show this behaviour.
You can enforce that the same String is return by using String::intern():
String s1 = new String("HELLO").intern();
String s2 = new String("HELLO").intern();
System.out.println(s1 == s2); // will print "true";
Ideone demo

In case of String literal,before creating new Object in String Constant Pool ,JVM will check already same Object persist in SCP area or not if yes it will point to same object instead of creating new Object.Hence, below code s1 == s2 is true
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
but we are creating new object by using new keyword, it will create object in heap area, hence s1 and s2 are pointing to two different object, hence it is return false

== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
from here How do I compare strings in Java?

== compares the objects reference pointer. When 2 objects are same exact object it will be true.
Instantiating a string using double quotes uses the string pool, creates a string once and reuses it.
Instantiating a string wit new always creates a brand new string.

== tests for reference equality (whether they are the same object).
First Case
System.out.println(s1 == s2); // true
Because you are comparing literals that are interned by the compiler and thus refer to the same object. Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions - are "interned" so as to share unique instances, using the method String.intern.
Second Case
System.out.println(s1 == s2); // false
You are comparing the Object reference which is different so you are getting false.
Please check https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28

i first case u comparing two strings with its ASCII values. thats why...//true
and in second case you are comparing two functions/methods. thats why... //false

the first one is true because s1 and s2 refer to the same string literal in the method area, the memory references are the same. ( == checks just the references in string). when the same string literal is created more than once, only one copy of each distinct string value is stored.
the second one is false because s1 and s2 refer to two different objects in the heap. different objects always have different memory references.

Related

Substring in if statement [duplicate]

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

In Java, by new operator is it possible to create different objects with same String content? [duplicate]

This question already has answers here:
Does java optimize string literal toLowerCase()?
(2 answers)
How do I compare strings in Java?
(23 answers)
How == returns false even though two Strings s1 and s3 having same hashcode? [duplicate]
(4 answers)
Closed 3 years ago.
In the below code, by hashCode() it seems 2 objects got created. Then although s1 == s3 is giving true, but why s1 == s4 is giving false ?
public class Main {
public static void main(String[] args) {
String s1 = new String("jordi") ;
String s2 = s1.toUpperCase() ;
String s3 = s1.toLowerCase() ;
String s4 = new String("jordi") ;
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1==s4);
}
}
This gives output as :
101312786
70775026
101312786
101312786
false
true
false
s1 == s4
This performs reference comparison. So you're comparing the is both s1 and s4 point to the same object or not (which they don't - since you explicitly created two different objects)
When we use == operator for s1 and s4 comparison then it is false since both have different addresses in memory. It compares for memory address
Value objects (objects whose identity is unimportant and whose value is the only important thing about them, such as String and Integer), override equals and hashCode so that, for example, they can be used as keys in a HashMap. The hashCode value for String is specified in detail specifically so that any two strings with the same content will hash to the same value.
Your s1 and s3 are the same object because String#toLowerCase() has an optimization that returns this and avoids creating a new object if the entire string is already lowercase.
Use the .equals method instead of == for strings. Java gets a little screwy when you try to compare two strings with == instead of .equals()
Here's your code but fixed.
public static void main(String[] args) {
String s1 = new String("jordi");
String s2 = s1.toUpperCase();
String s3 = s1.toLowerCase();
String s4 = new String("jordi");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}

String literals vs string objects hashcode [duplicate]

This question already has answers here:
why '==' is returning false even after my hashcode value is same
(3 answers)
Closed 5 years ago.
I read that strings declared as literals are created on String Constant Pool
String s1 = "Hello";
String s2 = "Hello"; -> This will not create a new object and will refer to the s1 reference.
And strings declared with new keyword are created on both Heap Memory and String Constant Pool
String s3 = new String("Hello"); -> This will create a new object in the heap.
But will it create a new constant in the String Constant Pool also or will it use the one from s1?
I have this following code.
Hashcode for all s1, s2, and s3 are return as same.
public class question1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3); // not sure why false result, s3 will create a separate constant in the pool? There is already a constant with value "Hello" created by s1. Please confirm if s3 will again create a constant.
}
}
I understant that == compares the object.
Are there two "Hello" defined in the String Constant Pool, one from s1 and one from s3?
String literals are automatically "interned," which places them in a pool. This minimizes the number of instances required. So, the two literals use the same String instance. hashCode() operates on the contents of the String in a consistent way. If two String instances have the same characters, then they will have the same hash code.

Java String Objects [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have the following code:
public class Porow{
public static void main (String[] args){
String s1 = "foo";
String s2 = "foo";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
String s3 = new String ("foo");
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}
which outputs:
true
true
false
true
I am trying to understand and explain what's going on here. And I need some guidance. Will I be right to say s1 and s2 are same objects stored in different parts of memory and that's why we get the first 2 trues?
Why is the 3rd output false? is s3 a different object? and why does it produce true with the equals method on s1? I'd appreciate some help. Thanks :).
EDIT:
This question is not about == nor equals() I know what they are. My question is more related to memory references and addresses. So don't just presume I'm asking about String Comparison. I'm asking about a whole different thing here.
That's because in the 3rd scenario, a new object is created(the new keyword creates a new string object) and == is used for object reference equality. That's why it returns false.
Whereas the equals() method is used for String value equality, and hence, it returns true.
In the first and second case, the "foo" String literal is interned and thus, both s1 and s2 refer the same String literal.
The == operator checks reference equivalence. If the two references are equivalent, then they're the same instance.
Your first example works because the strings are interned - but don't rely on this. equals() actually checks to see if the two Strings contain the same data.
With the new keyword, a new reference is created for the other string - hence, they no longer point to the same instance.
Because == tests that the strings refer to the same object and equals tests if they are equivalent. Your line
String s3 = new String ("foo");
constructs a new reference to the constant "foo" String. Take a look at What is String interning? for a bit more, but be aware that interning will use PermGen space.
String are put into a String pool
When you have
String s1 = "foo";
String s2 = "foo";
Only one "foo" is placed into the String pool.
So
s1 == s2 is true becuase they reference the Same String "foo" in the pool
To answer your question, your assumptions are right!
The last true s1.equals(s3) compares the value "foo", that's why they are equal.
So just remember with Strings
== compares Object reference
equals compares value.

What's the difference between ".equals" and "=="? [duplicate]

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.

Categories