0% found this document useful (0 votes)
4 views42 pages

Java UNIT - 4 Material

Unit IV of the document covers Java packages, including their definition, advantages, and how to create and use them. It also discusses exception handling, Java I/O, wrapper classes, and utility classes from the java.util package. Additionally, it provides examples of package usage, class access methods, and the Formatter class for formatted text output.

Uploaded by

saitharunkumar26
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)
4 views42 pages

Java UNIT - 4 Material

Unit IV of the document covers Java packages, including their definition, advantages, and how to create and use them. It also discusses exception handling, Java I/O, wrapper classes, and utility classes from the java.util package. Additionally, it provides examples of package usage, class access methods, and the Formatter class for formatted text output.

Uploaded by

saitharunkumar26
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/ 42

Object Oriented Programming Through Java UNIT-3

Object Oriented Programming Through Java

Unit - 4

UNIT IV: Packages and Java Library: Introduction, Defining Package, Importing Packages and
Classes into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang
Package and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and
Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class, Time Package,
Class Instant (java.time.Instant), Formatting for Date/Time in Java, Temporal Adjusters Class,
Temporal Adjusters Class. Exception Handling: Introduction, Hierarchy of Standard Exception
Classes, Keywords throws and throw, try, catch, and finally Blocks, Multiple Catch Clauses, Class
Throwable, Unchecked Exceptions, Checked Exceptions. Java I/O and File: Java I/O API, standard
I/O streams, types, Byte streams, Character streams, Scanner class, Files in Java

Java Package :
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package :
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

GATES-CSE(DS|CY) Page 1
Object Oriented Programming Through Java UNIT-3
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.

GATES-CSE(DS|CY) Page 2
Object Oriented Programming Through Java UNIT-3
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }

GATES-CSE(DS|CY) Page 3
Object Oriented Programming Through Java UNIT-3
10. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

GATES-CSE(DS|CY) Page 4
Object Oriented Programming Through Java UNIT-3

Subpackage in java :
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has defined a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are
for networking etc and so on. So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

GATES-CSE(DS|CY) Page 5
Object Oriented Programming Through Java UNIT-3
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For

example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where
to look for class file. For example:

GATES-CSE(DS|CY) Page 6
Object Oriented Programming Through Java UNIT-3
e:\sources> java -classpath c:\classes mypack.Simple
Output: Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the
jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files
containing one public class, but keep the package name same. For example:
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

GATES-CSE(DS|CY) Page 7
Object Oriented Programming Through Java UNIT-3
Wrapper Classes
Wrapper classes in Java are used to convert primitive data types into objects. Each of the eight
primitive data types (byte, short, int, long, float, double, char, and boolean) has a corresponding
wrapper class in the java.lang package. These classes provide a way to use primitive data types as
objects, which is useful when working with collections or when an object reference is required.
Here is a list of the primitive types and their corresponding wrapper classes:
1. byte -> Byte
2. short -> Short
3. int -> Integer
4. long -> Long
5. float -> Float
6. double -> Double
7. char -> Character
8. boolean -> Boolean

Key Features of Wrapper Classes


1. Immutability:
o Wrapper class objects are immutable, meaning once they are created, their values
cannot be changed.
2. Methods for Conversion:
o Each wrapper class provides methods to convert between the corresponding
primitive type and the wrapper object.
o Example: Integer.parseInt(String s) converts a string to an int.
3. Utility Methods:
o Wrapper classes provide various utility methods for parsing, converting, comparing,
and working with primitive values.
o Example: Integer.compare(int x, int y) compares two int values.
4. Autoboxing and Unboxing:
o Java automatically converts between primitive types and their corresponding
wrapper class objects (autoboxing) and vice versa (unboxing).
o Example:
Integer obj = 5; // Autoboxing
int value = obj; // Unboxing

Common Methods in Wrapper Classes

