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

Unit - 5 Java Notes

Uploaded by

vishwas89695
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit - 5 Java Notes

Uploaded by

vishwas89695
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit-5

Inheritance in Java:
Inheritance is an important concept of OOPs. It is a mechanism in which a child object
acquires all the properties and behaviors of a parent object. Inheritance means driving a
new class from an existing class The existing class is known as base class or super class or
parent class. The new class is known as a derived class or sub class or child class.
Inheritance provides the reusability of code especially when there is a large scale of code to
reuse.
Note: we can’t access private members of class through inheritance.
Method overriding only possible through inheritance.
Syntax :
Class Superclass-name
{
//methods and fields

}
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 in java:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance

1.Single Inheritance:
➢ In single inheritance, subclasses inherit the features of one superclass. In the
image below, class A serves as a base class for the derived class B.

or ➢ When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.
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();
}}

Output:

barking...
eating...

2.Multilevel Inheritance:
➢ In Multilevel Inheritance, a derived class will be inheriting a base class, and as
well as the derived class also acts as the base class for other classes. In the
below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot
directly access the grandparent’s members.
Or
➢ When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.
Multilevel Inheritance

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();
}}

Output:

weeping...
barking...
eating...
3. Hierarchical Inheritance:
➢ When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance. OR
➢ In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the
derived classes B, C, and D.
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
}}
Output:
meowing...
eating...
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A
and B.
Q) 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.

Example:

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

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked? }
}
Compile Time Error

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.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.
Example:
class A
{
int i = 10;
}
class B extends A
{
int i = 20;
void show(int i)
{
System.out.println(i);
System.out.println(this.i);
System.out.println(super.i);
}
public static void main(String[] args)
{
B ob=new B();
ob.show(30);
}
}
Output:
30
20
10
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.
Example:
class A
{
void m1()
{
System.out.println(" i am Monitor");
}
}
class B extends A
{
void m1()
{
System.out.println(" i am student");
}
void show()
{
m1();
super.m1();
}
public static void main(String[] args)
{
B ob=new B();
ob.show();
}
}
Output:
i am student
i am Monitor
To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
class A
{
A()
{
System.out.println(" iam Class A");
}
}
class B extends A
{
B()
{
Super();
System.out.println(" i am Class B");// super and super()
}
public static void main(String[] args)
{
B ob=new B();
}
}
Output:
i am Class A
i am Class B

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

As we know well that default constructor is provided by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class A
{
A()
{
System.out.println(" iam Class A");
}
}
class B extends A
{
B()
{
System.out.println(" i am Class B"); b// super and super()
}
public static void main(String[] args)
{
B ob=new B();
}
}
Output:
i am Class A
i am Class B

Method Overriding in Java:

• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
Example:
class Person {
// Method to be overridden
public void display() {
System.out.println("I am a person.");
}
// Another method to be overridden
public void work() {
System.out.println("Person is working.");
}
}

class Student extends Person {


// Overriding the display method
@Override
public void display() {
System.out.println("I am a student.");
}
// Overriding the work method
@Override
public void work() {
System.out.println("Student is studying.");
}
}

class Main {
public static void main(String[] args) {
Person person = new Person(); // Create a Person object
person.display(); // Output: I am a person.
person.work(); // Output: Person is working.

Student student = new Student(); // Create a Student object


student.display(); // Output: I am a student.
student.work(); // Output: Student is studying.
}
}
Output:
I am a person.
Person is working.
I am a student.
Student is studying.

Abstraction class in Java:

• Abstraction is a process of hiding the implementation details and showing only .


• A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Example :
abstract class A{}

Note: We con’t create object for abstract class.

Abstract Method in Java:


• A method which is declared as abstract and does not have implementation is known
as an abstract method.

Example:

abstract void print Status();//no method body and abstract

Rules for Java Abstract class


 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 To use an abstract class, you have to inherit it from subclass.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of
the method.
 A method without a body is known as an Abstract Method. It must be declared
in an abstract class.
 The abstract method will never be final because the abstract class must
implement all the abstract methods.

