Memory plays a vital role in programming. Any objects, variables need memory to store its value. Generally, memory management involves the allocation and deallocation of memory space.
The memory areas in java can be classified into 4 types
listed as follows.
- · Heap Memory: It stores the objects and variables.
- · Stack Memory: Method calls and local variables.
- · Code (Method) Area: byte codes of methods and constructors are stored.
- · Native Method Stack: It has Native Method information.
Some of the concepts in memory management are given below.
- · Object Creation and Garbage Collection
- · Detecting Memory Leak
- · Using Weak References
Let us implement these concepts in Java.
Java Program to implement Object Creation and Garbage
Collection:
This program illustrates the object creation and garbage
collection.
Steps:
- · First, a class is created with main() function.
- · A loop is created with condition i<10. Until this condition fails, the process is repeated.
- · A string is created an object “temp”.
- · It holds the integer value and an output statement is printing this object value.
- · As it is a temporary value, it is garbage collected at the end.
Program:
public class MemoryMgtEg {
public static void
main(String[] args) {
System.out.println("The string created its object");
for (int i =
0; i < 10; i++) {
String
temp = new String("String number: " + i);
System.out.println(temp);
}
System.out.println("The garbage collection is done.");
}
}
Output:
When you compile and execute this program, you get the
output as follows…
C:\raji\blog>javac MemoryMgtEg.java
C:\raji\blog>java MemoryMgtEg
The string created its object
String number: 0
String number: 1
String number: 2
String number: 3
String number: 4
String number: 5
String number: 6
String number: 7
String number: 8
String number: 9
The garbage collection is done.
This is the way of implementing the java program to
illustrate the object creation and garbage collection. Hope this will be useful
for you.Keep coding!!!
No comments:
Post a Comment