0

I am reading some notes about how to compare equality between String in Java.

String s1 = new String("abc");
String s2 = new String("abc");

These two are allocated in different memory, so their reference are different. When we call

if (s1 == s2){ .. } // Comparing the reference, so return false
if(s1.equal(s2)){..} // Comparing content, so return true

So, what is

String s3 = "abc" String s4 = "abc"?

How is the memory allocated and when I do different equality check, what will happen?

For example :

s3==s4
s3.equal(s4)
s3.equal(s1)
Timothy Leung
  • 1,407
  • 7
  • 22
  • 39

1 Answers1

2

String s3 = "abc" String s4 = "abc"??

Those are literals. String literals are stored in a common pool(shares of storage for strings)

String objects creted via new operator are stored in the heap(no sharing).

s3==s4   //true 
s3.equals(s4) //true

Read More:

How can a string be initialized using " "?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307