GATES-CSE(DS|CY) Page 8
Object Oriented Programming Through Java UNIT-3
• Value Retrieval:
o int intValue(), byte byteValue(), short shortValue(), long longValue(), float
floatValue(), double doubleValue(), char charValue(), boolean booleanValue()
o Example:
Integer obj = 10;
int primitive = obj.intValue();
• String Conversion:
o String toString()
o Example:
Integer obj = 10;
String str = obj.toString(); // "10"
• Parsing Strings:
o static int parseInt(String s), static double parseDouble(String s), etc.
o Example:
int num = Integer.parseInt("123"); // 123
• Comparisons:
o static int compare(int x, int y), boolean equals(Object obj)
o Example:
Integer obj1 = 10;
Integer obj2 = 20;
int result = Integer.compare(obj1, obj2); // -1 (since 10 < 20)

Examples
public class WrapperExample {
public static void main(String[] args) {
// Autoboxing
Integer intObj = 10;
Double doubleObj = 15.5;

// Unboxing
int intValue = intObj;
double doubleValue = doubleObj;

// Using utility methods


String intStr = intObj.toString();

GATES-CSE(DS|CY) Page 9
Object Oriented Programming Through Java UNIT-3
int parsedInt = Integer.parseInt("123");

// Comparison
boolean areEqual = intObj.equals(10);
int comparison = Integer.compare(10, 20);

System.out.println("Integer Object: " + intObj);


System.out.println("Double Object: " + doubleObj);
System.out.println("Primitive int value: " + intValue);
System.out.println("Primitive double value: " + doubleValue);
System.out.println("String representation of Integer: " + intStr);
System.out.println("Parsed int from String: " + parsedInt);
System.out.println("Are Integer object and 10 equal? " + areEqual);
System.out.println("Comparison result between 10 and 20: " + comparison);
}
}
Wrapper classes are essential for using Java's collection framework and for situations where
primitives need to be treated as objects. They also provide many utility methods that simplify coding
tasks related to primitive values.

Java util Classes and Interfaces


The java.util package in Java contains a vast collection of utility classes and interfaces that provide
essential functionalities for data structures, collections, date and time operations, random number
generation, and more.
Formatter Class
The Formatter class in Java is part of the java.util package and is used for creating formatted text.
It provides support for formatting of strings, numbers, dates, and other objects in a similar way to
the printf function in C. The Formatter class can output the formatted text to a variety of destinations
including strings, files, and streams.
Key Features of the Formatter Class
1. Formatting Strings:
o You can use format specifiers to control the formatting of various types of data.
o Common format specifiers include %s for strings, %d for integers, %f for floating-
point numbers, and %t for dates and times.

GATES-CSE(DS|CY) Page 10
Object Oriented Programming Through Java UNIT-3
2. Output Destinations:
o Formatter can output to Appendable objects (like StringBuilder), OutputStream, and
File.
3. Localization:
o Supports localization to format numbers, dates, and text in a locale-specific manner.
Common Format Specifiers
• %s: String
• %d: Decimal integer
• %f: Floating-point number
• %x: Hexadecimal integer
• %o: Octal integer
• %e: Scientific notation
• %c: Character
• %b: Boolean
• %t: Date and time
o %tH: Hour (24-hour clock)
o %tM: Minute
o %tS: Second
o %tY: Year
o %tm: Month
o %td: Day of month
Example Usage
Basic Formatting
import java.util.Formatter;
public class FormatterExample {
public static void main(String[] args) {
Formatter formatter = new Formatter();

// Formatting strings
formatter.format("Name: %s\n", "John Doe");

// Formatting integers
formatter.format("Age: %d\n", 30);

// Formatting floating-point numbers

GATES-CSE(DS|CY) Page 11
Object Oriented Programming Through Java UNIT-3
formatter.format("Balance: %.2f\n", 12345.678);

// Formatting dates
formatter.format("Date: %tY-%tm-%td\n", System.currentTimeMillis(),
System.currentTimeMillis(), System.currentTimeMillis());

System.out.println(formatter);

// Close the formatter to free resources


formatter.close();
}
}

