Java is known for its memory management mechanisms that ensure efficient resource utilization and prevent memory leaks.
Heap Area in Java
The heap area is a segment of memory dedicated to storing objects and instances created during the Runtime of the Java program. Unlike the stack memory, which manages method calls and local variables, the heap is used for dynamic memory allocation and is shared among all threads within a Java application.
One of the most noteworthy features of the heap area is automatic memory management through a process called “Garbage Collection”.In Java garbage collector is available to identify and clean up objects that are no longer reachable or referenced by any part of the program.
We as programmers are responsible for managing the lifecycle of objects within the heap. We can create objects using new
keywords and must also ensure proper cleanup by allowing objects to become unreachable when they are no longer needed. This enables the garbage collector to do its job effectively.
Object o = new Object;
String Constant Pool
The String constant pool also known as String pool is a special area within the Heap that stores a pool of unique String literal. In Java String literals are frequently used. To optimize memory use and performance, Java uses a mechanism that allows multiple references to share the same instances of a String literal, rather than creating duplicate instances for each occurrence of a literal.
When a String literal is encountered in a Java Program, the Runtime checks the String constant pool first. If the literal already exists in the pool, the reference to the existing instance is returned, reducing memory consumption. If the String literal is not formed a new entry is added to the pool.
We can explicitly add a String to the String constant pool by using the intern method.
ublic class StringConstantPool {
public static void main(String[] args) {
String s1 = new String("Heap Memory");
String s2 = new String("Heap Memory");
System.out.println(s1 == s2);
String s3 = "Java"; // String Constant Pool
String s4 = "Java"; // String Constant Pool
System.out.println(s3 == s4);
}
}
Similar Java Tutorials
- Odd Even in Java
- java.lang Package
- toString() method in Java
- hashCode Method in Java
- equals Method in Java
- getClass Method in Java
- 1 01 101 Pattern in Java
- finalize method in Java
- String Class in Java
- StringBuffer Class in Java
- Difference Between String Buffer and String Builder
- clone() Method in Java