Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

BE Java Module - 2

The document introduces the fundamentals of classes and objects in Java, explaining their roles in Object-Oriented Programming (OOP). It covers class declarations, properties, methods, and the distinction between reference and instance variables. Additionally, it highlights the importance of methods, including predefined and user-defined methods, and provides examples of their usage.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

BE Java Module - 2

The document introduces the fundamentals of classes and objects in Java, explaining their roles in Object-Oriented Programming (OOP). It covers class declarations, properties, methods, and the distinction between reference and instance variables. Additionally, it highlights the importance of methods, including predefined and user-defined methods, and provides examples of their usage.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Module -2

Introducing Classes:
Class Fundamentals: In Java, classes and objects are basic concepts of Object Oriented
Programming (OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior. For example, the animal
type Dog is a class while a particular dog named Browny is an object of the Dog class.

Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which objects
are created. For example, Student is a class while a particular student named Raj is an object.

Properties of Java Classes


1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface

Class Declaration in Java


access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
// Java Program for class example

class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of Student
Student obj = new Student();
System.out.println(obj.id);
System.out.println(obj.name);
}
}
Components of Java Classes
In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
6. Body: The class body is surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provide the state
of the class and its objects, and methods are used to implement the behavior of the class and
its objects.

Objects:
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and methods
of a class. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior : It is represented by the methods of an object. It also reflects the response
of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with
other objects.
Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, and “menu”. An online shopping system might have
objects such as “shopping cart”, “customer”, and “product”.
Note: When we create an object which is a non primitive data type, it’s always allocated on
the heap memory.
Declaring Objects
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated . All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.
Example:

As we declare variables like (type name;). This notifies the compiler that we will use the
name to refer to data whose type is type. With a primitive variable, this declaration also
reserves the proper amount of memory for the variable. So for reference variables , the type
must be strictly a concrete class name. In general, we can’t create objects of an abstract class
or an interface.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an
object is actually created and assigned to it. Simply declaring a reference variable does not
create an object.

Initializing a Java object


The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.

/ Class Declaration

public class Dog {


// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed, int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName() { return name; }

// method 2
public String getBreed() { return breed; }

// method 3
public int getAge() { return age; }

// method 4
public String getColor() { return color; }

@Override public String toString()


{
return ("Hi my name is " + this.getName()
+ ".\nMy breed,age and color are "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}

public static void main(String[] args)


{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Output
Hi my name is tuffy.
My breed,age and color are papillon,5,white

Initialize by using method/function:


public class Software {
// sw=software
static String sw_name;
static float sw_price;

static void set(String n, float p)


{
sw_name = n;
sw_price = p;
}

static void get()


{
System.out.println("Software name is: " + sw_name);
System.out.println("Software price is: "
+ sw_price);
}

public static void main(String args[])


{
Software.set("Visual studio", 0.0f);
Software.get();
}
}

Output
Software name is: Visual studio
Software price is: 0.0

Assigning Object Reference Variables


In Java, a reference variable is a variable that holds the memory address of an object rather
than the actual object itself. It acts as a reference to the object and allows manipulation of its
data and methods. Reference variables are declared with a specific type, which determines
the methods and fields that can be accessed through that variable.
When an object is created using the new keyword, memory is allocated on the heap to store
the object's data. The reference variable is then used to refer to this memory location, making
it possible to access and manipulate the object's properties and behaviors.
Here's an example that demonstrates the concept of reference variables in Java:
class Car {
String brand;
int year;
}
public class ReferenceVariableExample {

public static void main(String[] args) {


// Declare a reference variable of type Car
Car myCar;
// Create a new Car object and assign its reference to myCar
myCar = new Car();
// Access and modify the object's properties
myCar.brand = "Toyota";
myCar.year = 2021;
// Use the reference variable to perform actions on the object
System.out.println("Brand: " + myCar.brand);
System.out.println("Year: " + myCar.year);
}
}
Output:
Brand: Toyota
Year: 2021
Benefits and Usage of Reference Variables
Reference variables offer several benefits and play a crucial role in Java programming:
o Object Manipulation: Reference variables allow programmers to work with objects,
access their properties, and invoke their methods. They enable object-oriented
programming principles such as encapsulation, inheritance, and polymorphism.
o Memory Efficiency: Reference variables only store the memory address of an object
rather than the entire object itself. This approach helps conserve memory by avoiding
unnecessary object duplication.
o Object Passing: Reference variables are often used when passing objects as arguments
to methods or returning objects from methods. This allows for efficient memory usage
and facilitates modular programming.
o Dynamic Behavior: Reference variables enable dynamic behavior in Java programs.
Different objects can be assigned to the same reference variable, allowing flexibility
in handling different types of objects at runtime.
o Object Lifetime Control: Using reference variables, developers can control the
lifetime of objects dynamically. When a reference variable is no longer referencing an
object, the object becomes eligible for garbage collection, freeing up memory
resources.

Introducing Methods
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method.

Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.

Predefined method:
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9

User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method


User defined method that checks the number is even or odd. First, we will define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the
called method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.

Combine both snippets of codes in a single program


import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}

Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.
Example of static method
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Output:
It is an example of a static method.

Instance Method
The method of the class is known as an instance method. It is a non-static method defined
in the class. Before calling or invoking the instance method, it is necessary to create an object
of its class. Let's see an example of an instance method.
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25

There are two types of instance method:


o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the
private field.
Example
public int getId()
{
return Id;
}

Mutator Method: The method(s) read the instance variable(s) and also modify the values.
We can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data
type that depends on the field. It is used to set the value of the private field.
Example
public void setRoll(int roll)
{
this.roll = roll;
}

Abstract Method
The method that does not has method body is known as abstract method. In other words,
without an implementation is known as abstract method. It always declares in the abstract
class. It means the class itself must be abstract if it has abstract method. To create an abstract
method, we use the keyword abstract.

Syntax
abstract void method_name();
Example of abstract method
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}

Output:
Abstract method...

Factory method
It is a method that returns an object to the class to which it belongs. All static methods are
factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();

Constructors
In Java, a Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.

// Java Program to demonstrate Constructor


import java.io.*;
class ConstructorEx {
// Constructor
ConstructorEx()
{
super();
System.out.println("Constructor Called");
}
// main function
public static void main(String[] args)
{
ConstructorEx ce= new ConstructorEx();
}
}
Note: It is not necessary to write a constructor for a class. It is because the java compiler
creates a default constructor (constructor with no arguments) if your class doesn’t have any.
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-
class or an overloaded constructor), if you don’t type in the call to super in your constructor
the compiler will provide you with a non-argument call to super at the first line of your code,
the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.

