0

I've recently started learning Java and I was fooling around and I got confused on this.

String s1 = "Happy";
String s2 = "Happy";
String s3 = new String ("Happy");

boolean sameString;
sameString = (s1 == s2);
System.out.println("s1 == s2 is " + sameString);
// This returns True.

sameString = (s1 == s3);
System.out.println("s1 == s3 is " + sameString);
// This returns False.

Can someone explain why this is so to me? Thanks!

Pokee
  • 51
  • 1
  • 5

2 Answers2

1

Strings in java are immutable
it means that when you change the string java will create a new memory location
when you write String s1 = "Happy" you give the java the control to make the
string for you if java finds any string that have the same value suppose you write s2 = "Happy"
it will make s1 and s2 points at the same memory location so s1 == s2 will return true but when you write String s3 = new String("Happy"); you make a new memory location


when you write s3 == s2 it will return false bec s2 and s3 are in different memory locations

1

== tests for reference equality (whether they are the same object).

String s1="Happy";
String s2="Happy";
if(s1==s2) ===> true

(s1==s2) ===> true

                   String Pool
s1 -----------------> "Happy" <-----------------s2

if(s1==s3) ===> false.

            String Pool
"Happy" <-------------------- s1

               Heap
"Happy" <-------------------- s3
Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65