Example:
abstract class Bike{
abstract void run(); // abstract method
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely

Example2:
abstract class vehicle
{
abstract void start();

}
class car extends vehicle
{
void start()
{
System.out.println("Car Starts with key ");
}
}
class Scooter extends vehicle
{
void start()
{
System.out.println("Scooter Starts with kick ");
}
public static void main(String[] agrs)
{
//vehicle v = new vehicle();
car c = new car();
c.start();
Scooter s = new Scooter();
s. start();
}
}
Output:

Car Starts with key


Scooter Starts with kick

Object class in Java:


✓ The Object class is the parent class of all the classes in java by
default.
✓ In other words, it is the topmost class of java.
✓ The Object class provides some common behaviors to all the objects such as
object can be compared, object can be cloned, object can be notified etc.
✓ Object class is present in java.lang package.
Every class in Java is directly or indirectly derived from the Object class.
✓ Therefore the Object class methods are available to all Java classes.
✓ Hence object class acts as a root of the inheritance hierarchy in any Java
Program.

For example:

Object obj=getObject(); //we don't know what object will be returned from this method
➢ The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.

What is Package in Java?

• A java package is a collection of similar types of classes, interfaces


and other packages.
• It works as containers for classes and other sub-packages.
• In other words we can say that the package is a way to group different classes
or interfaces together.
• The grouping is done on the basis of functionality of classes and
interfaces.
• There are two types of package in Java:
o Built-in Packages (packages from the Java API)
o User-defined Packages (create your own packages)

• There are many built-in packages such as java, lang, awt, net, io, util, applet etc.

Import Package:
We import the java package using the keyword import.
Suppose we want to use the student class stored in the java.util package then we
can write the import statement at the beginning of the program like:

import.java.util.student;

Access Protection in Packages:

➢ Packages adds another dimension to the access control.


➢ Java provides many levels of security that provides the visibility of members
within the classes,
➢ subclasses, and packages.
➢ Access modifiers define the scope of the class and its members.
➢ In java, the accessibility of the members of a class or interface depends on
its access specifiers.

There are four types of Java access modifiers:

1. Public
2. Private

3. Protected

4. Default

Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.

Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.

Interface in Java:
Interface is just like a class in java.
▪An interface is a fully abstract class.
▪ It includes a group of abstract methods without a body.
▪ We use the interface keyword to create an interface in Java.
▪ Interface variables are by default public, static and final.
▪ Like abstract classes, we cannot create objects of interfaces.
▪ To use an interface, other classes must implement it.
▪ We use the implements keyword to implement an interface.
 Inside the Interface, constructors are not allowed.
 Inside the interface main method is not allowed.
 On implementation of an interface, you must override all of its methods.
Syntax:

interface <interface_name>{
// declare methods that abstract
// declarepublic,final ,static fields
// by default.
}
Class Interface

In class, you can instantiate variables In an interface, you must initialize variables as
and create an object. they are final but you can’t create an object.

A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.

The access specifiers used with classes


In Interface only one specifier is used- Public.
are private, protected, and public.

Why and When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple interfaces.

Note: To implement multiple interfaces, separate them with a comma

Internal addition by the compiler:


The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, static and final keywords before data members.

The relationship between classes and interfaces:


A class extends another class, an interface extends another interface, but a class implements an interface.

Java Interface Example :


interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Gems Polytechnic college
Aurangabad….."); }
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output: Gems Polytechnic college Aurangabad…

Example1:
interface Animal {
void animalSound(); // interface method (does not have a body)
void sleep(); // interface method (does not have a body)
}
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
public void sleep() {
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Output:
The pig says: wee wee
Zzz
Notes on Interfaces:
 Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)

2.Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces,


it is known as multiple inheritance.

Example: To implement multiple interfaces, separate them with a comma:


interface I1{
void print();
}
interface I2{
void Display();
}
class Test implements I1,I2{
public void print(){
System.out.println("Gems Polytechnic college Aurangabad…..");
}
public void Display();
{
System.out.println("Computer Science Engineering…..");
}
Public static void main(String args[]){
Test obj = new Test();
obj.print();
obj.display();
}
}
Output:
Gems Polytechnic college Aurangabad…
Computer Science Engineering….

Exception:
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at
run time, that disturb the normal flow of the program.

OR In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

Exception Handling:

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained. It is an event that disturbs the normal flow of the program.
It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An exception
normally disturbs the normal flow of the application; that is why we need to handle exceptions

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Example:
class Test
{
public static void main (String[] agrs)
{
System.out.println(100);
System.out.println(10);
System.out.println(100);
System.out.println(10/0);//exception
System.out.println(20);
System.out.println(1000);
System.out.println(40);
System.out.println(1004);
System.out.println(4005);
System.out.println(6003);
}
}
Output:
100
10
100
Exception in thread "main" java.lang.ArithmeticException: / by zero
class Test
{
public static void main (String[] agrs)
{
System.out.println(100);
System.out.println(10);
System.out.println(100);
try{
System.out.println(10/0);
}
catch(Exception e)
{
System .out.println(“ We can’t divide by zero”);
}
System.out.println(20);
System.out.println(1000);
System.out.println(40);
System.out.println(1004);
System.out.println(4005);
System.out.println(6003);
}
}

Hierarchy of Java Exception classes:

The throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and
Error
Difference between Exception and Error in java:
Errors Exceptions
Error occurs because of lack of system resources Exception occurs because of your programs

Recovering from Error is not possible. We can recover from exceptions by either using try catch
block or throwing exceptions back to the caller.

Error are only of one type: Exception are of two types:


Runtime Exception or Unchecked Exception • Compile Time Exception or Checked Exception
• Run Time Exception or Unchecked Exception

Errors are mostly caused by the environment in Program itself is responsible for caused exceptions.
which program is running.

Types of Java Exceptions:

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1) Checked Exception :