When Java Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.
Rules for writing constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in which it
resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
Types of Constructors in Java
• Default Constructor
• Parameterized Constructor
• Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler does
not create a default constructor. It is taken out. It is being overloaded and called a
parameterized constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor. The default
constructor can be implicit or explicit. If we don’t define explicitly, we get an implicit default
constructor. If we manually write a constructor, the implicit one is overridded.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
// Java Program for Parameterized Constructor
import java.io.*;
class ParaConstructor {
// data members of the class.
String name;
int id;
ParaConstructor() // default constructor
{
}
ParaConstructor(String name, int id) // parameter constructor
{
this.name = name;
this.id = id;
}
ParaConstructor(String name) // parameter constructor
{
this.name = name;
}
}
class Navkis {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
ParaConstructor PC = new ParaConstructor("Raj", 24);
System.out.println("Name :" + PC.name
+ " and Id :" + PC.id);
}
}

3. Copy Constructor in Java


Unlike other constructors copy constructor is passed with another object which copies the
data available from the passed object to the newly created object.
// Java Program for Copy Constructor
import java.io.*;

class Ge {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Ge(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Ge(Ge obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class CopyConstructor{
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Ge ge1 = new Ge("Raj", 24);
System.out.println("Name :" + ge1.name + " and Id :" + ge1.id);

System.out.println();

// This would invoke the copy constructor.


Ge ge2 = new Ge(ge1);
System.out.println("Copy Constructor used Second Object");
System.out.println("Name :" + ge2.name + " and Id :" + ge2.id);
}
}
This Keyword:
In Java, ‘this’ is a reference variable that refers to the current object, or “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.

this reference Example


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.

Below is the implementation of this reference:


// Java Program to implement Java this reference

public class Person {


// Fields Declared
String name;
int age;

// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}

// Getter for name


public String get_name() { return name; }

// Setter for name


public void change_name(String name)
{
this.name = name;
}

// Method to Print the Details of


// the person
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}

public static void main(String[] args)


{
// Objects Declared
Person first = new Person("RAJ", 18);
Person second = new Person("RAM", 22);
first.printDetails();
second.printDetails();

first.change_name("PQR");
System.out.println("Name has been changed to: "
+ first.get_name());
}
}

Output
Name: RAJ
Age: 18

Name: RAM
Age: 22

Name has been changed to: PQR

Explanation
In the above code, we have defined a Person class with two private fields name and age. We
have defined the Person class constructor to initialize these fields using this keyword. We
have also defined getter and setter methods for these fields which use this keyword to refer to
the current object instance.
In the printDetails() method, we have used this keyword to refer to the current object instance
and print its name, age, and object reference.
In the Main class, we have created two Person objects and called the printDetails() method on
each object. The output shows the name, age, and object reference of each object instance.

Methods to use ‘this’ in Java


Following are the ways to use the ‘this’ keyword in Java mentioned below:
• Using the ‘this’ keyword to refer to current class instance variables.
• Using this() to invoke the current class constructor
• Using ‘this’ keyword to return the current class instance
• Using ‘this’ keyword as the method parameter
• Using ‘this’ keyword to invoke the current class method
• Using ‘this’ keyword as an argument in the constructor call

1. Using ‘this’ keyword to refer to current class instance variables


// 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

2. Using this() to invoke current class constructor

// Java code for using this() to invoke current class constructor


class Test {
int a;
int b;

// Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}

// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}

public static void main(String[] args)


{
Test object = new Test();
}
}

Output
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance

// Java code for using 'this' keyword to return the current class instance
class Test {
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}

// Method that returns current class instance


Test get() { return this; }

// Displaying value of variables a and b


void display()
{
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test();
object.get().display();
}
}

