Understanding "==" on String Objects
If the above code snippet confuses you, this article is for you.
Hi all, in this article, we will see why the above code executes?
String object can be created in 2 ways:
- Using String Literal
- Using new keyword
When we create a string using double quotes, it is called a string literal.
Eg : String s1 = "Hello";
Whenever a literal is created, it gets stored in the string pool.
What is String Pool?
String Pool is a special place in heap memory where literals are stored.
Whenever a new literal is created, JVM checks in the string pool whether the same string already exists in the pool or not.
If the string exists, then its reference is returned else new string is created and placed in the pool.
If we see the first 2 statements of the above snippet,
String s1 = "Hello";
String s2 = "Hello";
For s1, since the pool is empty a new String (Hello) is created in the pool and s1 is the reference to the string.
For s2, since "Hello" is already present in the pool, JVM will not create a new one, instead, it will return the earlier reference of string "Hello" which is s1.
So,
String s2 = "Hello" is same as String s2 = s1
Now, the literal "Hello" has 2 references s1 and s2.
Creating using the "new" keyword
String s3 = new String("Hello");
When we create a string using a new keyword, this object gets created outside the pool, it is different from the literal.
So its address will also be different.
Now I hope you have understood why the snippet works this way.
System.out.println(s1==s2);//true
System.out.println(s3==s2);//false
Since, s1 and s2 points to same object(in the pool), s1==s2 is true.
s3 points to different object, therefore s3==s2 is false but if we use equals() for comparison it would have given true because it compares the content not the address.
That's it for this short article.
If you find it helpful do like it.
Thanks for Reading!