Random Class
The Random class in Java, part of the java.util package, is used to generate pseudo-random numbers.
It can generate random integers, floating-point numbers, booleans, bytes, and can also be used to
generate random values within a specific range.
Key Features of the Random Class
1. Seeded Random Number Generation:
o The Random class can use a seed value to generate a sequence of random numbers.
If the same seed is used, the same sequence of numbers will be generated.
o If no seed is provided, the current time (in milliseconds) is used as the seed.
2. Thread Safety:
o Instances of Random are not thread-safe. If multiple threads need to generate random
numbers, it is recommended to use ThreadLocalRandom or ensure proper
synchronization.
Common Methods
1. Constructors:
o Random(): Creates a new random number generator using a unique seed based on
the current time.
o Random(long seed): Creates a new random number generator using a specified seed.
2. Number Generation Methods:

GATES-CSE(DS|CY) Page 12
Object Oriented Programming Through Java UNIT-3
o int nextInt(): Returns the next random int value.
o int nextInt(int bound): Returns a random int value between 0 (inclusive) and the
specified bound (exclusive).
o long nextLong(): Returns the next random long value.
o boolean nextBoolean(): Returns the next random boolean value.
o float nextFloat(): Returns the next random float value between 0.0 and 1.0.
o double nextDouble(): Returns the next random double value between 0.0 and 1.0.
o void nextBytes(byte[] bytes): Generates random bytes and places them into a user-
supplied byte array.
Example Usage
Basic Random Number Generation
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();

// Generate random integers


int randomInt = random.nextInt();
System.out.println("Random Integer: " + randomInt);

// Generate random integers within a specific range


int randomIntBound = random.nextInt(100); // 0 (inclusive) to 100 (exclusive)
System.out.println("Random Integer [0-99]: " + randomIntBound);

// Generate random long


long randomLong = random.nextLong();
System.out.println("Random Long: " + randomLong);

// Generate random boolean


boolean randomBoolean = random.nextBoolean();
System.out.println("Random Boolean: " + randomBoolean);

// Generate random float


float randomFloat = random.nextFloat();
System.out.println("Random Float: " + randomFloat);

GATES-CSE(DS|CY) Page 13
Object Oriented Programming Through Java UNIT-3

// Generate random double


double randomDouble = random.nextDouble();
System.out.println("Random Double: " + randomDouble);

// Generate random bytes


byte[] randomBytes = new byte[10];
random.nextBytes(randomBytes);
System.out.print("Random Bytes: ");
for (byte b : randomBytes) {
System.out.print(b + " ");
}
}
}

Time Package
The java.time package in Java, introduced in Java 8, provides a comprehensive set of classes for
handling dates, times, and time zones. It addresses many of the deficiencies of the older
java.util.Date and java.util.Calendar classes and provides a much cleaner and more powerful API
for date and time manipulation.
Key Classes and Interfaces in the java.time Package
1. LocalDate: Represents a date (year, month, day) without time and time zone.
2. LocalTime: Represents a time (hour, minute, second, nanosecond) without date and time
zone.
3. LocalDateTime: Represents both date and time without a time zone.
4. ZonedDateTime: Represents date and time with a time zone.
5. OffsetDateTime: Represents date and time with an offset from UTC/Greenwich.
6. Instant: Represents a point in time (timestamp) with nanosecond precision.
7. Duration: Represents a duration of time measured in seconds and nanoseconds.
8. Period: Represents a period of time in years, months, and days.
9. ZoneId: Represents a time zone identifier.
10. ZoneOffset: Represents a time zone offset from UTC.
11. DateTimeFormatter: Used for formatting and parsing date-time objects.
Example Usage
import java.time.LocalDate;

GATES-CSE(DS|CY) Page 14
Object Oriented Programming Through Java UNIT-3
public class LocalDateExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);

LocalDate specificDate = LocalDate.of(2024, 7, 20);


System.out.println("Specific date: " + specificDate);

LocalDate parsedDate = LocalDate.parse("2024-07-20");


System.out.println("Parsed date: " + parsedDate);

LocalDate tomorrow = today.plusDays(1);


System.out.println("Tomorrow's date: " + tomorrow);
}
}

