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

  • 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.
String s1 = new String("Code Factory");
String s2 = new String("Code Factory");
String s3 = "Code Factory";
String s4 = "Code Factory";
String s = new String("Code");
s = s.concat("Hello");
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
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
  • Same object can be resused multiple times
  • Memory saved
  • Performance will be improved




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A Complete Guide to Creating and Populating Word Templates with Power Automate

What the Hex?

Faster Data Loading for Pandas on S3

How to Build a Notion Clone with Strapi v4 and Next.js (Part 1 of 2)

Setup a Python Environment from Basic for Machine Learning

Chapter 4 of Clean Code is here

ASP .NET Core with Docker

A deep Look into Kouji’s eyes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Reducing Visibility Timeout — Exception Scenarios- Hack I did

Java extension mechanism — Self discovery & bean instantiation

Access modifiers in java

Numbering System Edge Cases of Java