Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views32 pages

JAVA Unit-2

This document covers key concepts of Object-Oriented Programming (OOP) in Java, including classes, objects, methods, and their characteristics. It explains principles such as inheritance, polymorphism, encapsulation, and abstraction, along with the benefits and applications of OOP. Additionally, it details method declarations, types of methods, and the differences between passing arguments by value and by reference.

Uploaded by

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

JAVA Unit-2

This document covers key concepts of Object-Oriented Programming (OOP) in Java, including classes, objects, methods, and their characteristics. It explains principles such as inheritance, polymorphism, encapsulation, and abstraction, along with the benefits and applications of OOP. Additionally, it details method declarations, types of methods, and the differences between passing arguments by value and by reference.

Uploaded by

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

UNIT-2

CONTENTS
2.1 Classes and Objects:
2.1.1 Introduction,
2.1.2 Class Declaration and Modifiers, (It will be in covered in
unit-3)
2.1.3 Class Members,
2.1.4 Declaration of Class Objects,
2.1.5 Constructor Methods,
2.1.6 Nested Classes,
2.1.7 Final Class and Methods, (It will be covered in unit-3)
2.1.8 Passing Arguments by Value and by Reference,
2.1.9 Keyword this.

2.2 Methods:
2.2.1 Introduction,
2.2.2 Defining Methods,
2.2.3 Overloaded Methods,
2.2.4 Overloaded Constructor Methods,
2.2.5 Recursive Methods,
2.2.6 Nesting of Methods,
2.2.7 Overriding Methods, (It will be covered in unit-3)
2.2.8 Attributes Final and Static. (It will be covered in unit-3)
2.1 Classes and Objects
2.1.1 Introduction
Java become famous because of two main reasons:
● Platform Independence: The Compilation and Execution phases can be done in same
operating system and also in different operating systems.
● Object Orientation: The way we see the world is a collection of objects.

Object Oriented Programming Concepts or Principles


Objects
Classes
Data abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects.
Classes
Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc. In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.
Abstraction
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the information on
what the object does instead of how it does it. In simpler words, data abstraction is the process
of hiding certain details and showing only essential information to the user. Hiding internal
details and showing functionality is known as abstraction. For example, phone call, we don't
know the internal processing. In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.

Benefits of OOPs:
 Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
 The principle of data hiding helps the programmer to build secure programs.
 It is easy to partition the work in a project based on objects.
 Object oriented system easily upgraded from small to large systems.
 Software complexity can be easily managed.

Applications of oops:
1. Real-time systems
2. Object-oriented databases
3. Neural networks and parallel programming
4. Decision support and office automation systems
5. CAD/CAM systems

What is a class in Java:


A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:


o Fields or Data members
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{
// Data members
// Member functions or methods
}

What is an object in Java


An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class. 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 has three characteristics:


o State: represents the data (value) of an object. State / properties means what an object
has. To take care of state we should use datatypes.
o Behaviour: Represents the behaviour (functionality) of an object such as deposit,
withdraw, etc. Behaviour means what an object does. To take care of behaviour we
should use Methods / Functions.
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behaviour.
o The object is an instance of a class.

Rules of Object Orientation:


● The world is nothing but collection of objects.
● Every object in the world belong to type.

class Car
{
//has part or state
String name;
int cost;
float mileage;
//does part or behaviour
void start()
{
//body of the method;
}
void accelerate()
{
//body of the method;
}
void stop()
{
//body of the method;
}
}
//Let’s see how to create an object in java:

Car c1 = new Car(); // object 1 creation


Car c2 = new Car(); // object 2 creation
c1.start(); //object 1 calling start ()
c1.accelerate(); //object 1 calling accelerate ()
c1.stop(); //object 1 calling stop ()

c2.start(); //object 2 calling start ()


c2.accelerate(); //object 2 calling accelerate ()
c2.stop(); //object 2 calling stop ()

2.1.6 Nested Classes


 Java inner class or nested class is a class that is declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
 Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

Example for Inner Class:


Program:
public class Outer
{
int i=10;
public class Inner
{
int j;
public void innerFn()
{
System.out.printIn(“I is “+I);
System.out.printIn(“j is “+j);
}
}
public void innerCreate()
{
Inner in=new Inner();
in.innerFn();
}
public void outerFn()
{
System.out.printIn(“I is “+ i);
}
public static void main(String s[ ] )
{
Out out=new Outer();
out.innerCreate();
}
}

Advantage of Java inner classes:


There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

2.2 Methods in Java


2.2.1 Introduction
The method in Java is a collection of instructions that performs a specific task. It provides the
reusability of code. We can also easily modify code using methods. 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.

2.2.2 Method Declaration