Class Instant
Java Instant class is used to represent the specific moment on the time line. It inherits the Object
class and implements the Comparable interface.
Java Instant Class Declaration
Let's see the declaration of java.time.Instant class.
public final class Instant extends Object
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable
import java.time.Instant;
public class InstantExample1 {
public static void main(String[] args) {
Instant inst = Instant.parse("2017-02-03T10:37:30.00Z");
System.out.println(inst);
}
}

Temporal Adjusters Class


TemporalAdjusters Class in Java provides Adjusters, which are a key tool for modifying temporal
objects. Examples include an adjuster that sets the date like “Second Saturday of the Month” or
“Next Tuesday”, or one that sets the date to the last day of the month.

GATES-CSE(DS|CY) Page 15
Object Oriented Programming Through Java UNIT-3
TemporalAdjuster can be used in two ways. The first is by invoking the method on the interface
directly. The second is by using Temporal.with(TemporalAdjuster):
The following two ways of using TemporalAdjuster are equivalent, but it is recommended to use
the second approach, as it is cleaner and readable
temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);

// Implementation of TemporalAdjuster Class Output will


// be different at the time of execution for different
// days. All the dates in the output will be with respect
// to the current date of executing the program

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class TemporalAdjusterExample {
public static void main(String args[])
{
TemporalAdjusterExample gfg
= new TemporalAdjusterExample();
gfg.testAdjusters();
}
public void testAdjusters()
{
// to get the current date
LocalDate date1 = LocalDate.now();
System.out.println("Today's date is: " + date1);
// to get the next monday
LocalDate nextTuesday = date1.with(
TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday is on : " + nextTuesday);
// to get the second saturday of next month
LocalDate firstInYear = LocalDate.of(
date1.getYear(), date1.getMonth(), 1);

GATES-CSE(DS|CY) Page 16
Object Oriented Programming Through Java UNIT-3
LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(
DayOfWeek.SATURDAY)).with(TemporalAdjusters.next(
DayOfWeek.SATURDAY));
// print date of second Saturday of next month
System.out.println("Second saturday is on : " + secondSaturday);
}
}

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.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest
of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we

GATES-CSE(DS|CY) Page 17
Object Oriented Programming Through Java UNIT-3
perform exception handling, the rest of the statements will be executed. That is why we use
exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

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
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception

GATES-CSE(DS|CY) Page 18
Object Oriented Programming Through Java UNIT-3
The classes that directly inherit the Throwable class except RuntimeException and Error are 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.

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 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

GATES-CSE(DS|CY) Page 19
Object Oriented Programming Through Java UNIT-3
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...");
}
}

Java try 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. So, it is recommended not to keep the code in try block that will not throw an exception.
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{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Internal Working of Java try-catch block

GATES-CSE(DS|CY) Page 20
Object Oriented Programming Through Java UNIT-3

Java Catch Multiple Exceptions


Java 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.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)

GATES-CSE(DS|CY) Page 21
Object Oriented Programming Through Java UNIT-3
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

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.
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block

When an exception does not occur


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 {

GATES-CSE(DS|CY) Page 22
Object Oriented Programming Through Java UNIT-3
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

When an exception occurr but not handled by the catch block


public class TestFinallyBlock1{
public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

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


}
}

When an exception occurs and is handled by the catch block

GATES-CSE(DS|CY) Page 23
Object Oriented Programming Through Java UNIT-3
public class TestFinallyBlock2{
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 occured or not


finally {
System.out.println("finally block is always executed");
}

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


}
}

Java throw keyword


The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc. We
can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to
throw a custom exception.
We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");

GATES-CSE(DS|CY) Page 24
Object Oriented Programming Through Java UNIT-3
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code
before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}

import java.io.IOException;

GATES-CSE(DS|CY) Page 25
Object Oriented Programming Through Java UNIT-3
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Checked Exceptions in Java


