What is garbage collection in Java, and how can it be used ?
Answer Posted / faiz misbah iiit-bangalore
Each time an object is created in java,it goes into an area
of memory known as the HEAP.All objects-no matter when.
where or how they're created -live on the heap.But it's not
just old memory heap;the java heap is actually called the
Garbage-collectible Heap.When you create an object, java
allocates memory space on the heap according to how much
that particular object needs.java manage that memory for
you!When the JVM can 'see' that an object can never be used
again,that object become eligible for garbage collection.and
if you're running low on memory,the garbage collector will
run,throw out the unreachable objects,and free up the
space.so that the space can be reused.
Run object finalization using System class
public class Main {
public static void main(String[] args) {
System.runFinalization();
}
}
Run the garbage collector using System class
public class Main {
public static void main(String[] args) {
System.gc();
}
}
The Lifetime of an Object
class Sphere {
double radius; // Radius of a sphere
Sphere() {
}
// Class constructor
Sphere(double theRadius) {
radius = theRadius; // Set the radius
}
}
public class MainClass {
public static void main(String[] arg){
Sphere sp = new Sphere();
System.gc();
}
}
| Is This Answer Correct ? | 13 Yes | 5 No |
Post New Answer View All Answers
What should I import for arraylist in java?
What is data movement?
FOR EXAMPLE WE R HAVING TWO LIST ELEMENTS ..BOTH LISTS CONTAINS ID,NAME,PLACE ..I NEED TO COMPARE BOTH IDS IN TWO LISTS,IF ID'S R SAME MEANS WE HAVE ADD THE DETAILS(LIKE NAME,PLACE) TO MAP...HOW IS POSSIBLE ?CAN ANY ONE SUGGEST?
5 Coding best practices you learned in java?
Which collection is thread safe in java?
Can a main method be declared final?
why are there separate wait and sleep methods? : Java thread
What is bytecode in java ?
What is an abstract method in java programming?
What is module with example?
What is runtime polymorphism or dynamic method dispatch?
What is the gregoriancalendar class in java programming?
What is garbage collector?
String and stringbuffer both represent string objects. Can we compare string and stringbuffer in java?
Is break statement can be used as labels in java?