The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments.
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.

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 for Static Method:


Program:
Class ExStatic
{
static int i=10;
public static void print()
{
System.out.printIn(“Value of i is “+i);
}
public static void main(String s[ ])
{
ExStatic.print(); //method is called using class name
}
}
Output:
Value of i is 10

Instance Method:
Instance Methods are the group of codes that performs a particular task. Sometimes the
program grows in size, and we want to separate the logic of the main method from other
methods. A method is a function written inside the class. Since java is an object-oriented
programming language, we need to write a method inside some classes.
The important points regarding instance variables are:
1. Instance methods can access instance variables and instance methods directly.
2. Instance methods can access static variables and static methods directly.
Example for Instance Method:
Program:
Class ExInsta
{
static int i=10;
public void print()
{
System.out.printIn(“Value of i is “+i);
}
public static void main(String s[ ])
{
new Exinsta().print();//method is called using class name
//Exinsta ei = new Exinsta();
//ei.print();
}
}
Output:
Value of i is 10

Object and Class Example: main within the same class


In this example, we have created a student class which has two data members id and name. We
are creating the object of the student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
Program:
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
//accessing member through reference variable
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Object and Class Example: main outside the class


In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
Program:
//Java Program to demonstrate having the main method in another class
//Creating Student class.
class Student
{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Types of methods (Passing parameters)
There are four different types of methods
1)Without Input and without Output
2)With Input and without output
3)Without Input and with output
4)With input and with output

Case-1: Without input and without output

Case-2: With input and without output


Case-3: Without input and with output

Case-4: With input and with output


2.1.8 Passing Arguments by Value and by Reference
Pass by value / Call by value:
If we call a method passing a value, it is known as call by value. The changes being done in
the called method, is not affected in the calling method. The call-by-value copies the value of
a actual parameter into the formal parameter of the method. In this method, changes made to
the formal parameter of the method have no effect on the actual parameter.
Create a method which accepts two parameters and return the results
Example for Pass by value:
Program:
class Calculator
{
int c;
int add(int a, int b)
{
c=a+b;
return c;
}
public static void main(Strings args[])
{
Calculator ca = new Calculator();
int num1 = 200;
int num2 = 300;
int num3 = ca.add(num1, num2);
System.out.println(num3);
}
}
Output:
500

Pass by reference / Call by reference:


In call-by-reference, a reference to an actual parameter (not the value of the argument) is passed
to the formal parameter. In this method, changes made to the actual parameter will affect the
actual parameter used to call the method.
Now let’s try to create the method which accept the reference of type car and modify the value
of instance variable inside that method
Example for Pass by Reference:
Program:
class Car
{
String name;
int cost;
void modifyCar(Car y)
{
y.name = “BMW”;
y.cost = 5000000;
}
}
class Test
{
public static void main(String args[])
{
Car x = new Car();
x.name = “Maruthi”;
x.cost = 3000000;
System.out.println(x.name);
System.out.println(x.cost);

x.modifyCar(x);
System.out.println(x.name);
System.out.println(x.cost);
}
}
Output:
Maruthi
3000000
BMW
5000000
2.2.3 Method Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different. When I say argument list it means the
parameters that a method has: For example, the argument list of a method add(int a, int b)
having two parameters is different from the argument list of the method add(int a, int b, int c)
having three parameters.
There are three ways to overload a method: In order to overload a method, the argument lists
of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
area(int, int)
area(int, int, int)
2. Data type of parameters.
For example: area(int, float)
area(int, int)
3. Sequence of Data type of parameters.
For example: area(int, float)
area(float, int)
Example for Method Overloading:
Program:
import java.util.Scanner;
class Printer
{
void print(int a)
{
System.out.println(a);
}
void print(float a)
{
System.out.println(a);
}
void print(char a)
{
System.out.println(a);
}
void print(boolean a)
{
System.out.println(a);
}
void print(short a)
{
System.out.println(a);
}
void print(int a, int b)
{
System.out.println(a +" " + b);
}
void print(float a, float b)
{
System.out.println(a +" " + b);
}
void print(double a, double b)
{
System.out.println(a +" " + b);
}
void print(int a, float b)
{
System.out.println(a +" " + b);
}
void print(int a, int b, int c)
{
System.out.println(a +" " + b + " " + c);
}
void print(int a, char b, float c)
{
System.out.println(a +" " + b + " " + c);
}
}
public class Demo
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
int c = 30;
char ch = 'a';
float f = 45.5f;
double d =55.5;
Printer p = new Printer();
p.print(ch);
p.print(a,a);
p.print(a,a,a);
}
}

Method overloading is an example of Static Polymorphism. We will look into polymorphism


