Chapter 6 - Oops
Chapter 6 - Oops
Semester – 4 th
Subject Name - Object Oriented Programming – 1
Subject Code - BE103404
Faculty Name – Radhika Gokani
Chapter – 6
Exception Handling, I/O, abstract classes and interfaces
6.1 Exception types
Certainly! In Java, there are several built-in exception types that relate to various class
libraries. Let’s explore some of the most important ones:
1. ArithmeticException:
o Thrown when an exceptional condition occurs during an arithmetic operation (e.g., division by zero).
o Example:
Java
int a = 30, b = 0;
int c = a / b; // Throws ArithmeticException: Can't divide a number by 0
2. ArrayIndexOutOfBoundsException:
o Raised when an array is accessed with an illegal index (negative or greater than the array size).
o Example:
Java
Java
try {
Class.forName("NonExistentClass");
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
}
4. FileNotFoundException:
o Thrown when a file is not accessible or fails to open.
o Example:
try {
FileReader fileReader = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
5. NullPointerException:
o Raised when referring to members of a null object.
o Example:
Remember that checked exceptions (like IOException) must be explicitly handled, while
unchecked exceptions (like NullPointerException) do not require explicit handling.
The finally clause in Java is a powerful construct that allows you to execute code
regardless of whether an exception occurs or not. Let’s learn it into the details:
1. Purpose of finally block:
o The finally block is used to execute important code, such as closing connections,
releasing resources, or performing cleanup tasks.
o It ensures that specific statements are executed no matter what happens in the
preceding try block or any associated catch blocks.
2. Execution Flow:
o The finally block follows either a try block or a catch block.
o Whether an exception occurs or not, the statements inside the finally block always
execute.
o Even if an unhandled exception terminates the program, the finally block still runs
before the program exits.
o
3. Examples: When an exception does not occur:
class TestFinallyBlock {
public static void main(String[] args) {
try {
// Code that does not throw any exception
int data = 25 / 5;
System.out.println(data);
} catch (NullPointerException e) {
// Catch block won't be executed
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("Rest of the code...");
}
}
Output:
5
finally block is always executed
Rest of the code...
o Normally, a catch block is used to handle exceptions raised in the try block.
o However, if the catch block is unable to handle the exception, you can rethrow it using
the throw keyword.
o When you rethrow an exception, it propagates to the exception handlers in the next higher
context (e.g., an outer try block).
o Any further catch clauses for the same try block are still ignored.
Sample Example:
public class Main
{
public int test(int n1, int n2) {
try {
return n1 / n2;
} catch (ArithmeticException e) {
throw e; // Rethrow the caught exception
}
}
In Java, chained exceptions allow you to associate one exception with another,
making debugging easier by providing additional information about the specific
error.
o In this example:
A NumberFormatException is caught.
We create a new RuntimeException with the message “Exception.”
The cause of the new exception is set to a NullPointerException with the message “It is
the actual cause of the exception.”
The new exception is thrown, preserving the chain.
Java
o In this example:
The validateFileName method checks if the given file name matches the pattern [a-zA-
Z0-9_]+\\.txt.
If the file name is invalid, it throws a WrongFileNameException.
The main method catches the exception and prints the error message.
Output:
File name is valid.
Let’s explore the Java File class, which is an essential part of handling file input and
output operations. The File class provides an abstract representation of file and
directory pathnames. Here are the key points about the File class:
1. Overview:
o The File class allows you to work with both files and directories.
o It represents system-independent views of hierarchical pathnames.
o You can create, delete, rename, and list files and directories using its methods.
2. Creating a File Instance:
o You can create a File instance using various constructors:
File(String pathname): Creates a new File instance from a pathname string.
File(File parent, String child): Creates a new File instance from a parent
abstract pathname and a child pathname string.
File(URI uri): Creates a new File instance from a file URI.
And more…
3. Common Methods:
o Some useful methods provided by the File class:
getName(): Returns the name of the file or directory.
getParent(): Returns the parent pathname string.
isDirectory(): Checks if the path denotes a directory.
isFile(): Checks if the path denotes a normal file.
listFiles(): Returns an array of abstract pathnames for files in a directory.
toPath(): Converts the File to a java.nio.file.Path object.
And more…
4. Example: Listing Files in a Directory:
import java.io.File;
o The java.nio.file package provides more advanced features for file I/O.
o Consider using it for better performance and additional capabilities.
import java.net.*;
public class URLExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host Name: " + url.getHost());
System.out.println("Port Number: " + url.getPort());
System.out.println("File Name: " + url.getFile());
} catch (Exception e) {
System.out.println(e);
}
}
}
o Output:
o Protocol: https
o Host Name: www.javatpoint.com
o Port Number: -1
o File Name: /java-tutorial
2. Using the URLConnection Class:
o The URLConnection class establishes a connection between your application and a resource
(such as a URL).
o You can use it to read or write data from/to the specified resource.
o To get a URLConnection object, call the openConnection() method on a URL object.
o example of reading data from a URL:
import java.io.*;
import java.net.*;
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading data: " + e.getMessage());
}
}
}
o Replace "https://www.example.com" with the actual URL you want to read from.
o This example reads the content from the specified URL and prints it line by line.
In Java, abstract classes play a crucial role in designing class hierarchies and
providing a blueprint for other classes.
1. What is an Abstract Class?
o An abstract class is a class that cannot be instantiated directly (i.e., you cannot create
objects of it).
o It serves as a blueprint for other classes by defining common properties and methods.
o Abstract classes can have both abstract methods (methods without a body) and non-
abstract methods (methods with implementations).
2. Key Points about Abstract Classes:
o Declaration: You define an abstract class using the abstract keyword in its class definition.
o Inheritance: Other classes can extend (inherit from) an abstract class.
o Abstract Methods: Abstract classes can contain abstract methods, which must be
implemented by their subclasses.
o Non-Abstract Methods: They can also have regular (non-abstract) methods with
implementations.
o Constructor: Abstract classes can have constructors.
o Instance Creation: You cannot directly create an instance of an abstract class.
3. Example: Abstract Class with Abstract Method:
abstract class Shape {
int color; // Data member
6.9 Interfaces
interface MyInterface {
// Declare constant fields (static and final by default)
int MY_CONSTANT = 42;
3. Implementing an Interface:
o A class can implement one or more interfaces using the implements keyword.
o When a class implements an interface, it must provide implementations for all the methods
declared in that interface.
o Example:
@Override
public int calculate(int x, int y) {
// Implementation for calculate()
return x + y;
}
}
4. Advantages of Interfaces:
o Achieving total abstraction: Interfaces allow you to define behavior without specifying
implementation details.
o Supporting multiple inheritances: A class can implement multiple interfaces, overcoming
the limitation of single inheritance in classes.
o Promoting loose coupling: Interfaces help decouple classes by defining contracts without
enforcing a specific class hierarchy.
5. Difference Between Class and Interface:
o Class:
Can be instantiated (objects can be created).
Can contain concrete (implemented) methods.
Supports access specifiers (private, protected, public).
o Interface:
Cannot be instantiated (no objects).
Contains only abstract methods (no implementation).
All methods are implicitly public.
Can extend other interfaces (but not classes).
6. Example: Using an Interface:
Java
interface Player {
int MAX_SCORE = 100; // Constant field
@Override
public void pause() {
// Implementation for pause()
}
}
o The Comparable interface allows you to define the default ordering for objects of your class.
o It provides the compareTo method, which compares the current object with another object.
2. Method Signature:
@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
}
4. Usage:
o You can use Comparable when sorting collections (e.g., List, Set) of objects.
o Collections that support natural ordering (e.g., TreeSet, Arrays.sort) use
the compareTo method.
Cloneable Interface:
The Cloneable interface is a marker interface in Java. It indicates that a class can be
cloned using the Object.clone() method.
Purpose:
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
4. Usage:
o Use Cloneable when you want to create a copy of an object without explicitly using
the new operator.
o Remember that clone() performs a shallow copy by default; for deep copies, customize the
method.