Difference between "equals() method" and "== operator" in Java (Java String)

String
  • is an object that represents a sequence of characters or char values.
  • immutable (Strings are constant, their values cannot be changed after they are created)

==         => operator => reference comparison/address comparison 
                                     (both objects pointing to same memory location)
.equals()  => method => comparison of values/content in the objects

Summary: == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.


2 ways to create sting in Java: 
String s=“Apple”;        //by using double quotes
String s=new String(“Apple”);  //by using a keyword “new”

 

new String("Apple") explicitly creates a new and referentially distinct instance of a string object
String s="Apple" may reuse an instance from the string constant pool if one is available

s1==s2 //true
s1==s3 //false

s1.equals(s2) //true
s1.equals(s3) //true

More Explanation: Java String pool refers to collection of Strings which are stored in heap memory. Whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable, else new object will be created in the String pool and the respective reference will be returned.



Popular posts from this blog

GOOGLEFINANCE attributes

Practice

Merge/join two or more video files using Python