The classes that directly inherit the Throwable class except CompileException is known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception :

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error : Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Exception:
class Test{
public static void main(String args[]){
//FileInputStream fis= new FileInputStream(“d:/abc.txt”);
//Class.forName(com.mysql.jdbc”);
int a=100,b=0;
int c=100/0;
System.out.println( c);
}
}
Output: compile successfully

Java Exception Handling Example:


Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle
the exception.

JavaExceptionExample.java :

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the
code...

Java Exception Keywords:


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java try-catch block :

 Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
 If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute.
 Java try block must be followed by either catch or finally block.

Syntax of Java try-catch:

try {
//code that may throw an exception
} catch(Exception_class_Name ref){}

Syntax of try-finally block :

try{
//code that may throw an exception
}finally{}

TryCatchExample2.java

public class TryCatchExample2 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
} Output: java.lang.ArithmeticException: / by zero rest of the code

Multi-catch block:
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-
catch block.

Example:
class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
// System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output: Arithmetic Exception occurs
rest of the code

//ArrayIndexOutOfBounds Exception occurs


// rest of the code

Java Nested try block :

 In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.
 For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException
while the outer try block can handle the ArithemeticException (division by zero).

Why use nested try block :

Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

//main try block


try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
Example:
class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..

Difference Between Throw and Throws :


Sr. Basis of throw throws
no. Differences

Java throws keyword is used in the


Java throw keyword is used throw
method signature to declare an
an exception explicitly in the code,
1 Definition exception which might be thrown by
inside the function or the block of
the function while the execution of the
code.
code.

Type of exception Using throw Using throws keyword, we can declare


keyword, we can only propagate both checked and unchecked
2 Usage unchecked exception i.e., the exceptions. However, the throws
checked exception cannot be keyword can be used to propagate
propagated using throw only. checked exceptions only.

The throw keyword is followed by an The throws keyword is followed by class


3 Syntax
instance of Exception to be thrown. names of Exceptions to be thrown.

throws is used with the method


4 Declaration throw is used within the method.
signature.
Throw keyword in Java :
➢ Throw Keyword is used to throw the user defined or customized exception object to the
JVM explicitly for that purpose we use throw keyword.
➢The Throw keyword in Java allows you to throw an exception explicitly in the code.
➢ The throw keyword comes in handy when you want to raise an exception in your
code based on specific conditions.

Throw Example:
if (balance <withdrawAmount) {
throw new InsufficientBalanceException("You have insufficient balance");
}

Java throw Example:


class throwDemo
{
public static void main (String[] args)
{
System.out.println(100/0);
throw new ArithmeticException("/ by zero");
throw new InvalidAgeException(" Age not greater then 20");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at throwDemo.main(throwDemo.java:6)

Throws keyword in Java:


➢ throws keyword when we doen’t want to handle the exception and try to sed
the exception to JVM or other method.
➢ Throws keyword in Java is used in a method signature to declare that the
method might throw an exception.

➢ When you declare a method using the Throws keyword, the method does not handle the
exception itself. But instead, it passes it on to the calling code. The calling code must either
handle the exception using a “try-catch” block or declare it in its own method signature
using the Throws keyword.
Throws Example:
public void withdraw(double amount) throws InsufficientBalanceException
InsufficientBalanceException("You have insufficient balance");

Public static void main(Strinr[] args)


}
// ...
}
Java throws Example:
class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}
Output:

Java throw and throws Example:


public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output:

Java finally block


Java finally block is a block used to execute important code such as closing the connection, etc.
 Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.
 The finally block follows the try-catch block.

Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).

TestFinallyBlock.java

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
Output:

Built-in Exception:
Exceptions that are already available in Java libraries are referred to as built-in exception. These
exceptions are able to define the error situation so that we can understand the reason of getting this
error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked
exception.

Checked Exception: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler. The compiler ensures whether the
programmer handles the exception or not. The programmer should have to handle the exception;
otherwise, the system has shown a compilation error.

CheckedExceptionExample.java

import java.io.*;
class CheckedExceptionExample {
public static void main(String args[]) {
FileInputStream file_data = null;
file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop /Hello.txt");
int m;
while(( m = file_data.read() ) != -1) {
System.out.print((char)m);
}
file_data.close();
}
}

we are trying to read the Hello.txt file and display its data or content on the screen.
The program throws the following exceptions:

1. The FileInputStream(Filefilename) constructor throws the FileNotFoundException that is


checked exception.
2. The read() method of the FileInputStream class throws the IOException.

3. The close() method also throws the IOException.

Output:
Unchec

ked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check
these exceptions at compile time. In simple words, if a program throws an unchecked exception, and
even if we didn't handle or declare it, the program would not give a compilation error. Usually, it
occurs when the user provides bad data during the interaction with the program.

Note: The RuntimeException class is able to resolve all the unchecked exceptions

UncheckedExceptionExample1.java

class UncheckedExceptionExample1 {
public static void main(String args[])
{
int postive = 35;
int zero = 0;
int result = positive/zero; //Give Unchecked Exception here.
System.out.println(result);
}
}

Output:

User-defined Exception:
 In Java, we already have some built-in exception classes like
ArrayIndexOutOfBoundsException, NullPointerException, and ArithmeticException.
These exceptions are restricted to trigger on some predefined conditions.

 In Java, we can write our own exception class by extends the Exception class. We can
throw our own exception on a particular condition using the throw keyword. For creating a
user-defined exception, we should have basic knowledge of the try-catch block and throw
keyword.

UserDefinedException.java

import java.util.*;
class UserDefinedException{
public static void main(String args[]){
try{
throw new NewException(5);
}
catch(NewException ex){
System.out.println(ex) ;
}
}
}
class NewException extends Exception{
int x;
NewException(int y) {
x=y;
}
public String toString(){
return ("Exception value = "+x) ;
}
}
Output:

Difference between final, finally and finalize:


The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these
keywords has a different functionality. The basic difference between final, finally and finalize is that
the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object
class.

Along with this, there are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
Sr. Key final finally finalize
no.

final is the keyword finally is the block in Java finalize is the method in Java
and access modifier Exception Handling to which is used to perform
1. Definition which is used to apply execute the important code clean up processing just
restrictions on a class, whether the exception before object is garbage
method or variable. occurs or not. collected.

Finally block is always


Final keyword is used
related to the try and catch finalize() method is used with
2. Applicable to with the classes,
block in exception the objects.
methods and variables.
handling.

(1) Once declared, final


variable becomes
(1) finally block runs the
constant and cannot be
important code even if finalize method performs the
modified.
exception occurs or not. cleaning activities with
3. Functionality (2) final method cannot
(2) finally block cleans up respect to the object before its
be overridden by sub
all the resources used in try destruction.
class.
block
(3) final class cannot
be inherited.

Finally block is executed as


Final method is soon as the try-catch block
finalize method is executed
4. Execution executed only when we is executed. It's execution is
just before the object is
call it. not dependant on the
destroyed.
exception.

Java final Example


Let's consider the following example where we declare final variable age. Once declared it cannot be
modified.

FinalExampleTest.java

public class FinalExampleTest {

//declaring final variable


final int age = 18;
void display() {
// reassigning value to age variable
// gives compile time error
age = 55;
}
public static void main(String[] args) {
FinalExampleTest obj = new FinalExampleTest();
// gives compile time error
obj.display();
}
}
Output:

In the above example, we have declared a variable final. Similarly, we can declare the methods and classes final
using the final keyword.

Java finally Example:


Java code throws an exception and the catch block handles that exception. Later the finally block is executed
after the try-catch block. Further, the rest of the code is also executed normally.

FinallyExample.java

public class FinallyExample {


public static void main(String args[]){
try {
System.out.println("Inside try block");
// below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
// handles the Arithmetic Exception / Divide by zero exception
catch (ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
// executes regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:

Java finalize Example:


FinalizeExample.java

public class FinalizeExample {


public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
System.out.println("Hashcode is: " + obj.hashCode());
obj = null;
// calling the garbage collector using gc()
System.gc();
System.out.println("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
System.out.println("Called the finalize() method");
}
}
Output:

You might also like