Java — Heap & String Constant Pool (SCP) | Code Factory

Code Factory
3 min readMay 14, 2020

--

Index Page : Link

Donate : Link

  • SCP stored in method area/PERMGEN till 1.6v, from 1.7v it is stored in Heap
  • In above scenario JVM will check that object already exist with this content, if already there then reuse it otherwise create new object.

How many objects will be created?

String s1 = new String("Code Factory");
String s2 = new String("Code Factory");
String s3 = "Code Factory";
String s4 = "Code Factory";

How many objects will be created?

String s = new String("Code");
s.concat("Factory");
s = s.concat("Hello");

How many objects will be created?

String s1 = new String("one");
s1.concat(", two");
String s2 = s1.concat(", three");
s2.concat(", four");
System.out.println(s1); // one
System.out.println(s2); // one, three

How many objects will be created?

String s1 = new String("code factory");
String s2 = new String("code factory");
System.out.println(s1 == s2); // false
String s3 = "code factory";
System.out.println(s1 == s3); // false
String s4 = "code factory";
System.out.println(s3 == s4); // true
String s5 = "code" + " factory";
// s5 will perform at compile time and JVM is responsible
System.out.println(s4 == s5); // true
String s6 = "code";
String s7 = s6 + " factory";
// s7 will perform at runtime
System.out.println(s4 == s7); // false
final String s8 = "code";
// s8 will perform at compile time
String s9 = s8 + " factory";
// s9 will perform at compile time
System.out.println(s4 == s9); // true
  • If both are constant then operation is performed at compile time. Ex. s5
  • Atleast one normal variable + constant then operation is performed at run time. Ex. s7
  • Every final variable will be replaced by compile time. Ex. s8

Importance of String Constant Pool (SCP) :

  • Same object can be resused multiple times
  • Memory saved
  • Performance will be improved

So many String objects are reference to single SCP value (India). So if any one will change there country India to Australia then all objects reference is changed. Thats why immutability concept is come in String.

--

--