Output
a = 10 b = 20

4. Using ‘this’ keyword as a method parameter

// Java code for using 'this' keyword as method parameter


class Test {
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}

// Method that receives 'this' keyword as parameter


void display(Test obj)
{
System.out.println("a = " + obj.a + " b = " + obj.b);
}

// Method that returns current class instance


void get() { display(this); }

// main function
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
}

Output
a = 10 b = 20

5. Using ‘this’ keyword to invoke the current class method

// Java code for using this to invoke current class method


class Test {

void display()
{
// calling function show()
this.show();

System.out.println("Inside display function");


}

void show()
{
System.out.println("Inside show function");
}

public static void main(String args[])


{
Test t1 = new Test();
t1.display();
}
}
Output
Inside show function
Inside display function
6. Using ‘this’ keyword as an argument in the constructor call

// Java code for using this as an argument in constructor call


// Class with object of Class B as its data member

class A {
B obj;

// Parameterized constructor with object of B as a parameter


A(B obj)
{
this.obj = obj;

// calling display method of class B


obj.display();
}
}

class B {
int x = 5;

// Default Constructor that create an object of A


// with passing this as an argument in the constructor
B() { A obj = new A(this); }

// method to show value of x


void display()
{
System.out.println("Value of x in Class B : " + x);
}

public static void main(String[] args)


{
B obj = new B();
}
}

Output
Value of x in Class B : 5

Advantages of using ‘this’ reference


There are certain advantages of using ‘this’ reference in Java as mentioned below:
1. It helps to distinguish between instance variables and local variables with the same
name.
2. It can be used to pass the current object as an argument to another method.
3. It can be used to return the current object from a method.
4. It can be used to invoke a constructor from another overloaded constructor in the
same class.
Disadvantages of using ‘this’ reference
Although ‘this’ reference comes with many advantages there are certain disadvantages of
also:
1. Overuse of this can make the code harder to read and understand.
2. Using this unnecessarily can add unnecessary overhead to the program.
3. Using this in a static context results in a compile-time error.
4. Overall, this keyword is a useful tool for working with objects in Java, but it should
be used judiciously and only when necessary.

Garbage Collection
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on 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.

How Does Garbage Collection in Java works?


Java garbage collection is an automatic process. Automatic garbage collection is the process
of looking at heap memory, identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced object, means that some part of
your program still maintains a pointer to that object. An unused or unreferenced object is no
longer referenced by any part of your program. So the memory used by an unreferenced
object can be reclaimed. The programmer does not need to mark objects to be deleted
explicitly. The garbage collection implementation lives in the JVM.

Types of Activities in Java Garbage Collection


Two types of garbage collection activity usually happen in Java. These are:
1. Minor or incremental Garbage Collection: It is said to have occurred when
unreachable objects in the young generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have occurred when the objects that
survived the minor garbage collection are copied into the old generation or permanent
generation heap memory are removed. When compared to the young generation,
garbage collection happens less frequently in the old generation.

Important Concepts Related to Garbage Collection in Java


1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any
reference to it. Also, note that objects which are part of the island of isolation are also
unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.
2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage
collection) if it is unreachable. After i = null, integer object 4 in the heap area is suitable for
garbage collection in the above image.
Ways to make an object eligible for Garbage Collector
• Even though the programmer is not responsible for destroying useless objects but it is
highly recommended to make an object unreachable (thus eligible for GC) if it is no
longer required.
• There are generally four ways to make an object eligible for garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. An object created inside the method
4. Island of Isolation
Ways for requesting JVM to run Garbage Collector
• Once we make an object eligible for garbage collection, it may not destroy
immediately by the garbage collector. Whenever JVM runs the Garbage Collector
program, then only the object will be destroyed. But when JVM runs Garbage
Collector, we can not expect.
• We can also request JVM to run Garbage Collector. There are two ways to do it :
1. Using System.gc() method: System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method: Runtime class allows the
application to interface with the JVM in which the application is running.
Hence by using its gc() method, we can request JVM to run Garbage
Collector.
3. There is no guarantee that any of the above two methods will run Garbage
Collector.
4. The call System.gc() is effectively equivalent to the call
: Runtime.getRuntime().gc()

Finalization
• Just before destroying an object, Garbage Collector calls finalize() method on the
object to perform cleanup activities. Once finalize() method completes, Garbage
Collector destroys that object.
• finalize() method is present in Object class with the following prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for performing our cleanup
activities like closing connection from the database.
1. The finalize() method is called by Garbage Collector, not JVM. However, Garbage
Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation. Thus, it is recommended
to override the finalize() method to dispose of system resources or perform other
cleanups.
3. The finalize() method is never invoked more than once for any object.
4. 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.

You might also like