0% found this document useful (0 votes)
12 views49 pages

Garbage Collection

The document discusses garbage collection in Java. It explains that in Java, memory allocation and deallocation for objects are handled automatically by the garbage collector in the Java Virtual Machine. It describes how the garbage collector works and when objects become eligible for garbage collection. It also discusses the finalize() method and inheritance in Java.

Uploaded by

jeevadon007007
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)
12 views49 pages

Garbage Collection

The document discusses garbage collection in Java. It explains that in Java, memory allocation and deallocation for objects are handled automatically by the garbage collector in the Java Virtual Machine. It describes how the garbage collector works and when objects become eligible for garbage collection. It also discusses the finalize() method and inheritance in Java.

Uploaded by

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

Garbage Collection

INTRODUCTION
● In java, allocation and deallocation of memory space for object are done by the
garbage collection process in an automated way by the JVM.
● Unlike C Language the developers need not write code for garbage collection in java
● This is one among the main features that made java popular and helps programmers
write better java applications.
When and How Java Garbage Collection Work
● The garbage collector is under the control of the JVM. The JVM decides when to run
the garbage collector. Objects that are referenced are said to be alive. Unreferenced
objects are considered garbage. From within your Java program you can ask the JVM
to run the garbage collector, but there are no guarantees, under any circumstances,
that the JVM will comply. The JVM will typically run the garbage collector when it
senses that memory is running low.
● Being an automatic process, programmers need not initiate the garbage collection
process explicitly in the code. System.gc() and Runtime.gc() are hooks to request the
JVM to initiate the garbage collection process.
EXPLICITLY MAKING OBJECTS AVAILABLE FOR
GARBAGE COLLECTION
Nulling a Reference : Set the reference variable that refers to the object to null. public
class GarbageTruck {
public static void main(String [] args)
{
StringBuffer sb = new StringBuffer("hello");
System.out.println(sb); // The StringBuffer object is not eligible for collection
sb = null; 7. // Now the StringBuffer object is eligible for collection
}}
Reassigning a Reference Variable :
We can also decouple a reference variable from an object by setting the reference
variable to refer to another object.
class GarbageTruck {
public static void main(String [] args)
{
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");
System.out.println(s1); // At this point the StringBuffer "hello" is not eligible
s1 = s2; // Redirects s1 to refer to the "goodbye" object // Now the StringBuffer
"hello" is eligible for collection } }
finalize() method

The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing.

Java Virtual Machine(JVM) permits invoking of finalize() method only once


per object.

This method is defined in Object class as:

Syntax

Access specifier return type finalize(){}


Example
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1(“hello”);
TestGarbage1 s2=new TestGarbage1(“hai”);
s1=null;
s2=null;
System.gc();
} }
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

Types of inheritance

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Single Inheritance
In Single inheritance, a single child class inherits the properties and methods of a single
parent class. In the following diagram: class B is a child class and class A is a parent
class.
Example
class Animal{

void eat(){

System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}
Multilevel Inheritance
In multilevel inheritance, a parent class becomes the child class of another class. In the
following diagram: class B is a parent class of C, however it is also a child class of A. In
this type of inheritance, there is a concept of intermediate class, here class B is an
intermediate class.
Example
class Animal{

void eat(){

System.out.println("eating...");

} }

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");} }

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat(); }}
Hierarchical Inheritance
In hierarchical inheritance, more than one class extends the same class. As shown in the
following diagram, classes B, C & D extends the same class A.
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have
the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.

