String in Java
String in Java is immutable and represents a sequence of characters.
before you understand what is immutability, understand :
Heap : Heap is a memory area where objects created using ‘new’ keyword is stored.
String Constant Pool (SCP) : This is a special storage area the inside heap used to store string literals. By reusing existing string objects, SCP helps saves memory.
Diagram :
Examples for understanding the behaviour of String in Java:
1.
String str = “hello”;
String str1 = “hello”;
System.out.println(str1==str);// true
As you can see in the diagram only one object is created in SCP (reusing the memory).
2.
String str = “hello”;
str.concat(“ bello!”); //only ‘bello!’ will get stored in SCP as it it a string literal
System.out.println(str);//hello
str=str.concat(“ bello!”);
System.out.println(str);//hello bello!
str was pointing ‘hello’ in SCP first and then the concat() method created a referenceless obj in heap area, after that we pointed the str to ‘hello bello!’ and as the ‘bello!’ was concatinated during runtime that’s the reason one ‘bello!’ is in SCP ans now in heap ‘hello bello!’ is present where str is it’s referennce var. phew that was confusing
Get Raj Dhok’s stories in your inbox
Join Medium for free to get updates from this writer.
String str = “hello”;//SCP
String str1 = str.concat(“ bello”);//heap area
String str2 = “hello bello”;//SCP
System.out.println(str1==str2);//false
As the ‘==’ operator compare the referance str1 and str2 points to different objects (heap vs SCP).
3.
String s1 = “hello”; //SCP
String s2 = “bello”; //SCP
String s3 = s1+s2; //heap
String s4 = “hellobello”;//SCP
System.out.println(s3==s4);//false as the ‘s3’ string will get created in the heap area.
4.
String s1 = “hello” + “bello”; //SCP
String s2 = “hello” + “bello”; //SCP
System.out.println(s1==s2);//true
5.
String s1 = “hello” + 3247347 + 234768623;
System.out.println(s1);
everything you concatenate using ‘+’ it gets converted into String object only if we do it left to righ (on the left the string, on right it can be anything)
6.
String s1 = 100 + 99 + 800 + “ hello”;
System.out.println(s1); //999 hello.
Arithmetic happens first until a String is encountered.
String literals go to SCP, runtime string operations create new objects in heap, and String immutability prevents modification of existing objects.