in deep in further classes. ∙ Static Polymorphism is also known as compile time binding or early
binding. ∙ Static binding happens at compile time. Method overloading is an example of static
binding where binding of method call to its definition happens at Compile time.

Method overloading and Type Promotion:


When a data type of smaller size is promoted to the data type of bigger size than this is called
type promotion,
For example: byte data type can be promoted to short, a short data type can be promoted to int,
long, double etc.
What does it has to do with method overloading?
Well, it is very important to understand type promotion else you will think that the program
will throw compilation error but in fact that program will run fine because of type promotion.
Example for Type promotion in method overloading:
Program:
class Printer
{
void print(int a, float b)
{
System.out.println(a +" " + b);
}
void print(int a, float b, short c)
{
System.out.println(a +" " + b+ " " +c);
}
}
public class Demo
{
public static void main(String[] args)
{
Printer p = new Printer();
p.print(2, 3.5f);
p.print(2,3,4);
}
}
Output:
2 3.5
2 3.0 4

Example of Method Overloading with Type Promotion in case of ambiguity


If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class Printer
{
void print(int a, float b)
{
System.out.println(a +" " + b);
}
void print(float a, int b)
{
System.out.println(a +" " + b);
}

}
public class Demo
{
public static void main(String[] args)
{
int a = 20;
int b = 30;
Printer p = new Printer();
p.print(a,b); // error: reference to print is ambiguous
}
}
Here print() is called by passing two integer values. There are two methods print() which accept
integer and floating point numbers, one more method with floating point and integer numbers.
Now java is confused which method to execute as in both methods one value is matching one
have type promotion so ambiguous error will occur.

2.1.5 Constructor Methods


A constructor is a special member function whose task is to initialize an object immediately
upon creation. The constructor is automatically called immediately after the object is created.
A constructor has the same name as the class in which it resides and is syntactically similar to
a method. If no constructor in program. System provides its own constructor called as default
constructor. Constructors doesn’t have any return type. A constructor which accepts parameters
is called as parameterized constructor. Constructors can be overloaded.
Constructors are two types
1. Non-Parameterized Constructor or Default Constructor
2. Parameterized Constructor
1. Non-parameterized constructor or default constructor: A constructor without parameters
is called Non-parameterized constrictor or default constructor.
Example for Default Constructor:
Program:
class Car
{
String name;
int mileage;
int cost;
public Car()
{
name = “BMW”;
mileage = 10;
cost = 7000000;
}
}
class ConDemo
{
public static void main(String args[])
{
Car c = new Car();
System.out.println(c.name);
System.out.println(c.mileage);
System.out.println(c.cost);
}
}
Output:
BMW
10
7000000

2. Parameterized Constructor: A constructor with parameters is called parameterized


constrictor
Example for Parameterized Constrictor:
Program:
class Car
{
String name;
int mileage;
int cost;
public Car(String name, int cost, int mileage)
{
this.name = name;
this.mileage = mileage;
this.cost = cost;
}
}
class ConDemo
{
public static void main(String args[])
{
Car c = new Car(“Ferrari”, 4000000, 5);
System.out.println(c.name);
System.out.println(c.cost);
System.out.println(c.mileage);
}
}
Output:
Ferrari
4000000
5

2.2.4 Constructor Overloading


Having Multiple constructors within a class is referred to as constructor overloading.
Constructors can also be overloaded in the same way as method overloading. Constructor
overloading is required so that different objects can be initialized differently.
Example for Constructor Overloading:
Program:
class Car
{
String name;
int mileage;
int cost;
public Car()
{
name = “BMW”;
mileage = 10;
cost = 7000000;
}
public Car(String name, int cost, int mileage)
{
System.out.println(name);
System.out.println(cost);
System.out.println(mileage);
}
}
class ConDemo
{
public static void main(String args[])
{
Car c = new Car();
System.out.println(c.name);
System.out.println(c.mileage);
System.out.println(c.cost);

Car c1 = new Car(“Ferrari”, 4000000, 5);


System.out.println(c1.name);
System.out.println(c1.cost);
System.out.println(c1.mileage);
}
}
Output:
BMW
10
7000000
Ferrari
4000000
5

2.1.9 This Keyword


If the instance variable and local variable have same name whenever you print (access) it in
the method. The value of the local variable will be printed (shadowing the instance variable).
If you still, need to access the values of instance variables in a method you need to access them
using this keyword (or object).
The this keyword can be used to refer current class instance variable in a method or constructor.
If there is ambiguity between the instance variables and parameters (local variables), this
keyword resolves the problem of ambiguity or removes the confusion.
Program:
Example for this keyword
class Car
{
String name;
int mileage;
int cost;
public Car(String name, int cost, int mileage)
{
this.name = name;
this.mileage = mileage;
this.cost = cost;
}
}
class ConDemo
{
public static void main(String args[])
{
Car c1 = new Car(“Ferrari”, 4000000, 5);
System.out.println(c1.name);
System.out.println(c1.cost);
System.out.println(c1.mileage);
}
}
Output:
Ferrari
4000000
5