class A{

void msg(){System.out.println("Hello");}

class B{

void msg(){System.out.println("Welcome");}

class C extends A,B{//suppose if it were


Simple Inheritance
class Employee {
float sal=600;
}
class Main extends Employee
{
float b=1500;
float temp= sal + b;
public static void main(String args[])
{
Main ob=new Main();
System.out.println("Salary amount is:"+ob.sal);
System.out.println(" Extra Bonous is:"+ob.temp); } }
Multilevel Inheritance
class X class MultipleInheritanceExample
class Z extends Y
{ {
{
int i; public static void main(String args[])
int k;
X() {
Z()
{ X a=new X();
{
i=5; Y b=new Y();
k=7;
}} Z c=new Z();
}}
class Y extends X System.out.println(a.i);
{ int j; System.out.println(b.i+b.j);
System.out.println(c.i+c.j+c.k);
Y()
}}
{
j=6;
}}
Hierarchical Inheritance
class Vehicle { public class Main {
class FourWheeler extends Vehicle {
double basePrice = 1000; public static void main(String[]
double increasePriceBy = 1; // 1 times args) {
public void showPrice() {
void finalPrice() { TwoWheeler bike = new
System.out.println("The price of Vehicle TwoWheeler();
is: Rs." + basePrice); }}// basePrice = basePrice + (basePrice *
increasePriceBy); FourWheeler car = new
class TwoWheeler extends Vehicle { FourWheeler();
System.out.println( "After
double increasePriceBy = 0.20; bike.showPrice();
modification, The price of car is: Rs." +
void finalPrice() { basePrice); bike.finalPrice();
basePrice = basePrice + (basePrice * }} car.showPrice();
increasePriceBy);
car.finalPrice();
System.out.println( "After modification,
The price of bike is: Rs." + basePrice); }}

}}
Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms.

Types of Polymorphism

You can perform Polymorphism in Java via two different methods:

1. Method Overloading
2. Method Overriding
Method overloading public void area(double b, double h)

Method overloading is the process that can create { System.out.println("Triangle area="+0.5*b*h);}


multiple methods of the same name in the same class,
and all the methods work in different ways. public void area(int l, int b)

class Shapes { {

public void area() System.out.println("Rectangle area="+l*b);

{ }}

System.out.println("Find area "); class Main {

} public static void main(String[] args) {

public void area(int r) { Shapes myShape = new Shapes(); myShape.area();

System.out.println("Circle area = "+3.14*r*r); myShape.area(5);

} myShape.area(6.0,1.2);

myShape.area(6,2); } }
Method overriding class Car2 extends Vehicle()

{
Method overriding is the process when the
subclass or a child class has the same method as void run()
declared in the parent class.
{
class Vehicle{
System.out.println("car is running safely");
void run()
}
{
public static void main(String args[])
System.out.println("Vehicle is moving");}
{
}
Car2 obj = new Car2();

obj.run();

}}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Example
class Animal { public void bark() {

String name=”tiger”; System.out.println("I can bark");

public void eat() { }

System.out.println("I can eat"); } class Main {

}} public static void main(String[] args) {

class Dog extends Animal { Dog labrador = new Dog();

public void eat() { labrador.eat();

System.out.println(super.name); labrador.bark();

} }}

super.eat();

System.out.println("I eat dog food"); }


Abstraction Class and Method
A class which is declared as abstract is known as
Syntax abstract method
an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and 1. abstract void printStatus();//no method
its method implemented. It cannot be instantiated.
body and abstract
Points to Remember 2. abstract Class name

○ An abstract class must be declared with an


abstract keyword.
○ It can have abstract and non-abstract
methods.
○ It cannot be instantiated.
○ It can have constructors and static methods
also.
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw(); } }
Interface
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static
constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in
Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
import java.io.*; public static void main(String[] args)

interface In1 { {
TestClass t = new TestClass();
final int a = 10;
t.display();
void display();
System.out.println(a);
}
}
class TestClass implements In1 { }
public void display(){
System.out.println("Geek");
}
Access modifier
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc to the user depending upon the access modifier used with the element.

Types of Access Modifiers in Java

There are four types of access modifiers available in Java:


1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
package p1;
When no access modifier is specified for a class,
method, or data member – It is said to be having the class Geek
default access modifier by default. The data members,
classes, or methods that are not declared using any {
access modifiers i.e. having default access modifiers void display()
are accessible only within the same package.
{

System.out.println("Hello World!");

}
2. Private Access Modifier
The private access modifier is specified using the keyword package p1;
private. The methods or data members declared as private are
accessible only within the class in which they are declared. class A{
● Any other class of the same package will not be able
private void display(){
to access these members.
● Top-level classes or interfaces can not be declared as System.out.println("GeeksforGeeks");
private because
}}
● private means “only visible within the
enclosing class”. class B
● protected means “only visible within the {public static void main(String args[])
enclosing class and any subclasses”
{A obj = new A();

obj.display();}}
3. Protected Access Modifier
package p1;
The protected access modifier is specified using
the keyword protected. public class A
The methods or data members declared as {
protected are accessible within the same
package or subclasses in different packages. protected void display()

System.out.println("GeeksforGeeks")
;

}
Public Access modifier
package p1;
The public access modifier is specified using the keyword
public. public class A
● The public access modifier has the widest scope
{
among all other access modifiers.
public void display()
● Classes, methods, or data members that are
{
declared as public are accessible from everywhere
System.out.println("GeeksforGeeks");
in the program. There is no restriction on the scope
of public data members. }

}
java package
Types of Packages in Java
A java package is a group of similar types of Packages in Java can be categorised into 2
classes, interfaces and sub-packages. categories.
The package keyword is used in Java to create
1. Built-in / predefined packages
Java packages.
2. User-defined packages.
Many in-built packages are available in Java,
including util, lang, awt, javax, swing, net, io, sql,
etc

We can import all members of a package using


packagename.* statement.
import java.lang.*;
Built-in packages
public class Example {
When we install Java on a personal computer or
public static void main(String[] args) {
laptop, many packages are automatically
installed. Each of these packages is unique and double radius = 5.0;
capable of handling various tasks. This eliminates
the need to build everything from scratch. Here double area = Math.PI * Math.pow(radius, 2);
are some examples of built-in packages: System.out.println("Area: " + area);

● java.lang String message = "Hello, World!";


● java.io int length = message.length();
● java.util
● java.applet System.out.println("Length: " + length);
● java.awt int number = 42;
● java.net
String binary = Integer.toBinaryString(number);

System.out.println("Binary: " + binary);}}


User-defined packages
package myFirstPackage;
User-defined packages are those that developers
create to incorporate different needs of class Main {
applications. In simple terms, User-defined public static void main(String args[]) {
packages are those that the users define. Inside a
package, you can have Java files like classes, System.out.println("Wooohooo!! I created my
first package");
interfaces, and a package as well (called a
sub-package). }

Sub-package }

A package defined inside a package is called a


sub-package. It’s used to make the structure of the
package more generic. It lets users arrange their
Java files into their corresponding packages. For
example, say, you have a package named cars.
You’ve defined supporting Java files inside it.
StringBuffer class
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string without
creating a new object every time.

advantages of using StringBuffer

Mutable: which means that you can modify the contents of the object after it has been created

Efficient: Because StringBuffer objects are mutable, they are more efficient than creating new
String objects each time you need to modify a string.

Thread-safe: they can be safely accessed and modified by multiple threads simultaneously
Methods & Action Performed
append() ->Used to add text at the end of the existing text.
length() ->The length of a StringBuffer can be found by the length( ) method
capacity() ->The total allocated capacity can be found by the capacity( ) method
charAt() ->This method returns the char value in this sequence at the specified index.
delete() ->Deletes a sequence of characters from the invoking object
deleteCharAt() ->Deletes the character at the index specified by the loc
ensureCapacity() ->Ensures capacity is at least equal to the given minimum.
insert() ->Inserts text at the specified index position
length() ->Returns the length of the string
reverse() ->Reverse the characters within a StringBuffer object
replace() ->Replace one set of characters with another set inside a StringBuffer object
import java.io.*;
Hello java
class A {
public static void main(String args[]) Hjavaello java
{
Hprogramaello java
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); Hgramaello java
System.out.println(sb);
avaj olleamargH
sb.insert(1, "Java");
System.out.println(sb); a
sb.replace(1, 3, "program");
System.out.println(sb);
sb.delete(1, 3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println(Sb.chartAt(2));
System.out.println(sb);
}
Object class
The Object class is the parent class of all the classes in Methods
java by default. In other words, it is the topmost class of tostring()
java.
hashCode()
The Object class is beneficial if you want to refer any
object whose type you don't know. Notice that parent class clone()
reference variable can refer the child class object, know as
upcasting.

Object obj=getObject();//we don't know what object will


be returned from this method
import java.util.*;
toString() Method public class Main {

As the name suggests, it returns a string representation of an int car_no;


object. It is used to convert an Object "to String".
Main(int car_no){

As each class is a sub-class of the Object class in Java. So the this.car_no=car_no;


toString() method gets inherited by the other classes from the
Object class. }

public static void main(String args[])


If we try to print the object of any class, then the JVM
internally invokes the toString() method. {

Main s = new Main(16);


It is a good practice to override the toString() in an inherited
class as it'll aid in a better string representation of the object. System.out.println(s.toString());
If we do not override it, it will give the hexadecimal
representation of the object. System.out.println(s);

}}
import java.util.*;
hashCode() Method public class Main {

A hash code is an integer value that gets generated by int car_no;


the hashing algorithm. Hash code is associated with each Main(int car_no){
object in Java and is a distinct value. It converts an
object's internal address to an integer through an this.car_no=car_no;
algorithm. It is not the memory address, it is the integer
} public static void main(String args[])
representation of the memory address.
{

Main s = new Main(16);

System.out.println(s.hashCode());

}
clone() Method
The object cloning is a way to create exact copy of an object. The clone()
method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose


object clone we want to create. If we don't implement Cloneable interface,
clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone()
method is as follows:

1. protected Object clone() throws CloneNotSupportedException


import java.util.*; try {

class Main implements Cloneable { Main obj2 = (Main)obj1.clone();

String name; System.out.print(obj2.name); // xyz

int age; System.out.println(" "+ obj2.age); // 19

public static void main(String[] args) { }

Main obj1 = new Main(); catch (Exception e) {

obj1.name = "xyz"; System.out.println(e);

obj1.age = 19; }}

System.out.print(obj1.name); // xyz }

System.out.println(" "+ obj1.age); // 19


static Keyword
The static keyword in Java is mainly used for memory management. The static
keyword in Java is used to share the same variable or method of a given class. The
users can apply static keywords with variables, methods, blocks, and nested classes.
The static keyword belongs to the class than an instance of the class. The static
keyword is used for a constant variable or a method that is the same for every
instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the
following:
1. Blocks
2. Variables
3. Methods
4. Classes
class Test

Static blocks {

static int a = 10; static int b;


If you need to do the computation in order to
initialize your static variables, you can declare a static {
static block that gets executed exactly once, when System.out.println("Static block initialized.");
the class is first loaded.
b = a * 4;}

public static void main(String[] args)

System.out.println("from main");

System.out.println("Value of a : "+a);

System.out.println("Value of b : "+b);

}}
static variables class Test

{
When a variable is declared as static, then a single
copy of the variable is created and shared among all Static int a=10;
objects at the class level. Static variables are,
essentially, global variables. All instances of the class Public static void main(string args[)
share the same static variable.
{
Important points for static variables:
System.out.println(a);
● We can create static variables at the class
level only.static block and static variables are }

executed in the order they are present in a


program.
class Test
Static methods { static void m1(){

When a method is declared with the static System.out.println(“from m1”);


keyword, it is known as the static method. The
}
most common example of a static method is the
main( ) method. As discussed above, Any static void m2()
member can be accessed before any objects of its
class are created, and without reference to any {
object. Methods declared as static have several System.out.println("from m2");
restrictions:
}
● They can only directly call other static
methods. public static void main(String[] args)

● They can only directly access static data. {m1();

● They cannot refer to this or super in any Test obj=new Test();


way. obj.m2();}}
import java.io.*;

Static Classes public class GFG {

private static String str = "GeeksforGeeks";


A class can be made static only if it is a nested
static class MyNestedClass {
class. We cannot declare a top-level class with a
static modifier but can declare nested classes as public void disp(){
static. Such types of classes are called Nested
static classes. Nested static class doesn’t need a System.out.println(str);}}
reference of Outer class. In this case, a static class
public static void main(String args[])
cannot access non-static members of the Outer
class. {

GFG.MyNestedClass obj = new GFG.MyNestedClass();

obj.disp();

}}

You might also like