[go: up one dir, main page]

0% found this document useful (0 votes)
14 views5 pages

Unit1 - This Garbage

The document explains three types of variables in Java: instance variables, local variables, and static variables, detailing their scopes and lifetimes. It also covers the 'this' keyword, its uses in referencing current object members, and the garbage collection process in Java, which automatically manages memory by removing unreferenced objects. Additionally, it discusses how to make objects eligible for garbage collection, request garbage collection, and the finalize() method for cleanup before object destruction.

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Unit1 - This Garbage

The document explains three types of variables in Java: instance variables, local variables, and static variables, detailing their scopes and lifetimes. It also covers the 'this' keyword, its uses in referencing current object members, and the garbage collection process in Java, which automatically manages memory by removing unreferenced objects. Additionally, it discusses how to make objects eligible for garbage collection, request garbage collection, and the finalize() method for cleanup before object destruction.

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

VARIABLES:

1. An instance variable in Java is a variable that is defined within a class but outside of any method,
constructor, or block. Each object of the class has its own copy of the instance variable.
 Instance variables are also known as member variables or fields.
 They are created when an object is instantiated and destroyed when the object is garbage
collected.
2. A local variable in Java is a temporary variable that is only available within a specific function or
block of code. Local variables are created when a function or block is entered and destroyed when it
exits.
 Local variables are declared in a function body, block, or loop statement
3. A static variable in Java is a variable that is associated with a class, rather than with a specific
instance of a class. This means that all instances of a class share a single copy of the variable.
 How to declare a static variable
 Use the keyword static to declare a variable
 Declare the variable outside of any method, constructor, or block
 Static variables are created when the program starts and destroyed when the program ends
 The value of a static variable is preserved across function calls and instances.

this keyword
 The this keyword in Java is a reference variable that refers to the current object. It is used in
instance methods and constructors to access the current object's members.

Why use the this keyword?


 To avoid confusion between class attributes and parameters with the same name
 To make code easier to read and understand

How to use the this keyword?


 To invoke the current class constructor
 To invoke the current class method
 To return the current class object
 To pass an argument in the method call
 To pass an argument in the constructor call

Why using this keyword?


 Constructor invocation: To call another constructor in the same class from within a constructor
 Referencing instance variables: To make it clear that you are referring to the instance variable, not
the local variable in the method
 The most common use of this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
 In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a
keyword that refers to the current object instance.
 It can be used to call current class methods and fields, to pass an instance of the current class as a
parameter, and to differentiate between the local and instance variables. Using “this” reference can
improve code readability and reduce naming conflicts.
 In Java, this is a reference variable that refers to the current object on which the method or
constructor is being invoked. It can be used to access instance variables and methods of the current
object.

Example: 1
// Java code for using 'this' keyword to
// refer current class instance variables
class Test {
int a;
int b;

// Parameterized constructor
Test(int a, int b){
this.a = a;
this.b = b;}

void display() {
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);}

public static void main(String[] args){


Test object = new Test(10, 20);
object.display(); }}

Output

a = 10 b = 20

Garbage Collection
 Garbage Collection is a key feature of the Java programming language that automatically manages
memory allocation and deallocation for objects that are created in an eden space.
 Garbage Collection in Java allows developers to focus on writing code without worrying about
memory management, making Java a popular choice for building complex and large-scale
applications.
 Garbage collection in Java is an automatic memory management process that helps Java programs
run efficiently.
 Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java
programs run on the JVM, objects in the heap, which is a portion of memory dedicated to the
program.
 Eventually, some objects will no longer be needed. The garbage collector finds these unused
objects and deletes them to free up memory.
 In C/C++, programmers have to manually create and delete objects, which can sometimes lead to
memory leaks and errors when there isn’t enough memory available. This happens when unused
objects are not deleted properly.
 In Java, this process is automated. The garbage collector automatically finds and removes objects
that are no longer needed, freeing up memory in the heap. It runs in the background as a daemon
thread, helping to manage memory efficiently without requiring the programmer’s constant
attention.

Working of Garbage Collection


 Java garbage collection is an automatic process that manages memory in the heap.
 It identifies which objects are still in use (referenced) and which are not in use (unreferenced).
 Unreferenced objects can be deleted to free up memory.
 The programmer does not need to mark objects to be deleted explicitly. The garbage collection
implementation lives in the JVM.

four ways to make an object eligible for garbage collection.


 Nullifying the reference variable: Set the reference to null.
 Re-assigning the reference variable: Assign a new object to the reference.
 An object created inside the method: Objects created within a method are eligible for garbage
collection once the method completes.
 Island of Isolation: Objects that are isolated and not referenced by any reachable objects.

Ways to Request JVM to Run Garbage Collection


 Once an object is eligible for garbage collection, it may not be destroyed immediately.
 The garbage collector runs at the JVM’s discretion, and you cannot predict when it will occur.
 We can also request JVM to run Garbage Collector. There are two ways to do it :
 Using System.gc(): This static method requests the JVM to perform garbage collection.
 Using Runtime.getRuntime().gc(): This method also requests garbage collection through the
Runtime class.
 Note: There is no guarantee that the garbage collector will run immediately after these calls.
3. Finalization
 Before destroying an object, the garbage collector calls the finalize() method to perform cleanup
activities. The method is defined in the Object class as follows:
 protected void finalize() throws Throwable
 Note:
 The finalize() method is called by Garbage Collector, not JVM.
 The default implementation of finalize() is empty, so overriding it is recommended for resource
cleanup.
 The finalize() method is called only once per object.
 If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the
finalization of that object terminates.

Advantages of Garbage Collection in Java


 The advantages of Garbage Collection in Java are:
 It makes java memory-efficient because the garbage collector removes the unreferenced objects
from heap memory.
 It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
4) finalize() method
 The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
 Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So
if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
 The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
public static void gc(){}
 Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
output:
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.

You might also like