These are the exceptions that are checked at compile time. If some code within a method throws a
checked exception, then the method must either handle the exception or it must specify the
exception using the throws keyword. Checked exceptions can be fully checked or partially checked.
• Fully Checked Exception: A checked exception where all its child classes are also checked
(e.g., IOException, InterruptedException).
• Partially Checked Exception: A checked exception where some of its child classes are
unchecked (e.g., Exception).
Checked exceptions represent invalid conditions in areas outside the immediate control of the
program (like memory, network, file system, etc.). Any checked exception is a subclass
of Exception. Unlike unchecked exceptions, checked exceptions must be either caught by the caller
or listed as part of the method signature using the throws keyword.
// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException occurred
// Importing I/O classes
import java.io.*;

GATES-CSE(DS|CY) Page 26
Object Oriented Programming Through Java UNIT-3
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Reading file from path in local directory


FileReader file = new FileReader("C:\\test\\a.txt");

// Creating object as one of ways of taking input


BufferedReader fileInput = new BufferedReader(file);

// Printing first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

// Closing file connections


// using close() method
fileInput.close();
}
}

Unchecked Exceptions in Java


These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked,
so it is not forced by the compiler’s to either handle or specify the exception. It is up to the
programmers to be civilized and specify or catch the exceptions. In Java, exceptions
under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run.
The compiler allows it to compile because ArithmeticException is an unchecked exception.

// Java Program to Illustrate Un-checked Exceptions

// Main class

GATES-CSE(DS|CY) Page 27
Object Oriented Programming Through Java UNIT-3
class GFG {

// Main driver method


public static void main(String args[])
{
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}

Here are some examples of unchecked exceptions in Java:


1. ArrayIndexOutOfBoundsException: This exception is thrown when you attempt to access an
array index that is out of bounds.
2. NullPointerException: This exception is thrown when you attempt to access a null object
reference.
3. ArithmeticException: This exception is thrown when you attempt to divide by zero or perform
an invalid arithmetic operation.

Java I/O and File

The Java I/O API (Input/Output Application Programming Interface) is a fundamental part of Java
programming for handling input and output operations. Here are some key components and
concepts:
1. Streams: Streams are the core abstraction used in Java I/O. They represent sequences of
data. There are two types:
o Byte Streams: Handle I/O of raw binary data (InputStream, OutputStream).
o Character Streams: Handle I/O of character data (Reader, Writer).
2. Byte Streams:
o InputStream and OutputStream: Base classes for all byte stream classes.

GATES-CSE(DS|CY) Page 28
Object Oriented Programming Through Java UNIT-3
o FileInputStream and FileOutputStream: Read from and write to files.
o ByteArrayInputStream and ByteArrayOutputStream: Read from and write to byte
arrays.
o BufferedInputStream and BufferedOutputStream: Provide buffering for improved
performance.
3. Character Streams:
o Reader and Writer: Base classes for all character stream classes.
o FileReader and FileWriter: Read from and write to files using characters.
o BufferedReader and BufferedWriter: Provide buffering for improved performance.
o InputStreamReader and OutputStreamWriter: Bridge between byte streams and
character streams.
4. File I/O:
o File: Represents files and directories on the filesystem.
o FileInputStream, FileOutputStream, FileReader, FileWriter: Classes for reading
from and writing to files.
o RandomAccessFile: Allows reading from and writing to a file with random access.
5. Serialization:
o Serializable interface: Used to mark classes whose objects can be serialized.
o ObjectInputStream and ObjectOutputStream: Used for serializing and deserializing
objects.
6. Other useful classes:
o Scanner: Used for parsing primitive types and strings from input streams.
o PrintStream: Supports formatted output operations to a text output stream.
o Console: Provides access to character-based console device.
Java's I/O API is versatile and provides different classes to handle various I/O operations efficiently

GATES-CSE(DS|CY) Page 29
Object Oriented Programming Through Java UNIT-3

standard I/O streams

In Java, the standard I/O streams are used for interacting with the console, allowing the program to
read input from the user and print output to the screen. These streams are predefined in the System
class:
1. Standard Input (System.in):
o Used to read input from the console.
o It is an instance of InputStream.
o Commonly wrapped with Scanner or BufferedReader for easier handling.

import java.util.Scanner;

public class StandardInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");

GATES-CSE(DS|CY) Page 30
Object Oriented Programming Through Java UNIT-3
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

Standard Output (System.out):


• Used to print output to the console.
• It is an instance of PrintStream.
• Provides methods like print(), println(), and printf() for formatted output

public class StandardOutputExample {


public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.print("Hello, ");
System.out.print("World!");
System.out.printf("Number: %d%n", 10);
}
}

