Garbage Collection
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.
Syntax
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.
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...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
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...");
} }
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");} }
class TestInheritance2{
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");}
}}
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
1. Method Overloading
2. Method Overriding
Method overloading public void area(double b, double h)
class Shapes { {
{ }}
} 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.
System.out.println(super.name); labrador.bark();
} }}
super.eat();
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.
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
Sub-package }
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.
}}
import java.util.*;
hashCode() Method public class Main {
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 clone() method is defined in the Object class. Syntax of the clone()
method is as follows:
obj1.age = 19; }}
System.out.print(obj1.name); // xyz }
Static blocks {
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 }
obj.disp();
}}