Local Chaining in Constructors:


Local Chaining is the process of a constructor of a class calling another constructor of the same
class. Local chaining allows you to maintain your initialization from a single location, while
providing multiple constructors to the user. Local chaining can be achieved using this()
function call. this() should compulsorily be the first line in the constructor.
Example for Local chaining:
Program:
class Car
{
String name;
int mileage;
int cost;
public Car()
{
name = “BMW”;
mileage = 10;
cost = 7000000;
System.out.println(name);
System.out.println(mileage);
System.out.println(cost);
}
public Car(String name, int cost, int mileage)
{
this();
this.name = name;
this.mileage = mileage;
this.cost = cost;
}
}
class ConDemo
{
public static void main(String args[])
{
Car c1 = new Car(“Ferrari”, 4000000, 5);
System.out.println(c1.name);
System.out.println(c1.cost);
System.out.println(c1.mileage);
}
}
Output:
BMW
10
7000000
Ferrari
4000000
5

This below code will raise an error because there is no default constructor.
If we create even one single constructor within class the system didn’t provide any default
constructor. If we didn’t create any constructor then the system by default creates a default
constructor.
Program:
class Car
{
String name;
int mileage;
int cost;
public Car(String name, int cost, int mileage)
{
this.name = name;
this.mileage = mileage;
this.cost = cost;
}
}
class ConDemo
{
public static void main(String args[])
{
Car c1 = new Car(“Ferrari”, 4000000, 5);
System.out.println(c1.name);
System.out.println(c1.cost);
System.out.println(c1.mileage);

Car c = new Car(); //Error


System.out.println(c.name);
System.out.println(c.mileage);
System.out.println(c.cost);
}
}

Differences between Constructors and methods:

S.No Constructor Method

1. Constructor name should be same as class Method name may or may not be same
name. as class name.

2. It is mainly used for initializing the object. It is mainly used to reuse the code
without writing the code again.

3. It is implicitly invoked by the system. A method is called by the programmer.


4. The new keyword plays an important role Method calls are responsible for
in invoking the constructor. invoking methods.

5. It has no return type. It cannot return any So, it has a return type.
value to the caller.

6. Constructor cannot be overridden in java. Methods can be overridden.

7. A class can have more than one A class can also have more than one
parameterized constructor. But method with the same name but
constructors should have different different in arguments and datatypes.
parameters.

8. Sub-class cannot inherit parent class Sub-class can inherit the method of the
constructor. parent class.

9. If there is no constructor designed by user Javac never provides any method by


then the java compiler automatically default.
provides the default constructor.

10. In constructors can use both this, super In methods only use this, super
keywords and also this(), super(). keywords but not this(), super().

2.2.5 Recursive Methods


Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Example for Recursive Method
Program:
class Factorial
{
int fact(int n)
{
int result;
if(n==1)
return 1;
else
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
//System.out.println("Factorial of 3 is: " + f.fact(3));
//System.out.println("Factorial of 4 is: " + f.fact(4));
System.out.println("Factorial of 5 is: " + f.fact(5));
}
}
Output:
Factorial of 5 is: 120

2.2.6 Nesting of Methods in Java


In Java, methods and variables that are defined within a class can only be accessed by creating
an instance of that class or by using the class name if the methods are static. The dot operator
is used to access methods and variables within a class.
However, there is an exception to this rule: a method can also be called by another method
using the class name, but only if both methods are present in the same class. Efficient code
organization and simplified method calls within a class are possible through nesting of
methods.
Syntax:
class Main
{
method1(){
// statements
}
method2()
{
// statements
// calling method1() from method2()
method1();
}
method3()
{
// statements
// calling of method2() from method3()
method2();
}
}
Example for Nested Method:
Program:
public class NestingMethodsExample3
{
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("After swap: a = " + a + ", b = " + b);
}
int main(int x, int y) {
System.out.println("Before swap: x = " + x + ", y = " + y);
swap(x, y);
int product = x * y;
return product;
}
public static void main(String[] args)
{
NestingMethodsExample obj = new NestingMethodsExample();
int result = obj.main(5, 10);
System.out.println("Product: " + result);
}
}

Garbage Collection:
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?


There are many ways:
o By nulling the reference
o By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By anonymous object:
new Employee();

You might also like