Standard Error (System.err):


• Used to print error messages to the console.
• It is also an instance of PrintStream.
• Useful for separating regular output from error messages.

public class StandardErrorExample {


public static void main(String[] args) {
System.err.println("This is an error message.");
}
}

Byte Streams

Byte streams in Java are used for reading and writing binary data. They handle raw bytes, making
them suitable for processing any kind of I/O, including binary files and streams. Byte streams are
part of the java.io package. Here's a closer look at the key classes and their usage:

GATES-CSE(DS|CY) Page 31
Object Oriented Programming Through Java UNIT-3

Key Classes
1. InputStream: The abstract base class for all byte input streams. It defines methods like
read(), read(byte[] b), and close().
o FileInputStream: Reads bytes from a file.

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("example.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData); // Print each byte as a character
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

ByteArrayInputStream: Reads bytes from a byte array.


import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInputStreamExample {


public static void main(String[] args) {
byte[] data = "Hello, World!".getBytes();
try (ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
int byteData;
while ((byteData = bais.read()) != -1) {
System.out.print((char) byteData); // Print each byte as a character
}
} catch (IOException e) {

GATES-CSE(DS|CY) Page 32
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}

OutputStream: The abstract base class for all byte output streams. It defines methods like write(int
b), write(byte[] b), and flush().
• FileOutputStream: Writes bytes to a file.

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String data = "Hello, World!";
fos.write(data.getBytes()); // Write data to file
} catch (IOException e) {
e.printStackTrace();
}
}
}

ByteArrayOutputStream: Writes bytes to a byte array.

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamExample {


public static void main(String[] args) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
String data = "Hello, World!";
baos.write(data.getBytes()); // Write data to byte array
System.out.println(baos.toString()); // Convert byte array to string and print
} catch (IOException e) {

GATES-CSE(DS|CY) Page 33
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}

Buffered Streams:
• BufferedInputStream: Provides buffering for input streams to improve performance.
• BufferedOutputStream: Provides buffering for output streams to improve performance.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class BufferedInputStreamExample {


public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("example.txt"))) {
int byteData;
while ((byteData = bis.read()) != -1) {
System.out.print((char) byteData); // Print each byte as a character
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamExample {


public static void main(String[] args) {
try (BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("output.txt"))) {
String data = "Hello, World!";

GATES-CSE(DS|CY) Page 34
Object Oriented Programming Through Java UNIT-3
bos.write(data.getBytes()); // Write data to file
} catch (IOException e) {
e.printStackTrace();
}
}
}

Byte streams are ideal for handling binary data and are a fundamental part of Java's I/O system.
They are versatile and can be used to read from and write to files, byte arrays, and other byte-based
sources and destinations.

Character streams

Character streams in Java are designed to handle the reading and writing of data as characters. They
are built on top of byte streams but provide a more convenient way to process text data by handling
character encoding and decoding automatically. Character streams are part of the java.io package
and are designed to work with Unicode characters, making them suitable for internationalization.

Key Classes
1. Reader: The abstract base class for all character input streams. It defines methods like read(),
read(char[] cbuf), and close().
o FileReader: Reads characters from a file.

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args) {
try (FileReader fr = new FileReader("example.txt")) {
int charData;
while ((charData = fr.read()) != -1) {
System.out.print((char) charData); // Print each character
}
} catch (IOException e) {

GATES-CSE(DS|CY) Page 35
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}

StringReader: Reads characters from a String.

import java.io.StringReader;
import java.io.IOException;

public class StringReaderExample {


public static void main(String[] args) {
String data = "Hello, World!";
try (StringReader sr = new StringReader(data)) {
int charData;
while ((charData = sr.read()) != -1) {
System.out.print((char) charData); // Print each character
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Writer: The abstract base class for all character output streams. It defines methods like write(int c),
write(char[] cbuf), and flush().
• FileWriter: Writes characters to a file.
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {


public static void main(String[] args) {
try (FileWriter fw = new FileWriter("output.txt")) {
String data = "Hello, World!";
fw.write(data); // Write characters to file

GATES-CSE(DS|CY) Page 36
Object Oriented Programming Through Java UNIT-3
} catch (IOException e) {
e.printStackTrace();
}
}
}

StringWriter: Writes characters to a StringBuilder.


import java.io.StringWriter;
import java.io.IOException;

public class StringWriterExample {


public static void main(String[] args) {
try (StringWriter sw = new StringWriter()) {
String data = "Hello, World!";
sw.write(data); // Write characters to StringWriter
System.out.println(sw.toString()); // Convert to string and print
} catch (IOException e) {
e.printStackTrace();
}
}
}

Buffered Character Streams:


• BufferedReader: Buffers the input from a Reader to improve efficiency. It provides
methods like readLine() to read text lines.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line); // Print each line

GATES-CSE(DS|CY) Page 37
Object Oriented Programming Through Java UNIT-3
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

BufferedWriter: Buffers the output to a Writer to improve efficiency.


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String data = "Hello, World!";
bw.write(data); // Write characters to file
} catch (IOException e) {
e.printStackTrace();
}
}
}

Other Useful Classes:


• PrintWriter: Provides convenient methods for formatted output, and can be used with both
file and console output.
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class PrintWriterExample {


public static void main(String[] args) {
try (PrintWriter pw = new PrintWriter(new FileWriter("output.txt"))) {

GATES-CSE(DS|CY) Page 38
Object Oriented Programming Through Java UNIT-3
pw.println("Hello, World!"); // Print formatted output to file
} catch (IOException e) {
e.printStackTrace();
}
}
}

Character streams are designed for handling text data in a more human-readable form compared to
byte streams. They provide better support for character encoding and decoding, making them
suitable for reading from and writing to text files, processing strings, and handling internationalized
text.

Scanner Class

The Scanner class in Java, part of the java.util package, is used for parsing and reading input from
various sources, including keyboard input, files, and strings. It provides a convenient way to parse
primitive types and strings using regular expressions.

Key Features
• Versatile Input Sources: Can read from various sources such as InputStream, File, String,
and Readable.
• Parsing Methods: Provides methods to read and parse different data types like int, double,
boolean, etc.
• Delimiter Support: Supports custom delimiters and regular expressions for splitting input
data.
• Exception Handling: Handles input errors gracefully and can throw exceptions for invalid
input.
Commonly Used Constructors
1. From InputStream (e.g., System.in):

import java.util.Scanner;

public class ScannerExample {

GATES-CSE(DS|CY) Page 39
Object Oriented Programming Through Java UNIT-3
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}

From File:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileScannerExample {


public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("example.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

File Handling: In Java, working with files is a common task, and there are several classes and
methods available to handle file operations, ranging from basic file handling to more advanced
functionalities. Here's an overview of how to work with files in Java:
Basic File Operations
1. Creating a File Object

GATES-CSE(DS|CY) Page 40
Object Oriented Programming Through Java UNIT-3
o Use the File class from the java.io package to create a file object.
2. Creating and Deleting Files
3. Check File Properties
4. Reading and Writing Files

import java.io.File;

public class FileInfoExample {


public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());
System.out.println("File size in bytes: " + file.length());
} else {
System.out.println("File does not exist.");
}
}
}

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args) {
try (FileReader fr = new FileReader("example.txt")) {
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();

GATES-CSE(DS|CY) Page 41
Object Oriented Programming Through Java UNIT-3
}
}
}

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {


public static void main(String[] args) {
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

GATES-CSE(DS|CY) Page 42

You might also like