0% found this document useful (0 votes)
8 views90 pages

r23 Java Unit4 Ay 2024 25

The document outlines the syllabus for Unit 4 of the Object Oriented Programming course, focusing on Java packages, exceptions, and I/O operations. It covers the definition and advantages of Java packages, methods for importing and accessing packages, and details on exception handling and the Java I/O API. Additionally, it provides examples and explanations of various classes in the java.lang package and the concept of enumerations in Java.

Uploaded by

indhu.breddy
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)
8 views90 pages

r23 Java Unit4 Ay 2024 25

The document outlines the syllabus for Unit 4 of the Object Oriented Programming course, focusing on Java packages, exceptions, and I/O operations. It covers the definition and advantages of Java packages, methods for importing and accessing packages, and details on exception handling and the Java I/O API. Additionally, it provides examples and explanations of various classes in the java.lang package and the concept of enumerations in Java.

Uploaded by

indhu.breddy
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/ 90

ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET

AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Syllabus : Unit-4
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 Autounboxing, 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(Text Book 2)
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.
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.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
Collected & Prepared By: T. N.RANGANADHAM Page 1 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
Syntax: javac -d directory javafilename

For example
javac -d . Simple.java
How to run java package program
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package

How to access package from another package?


There are three ways to access the package from outside the package.
 import package.*;
 import package.classname;
 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.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
Collected & Prepared By: T. N.RANGANADHAM Page 2 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.

Collected & Prepared By: T. N.RANGANADHAM Page 3 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

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:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
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:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package

Collected & Prepared By: T. N.RANGANADHAM Page 4 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.
Temporary
By setting the classpath in the command prompt
By -classpath switch
Permanent
By setting the classpath in the environment variables
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.
//save as C.java otherwise Compilte Time Error

class A{}
class B{}
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:
//save as A.java

package javatpoint;
public class A{}
//save as B.java

package javatpoint;
public class B{}

Java.lang package in Java


Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at run time.

Following are the Important Classes in Java.lang package :

Boolean: The Boolean class wraps a value of the primitive type boolean in an object.
Byte: The Byte class wraps a value of primitive type byte in an object.
Character – Set 1, Set 2: The Character class wraps a value of the primitive type char in an object.
Character.Subset: Instances of this class represent particular subsets of the Unicode character set.
Collected & Prepared By: T. N.RANGANADHAM Page 5 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Character.UnicodeBlock: A family of character subsets representing the character blocks in the Unicode
specification.
Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces in a running Java
application.
ClassLoader: A class loader is an object that is responsible for loading classes.
ClassValue: Lazily associate a computed value with (potentially) every type.
Compiler: The Compiler class is provided to support Java-to-native-code compilers and related services.
Double: The Double class wraps a value of the primitive type double in an object.
Enum: This is the common base class of all Java language enumeration types.
Float: The Float class wraps a value of primitive type float in an object.
InheritableThreadLocal: This class extends ThreadLocal to provide inheritance of values from parent
thread to child thread: when a child thread is created, the child receives initial values for all inheritable
thread-local variables for which the parent has values.
Integer :The Integer class wraps a value of the primitive type int in an object.
Long: The Long class wraps a value of the primitive type long in an object.
Math – Set 1, Set 2: The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root, and trigonometric functions.
Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double,
Float, Integer, Long, and Short.
Object: Class Object is the root of the class hierarchy.
Package: Package objects contain version information about the implementation and specification of a
Java package.
Process: The ProcessBuilder.start() and Runtime.exec methods create a native process and return an
instance of a subclass of Process that can be used to control the process and obtain information about
it.
ProcessBuilder: This class is used to create operating system processes.
ProcessBuilder.Redirect: Represents a source of subprocess input or a destination of subprocess output.
Runtime: Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
RuntimePermission: This class is for runtime permissions.
SecurityManager: The security manager is a class that allows applications to implement a security
policy.
Short: The Short class wraps a value of primitive type short in an object.
StackTraceElement: An element in a stack trace, as returned by Throwable.getStackTrace().
StrictMath- Set1, Set2: The class StrictMath contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric functions.

Collected & Prepared By: T. N.RANGANADHAM Page 6 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

String- Set1, Set2: The String class represents character strings.


StringBuffer: A thread-safe, mutable sequence of characters.
StringBuilder: A mutable sequence of characters.
System: The System class contains several useful class fields and methods.
Thread: A thread is a thread of execution in a program.
ThreadGroup: A thread group represents a set of threads.
ThreadLocal: This class provides thread-local variables.
Throwable: The Throwable class is the superclass of all errors and exceptions in the Java language.
Void: The Void class is an uninstantiable placeholder class to hold a reference to the Class object
representing the Java keyword void.

What is Enumeration or Enum in Java?


A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the
same capabilities as other classes. This fact makes Java enumeration a very powerful tool.
1. Declaration outside the class
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
RED,
GREEN,
BLUE;
}

public class Test {


// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output
RED
2. Declaration inside a class

Collected & Prepared By: T. N.RANGANADHAM Page 7 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// enum declaration inside a class.


public class Test {
enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output
RED
Properties of Enum in Java
There are certain properties followed by Enum as mentioned below:
Class Type: Every enum is internally implemented using the Class type.
Enum Constants: Each enum constant represents an object of type enum.
Switch Statements: Enum types can be used in switch statements.
Implicit Modifiers: Every enum constant is implicitly public static final. Since it is static, it can be
accessed using the enum name. Since it is final, enums cannot be extended.
Main Method: Enums can declare a main() method, allowing direct invocation from the command line.
Below is the implementation of the above properties:
// A Java program to demonstrate working on enum
// in a switch case (Filename Test.java)

import java.util.Scanner;

// An Enum class
enum Day {
SUNDAY,
MONDAY,
Collected & Prepared By: T. N.RANGANADHAM Page 8 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}

// Driver class that contains an object of "day" and


// main().
public class Test {
Day day;

// Constructor
public Test(Day day) {
this.day = day;
}

// Prints a line about Day using switch


public void dayIsLike() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;

Collected & Prepared By: T. N.RANGANADHAM Page 9 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
}

// Driver method
public static void main(String[] args) {
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
Output
Mondays are bad.

Java Math Class


Java.lang.Math Class methods help to perform numeric operations like square, square root, cube, cube
root, exponential and trigonometric operations.

Declaration
public final class Math
extends Object
Methods of Math Class in Java
Math class consists of methods that can perform mathematical operations and can make long
calculations a bit easier. Let us check the method provided in the Math class.
Method Description
sin Returns the trigonometric value of the sine of an angle.
cos Returns the trigonometric value of the cosine of an angle.
tan Returns the trigonometric value of the tangent of an angle.
asin Returns the trigonometric value of the arc sine of an angle.
acos Returns the trigonometric value of the arc cosine of an angle.
atan Returns the trigonometric value of the arc tangent of an angle.
toRadians Convert value in degrees to value in radians
toDegrees Convert value in radians to value in degrees
exp Returns Euler’s number e raised to the power of a double value
log Returns the natural logarithm (base e) of a double value
log10 Returns the base 10 logarithms of a double value

Collected & Prepared By: T. N.RANGANADHAM Page 10 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// Java program to demonstrate the


// Use of Math Class
public class MathLibraryExample {
public static void main(String[] args) {
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;

System.out.println("i is " + i);


System.out.println("j is " + j);

// The absolute value of a number is equal to the


// number if the number is positive or zero and
// equal to the negative of the number if the number
// is negative.

System.out.println("|" + i + "| is " + Math.abs(i));


System.out.println("|" + j + "| is " + Math.abs(j));

// Truncating and Rounding functions


// You can round off a floating point number to the
// nearest integer with round()
System.out.println(x + " is approximately " + Math.round(x));
System.out.println(y + " is approximately " + Math.round(y));

// The "ceiling" of a number is the smallest integer


// greater than or equal to the number. Every
// integer is its own ceiling.
System.out.println("The ceiling of " + x + " is " + Math.ceil(x));
System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

Collected & Prepared By: T. N.RANGANADHAM Page 11 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// The "floor" of a number is the largest integer


// less than or equal to the number. Every integer
// is its own floor.
System.out.println("The floor of " + x + " is " + Math.floor(x));
System.out.println("The floor of " + y + " is " + Math.floor(y));

// Comparison operators

// min() returns the smaller of the two arguments


// you pass it
System.out.println("min(" + i + "," + j + ") is " + Math.min(i, j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x, y));

// There's a corresponding max() method


// that returns the larger of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i, j));
System.out.println("max(" + x + "," + y + ") is " + Math.max(x, y));

// The Math library defines a couple of useful


// constants:
System.out.println("Pi is " + Math.PI);
System.out.println("e is " + Math.E);

// Trigonometric methods. All arguments are given in


// radians
// Convert a 45 degree angle to radians
double angle = 45.0 * 2.0 * Math.PI / 360.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));

// Inverse Trigonometric methods. All values are


// returned as radians
double value = 0.707;

Collected & Prepared By: T. N.RANGANADHAM Page 12 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

System.out.println("acos(" + value + ") is " + Math.acos(value));


System.out.println("asin(" + value + ") is " + Math.asin(value));
System.out.println("atan(" + value + ") is " + Math.atan(value));

// Exponential and Logarithmic Methods


// exp(a) returns e (2.71828...) raised
// to the power of a.
System.out.println("exp(1.0) is " + Math.exp(1.0));
System.out.println("exp(10.0) is " + Math.exp(10.0));
System.out.println("exp(0.0) is " + Math.exp(0.0));

// log(a) returns the natural


// logarithm (base e) of a.
System.out.println("log(1.0) is " + Math.log(1.0));
System.out.println("log(10.0) is " + Math.log(10.0));
System.out.println("log(Math.E) is " + Math.log(Math.E));

// pow(x, y) returns x raised to the power of y.


System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0, 2.0));
System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0, 3.5));
System.out.println("pow(8, -1) is " + Math.pow(8, -1));

// sqrt(x) returns the square root of x.


for (i = 0; i < 10; i++) {
System.out.println("The square root of " + i + " is " + Math.sqrt(i));
}

// Finally there's one Random method


// that returns a pseudo-random number
// between 0.0 and 1.0;
System.out.println("Here's one random number: " + Math.random());
System.out.println("Here's another random number: " + Math.random());
}

Collected & Prepared By: T. N.RANGANADHAM Page 13 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
Output
i is 7
j is -9
|7| is 7
|-9| is 9
72.3 is approximately 72
0.34 is approximately 0
The ceiling of 72.3 is 73.0
The ceiling of 0.34 is 1.0
The floor of 72.3 is 72.0
The floor of 0.34 is 0.0
min(7,-9) i...

Wrapper Classes in Java


A Wrapper class in Java is a class whose object wraps or contains primitive data types. When we create
an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In
other words, we can wrap a primitive value into a wrapper class object.
Advantages of Wrapper Classes
 Collections allowed only object data.
 On object data we can call multiple methods compareTo(), equals(), toString()
 Cloning process only objects
 Object data allowed null values.
 Serialization can allow only object data.

Primitive Data Type Wrapper Class


char Character
Byte Byte
Short Short
int Integer
Long Long
Float Float
Double Double
boolean Boolean

Collected & Prepared By: T. N.RANGANADHAM Page 14 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Autoboxing and Unboxing


1. Autoboxing
The automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing {
public static void main(String[] args)
{ char ch = 'a';
// Autoboxing- primitive to Character object
// conversion
Character a = ch;
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
// Autoboxing because ArrayList stores only objects
arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
Output
25
2. Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its
corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double, etc.
// Java program to demonstrate Unboxing
import java.util.ArrayList;

class Unboxing {
public static void main(String[] args)
{
Character ch = 'a';

Collected & Prepared By: T. N.RANGANADHAM Page 15 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// unboxing - Character object to primitive


// conversion
char a = ch;
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);

// unboxing because get method returns an Integer


// object
int num = arrayList.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
Output
24
Java Wrapper Classes Example
// Java program to demonstrate Wrapping and UnWrapping
// in Classes
import java.io.*;

class GFG {
public static void main(String[] args)
{
// byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);
// Use with Java 9
// Byte byteobj = Byte.valueOf(a);
// int data type
int b = 10;

Collected & Prepared By: T. N.RANGANADHAM Page 16 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// wrapping around Integer object


Integer intobj = new Integer(b);
// Use with Java 9
// Integer intobj = Integer.valueOf(b);

// float data type


float c = 18.6f;

// wrapping around Float object


Float floatobj = new Float(c);
// Use with Java 9
// Float floatobj = Float.valueOf(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);
// Use with Java 9
// Double doubleobj = Double.valueOf(d);

// char data type


char e = 'a';

// wrapping around Character object


Character charobj = e;

// printing the values from objects


System.out.println(
"Values of Wrapper objects (printing as objects)");
System.out.println("\nByte object byteobj: "
+ byteobj);
System.out.println("\nInteger object intobj: "

Collected & Prepared By: T. N.RANGANADHAM Page 17 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

+ intobj);
System.out.println("\nFloat object floatobj: "
+ floatobj);
System.out.println("\nDouble object doubleobj: "
+ doubleobj);
System.out.println("\nCharacter object charobj: "
+ charobj);

// objects to data types (retrieving data types from


// objects) unwrapping objects to primitive data
// types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


System.out.println(
"\nUnwrapped values (printing as data types)");
System.out.println("\nbyte value, bv: " + bv);
System.out.println("\nint value, iv: " + iv);
System.out.println("\nfloat value, fv: " + fv);
System.out.println("\ndouble value, dv: " + dv);
System.out.println("\nchar value, cv: " + cv);
}
}
Output
Values of Wrapper objects (printing as objects)
Byte object byteobj: 1
Integer object intobj: 10
Float object floatobj: 18.6
Double object doubleobj: 250.5
Character object charobj: a
Unwrapped values (printing as data types)
byte value, bv: 1
Collected & Prepared By: T. N.RANGANADHAM Page 18 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

int value, iv: 10


float value, fv: 18.6
double value, dv: 250.5
char value, cv: a
Custom Wrapper Classes in Java
Java Wrapper classes wrap the primitive data types. We can create a class that wraps data inside it. So
let us check how to create our own custom wrapper class in Java. It can be implemented for creating
certain structures like queues, stacks, etc.
// Java Program to implement
// Custom wrapper class
import java.io.*;

// wrapper class
class Maximum {
private int maxi = 0;
private int size = 0;

public void insert(int x)


{
this.size++;
if (x <= this.maxi)
return;
this.maxi = x;
}
public int top() { return this.maxi; }
public int elementNumber() { return this.size; }
};

//
class GFG {
public static void main(String[] args)
{
Maximum x = new Maximum();
x.insert(12);
x.insert(3);
Collected & Prepared By: T. N.RANGANADHAM Page 19 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

x.insert(23);

System.out.println("Maximum element: " + x.top());


System.out.println("Number of elements inserted: "
+ x.elementNumber());
}
}
Output
Maximum element: 23
Number of elements inserted: 3
java.util Package in Java
The java.util package in Java is a built-in package that contains various utility classes and interfaces. It
provides basic functionality for commonly occurring use cases. It contains Java's collections framework,
date and time utilities, string-tokenizer, event-model utilities, etc.

These components and their usage in Java:


Data Structure Classes: The java.util package contains several pre-written data structures like
Dictionary, Stack, LinkedList, etc. that can be used directly in the program using the import statements.
Date and Time Facility: The java.util package provides several date and time-related classes that can be
used to create and manipulate date and time values in a program.
Enumeration: It provides a special interface known as enumeration(enum for short) that can be used to
iterate through a set of values.
Exceptions: It provides classes to handle commonly occurring exceptions in a Java program.
Miscellaneous Utility Classes: The java.util package contains essential utilities such as the string
tokenizer and random-number generator.

Collected & Prepared By: T. N.RANGANADHAM Page 20 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

java.util Package Classes


Class Description
Collections Provides methods to represent and manage collections
Formatter An interpreter for format strings
Scanner Text scanner used to take user inputs
Arrays Provides methods for array manipulation
LinkedList Implements Doubly-linked list data structure
HashMap Implements Map data structure using Hash tables
TreeMap Implements Red-Black tree data structure
Stack Implements last-in-first-out (LIFO) data structure
PriorityQueue Implements unbounded priority queue data structure
Date Represents a specific instance of time
Calendar Provides methods to manipulate calendar fields
Random Used to generate a stream of pseudorandom numbers.
StringTokenizer Used to break a string into tokens
Timer, TimerTask Used by threads to schedule tasks
UUID Represents an immutable universally unique identifier

java.util Package Interfaces


Interface Description
Collections Root interface for the Collections API
Comparator Provides sorting logic
Deque Implements Deque data structure
Enumeration Produces enumeration objects
Iterator Provides iteration logic
List Implements an ordered collection (Sequence)
Map Implements Map data structure (key-value pairs)
Queue Implements Queue data structure
Set Produces a collection that contains no duplicate elements
SortedSet Produces a set that remembers the total ordering

Java Formatter Class


The Java Formatter class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output. Following are the important points
about Formatter −
Formatters are not necessarily safe for multithreaded access. Thread safety is optional and is the
responsibility of users of methods in this class.

Collected & Prepared By: T. N.RANGANADHAM Page 21 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Class declaration
public final class Formatter
extends Object
implements Closeable, Flushable

Some of the Class constructors


Sr.No. Constructor & Description

Formatter()
1
This constructor constructs a new formatter.

Formatter(Appendable a)
2
This constructor constructs a new formatter with the specified destination.

Formatter(Appendable a, Locale l)
3 This constructor constructs a new formatter with the specified destination
and locale.

Formatter(File file)
4
This constructor constructs a new formatter with the specified file.

Formatter(File file, String csn)


5 This constructor constructs a new formatter with the specified file and
charset.

Formatter(File file, String csn, Locale l)


6 This constructor constructs a new formatter with the specified file, charset,
and locale.

Formatter(File file, Charset charset, Locale l)


7 This constructor constructs a new formatter with the specified file, charset,
and locale..

Formatter(Locale l)
8
This constructor constructs a new formatter with the specified locale.

Formatter(OutputStream os)
9 This constructor constructs a new formatter with the specified output
stream.

Formatter(OutputStream os, String csn)


10
This constructor constructs a new formatter with the specified output stream

Collected & Prepared By: T. N.RANGANADHAM Page 22 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

and charset.

Formatter(OutputStream os, String csn, Locale l)


11 This constructor constructs a new formatter with the specified output
stream, charset, and locale.

Formatter(OutputStream os, Charset charset, Locale l)


12 This constructor constructs a new formatter with the specified output
stream, charset, and locale.

Formatter(PrintStream ps)
13
This constructor constructs a new formatter with the specified print stream.

Formatter(String fileName)
14
This constructor constructs a new formatter with the specified file name.

Formatter(String fileName, String csn)


15 This constructor constructs a new formatter with the specified file name and
charset.

Formatter(String fileName, Charset charset, Locale l) This constructor constructs a new


16
formatter with the specified file name, charset, and locale.

Formatter(String fileName, String csn, Locale l)


17 This constructor constructs a new formatter with the specified file name,
charset, and locale.

Class methods
Sr.No. Method & Description

void close()
1
This method closes this formatter.

void flush()
2
This method flushes this formatter.

Formatter format(Locale l, String format, Object... args)


3 This method writes a formatted string to this object's destination using the
specified locale, format string, and arguments.

Formatter format(String format, Object... args)


4
This method writes a formatted string to this object's destination using the

Collected & Prepared By: T. N.RANGANADHAM Page 23 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

specified format string and arguments.

IOException ioException()
5 This method returns the IOException last thrown by this formatter's
Appendable.

Locale locale()
6
This method returns the locale set by the construction of this formatter.

Appendable out()
7
This method returns the destination for the output.

String toString()
8 This method returns the result of invoking toString() on the destination for
the output.

Formatting a String using US Locale Example


The following example shows the usage of Java Formatter format(String, Object) method to format a
string using a formatter. We've created a formatter object with a StringBuffer and a locale. Formatter is
used to print a string using the format() method.
package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {


public static void main(String[] args) {

// create a new formatter


StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);

// format a new string


String name = "World";
formatter.format("Hello %s !", name);

// print the formatted string


System.out.println(formatter);

Collected & Prepared By: T. N.RANGANADHAM Page 24 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

formatter.close();
}
}
Output
Hello World !

Java Random Class


The Java Random class instance is used to generate a stream of pseudorandom numbers.Following are
the important points about Random −

The class uses a 48-bit seed, which is modified using a linear congruential formula.

The algorithms implemented by class Random use a protected utility method that on each invocation
can supply up to 32 pseudorandomly generated bits.
Class declaration
public class Random
extends Object
implements Serializable

Class constructors
Sr.No. Constructor & Description

Random()
1
This creates a new random number generator.

Random(long seed)
2
This creates a new random number generator using a single long seed.

Class methods
Sr.No. Method & Description

DoubleStream doubles()
1 Returns an effectively unlimited stream of pseudorandom double values,
each between zero (inclusive) and one (exclusive).

Collected & Prepared By: T. N.RANGANADHAM Page 25 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

IntStream ints()
2
Returns an effectively unlimited stream of pseudorandom int values.

LongStream longs()
3
Returns an effectively unlimited stream of pseudorandom long values.

boolean nextBoolean()
4 This method returns the next pseudorandom, uniformly distributed boolean
value from this random number generator's sequence.

void nextBytes(byte[] bytes)


5 This method generates random bytes and places them into a user-supplied
byte array.

double nextDouble()
6 This method returns the next pseudorandom, uniformly distributed double
value between 0.0 and 1.0 from this random number generator's sequence.

float nextFloat()
7 This method returns the next pseudorandom, uniformly distributed float
value between 0.0 and 1.0 from this random number generator's sequence.

double nextGaussian()
This method returns the next pseudorandom, Gaussian ("normally")
8
distributed double value with mean 0.0 and standard deviation 1.0 from this
random number generator's sequence.

int nextInt()
9 This method returns the next pseudorandom, uniformly distributed int value
from this random number generator's sequence.

long nextLong()
10 This method returns the next pseudorandom, uniformly distributed long
value from this random number generator's sequence.

void setSeed(long seed)


11 This method sets the seed of this random number generator using a single
long seed.

Getting a Random Double Number Example


The following example shows the usage of Java Random doubles() method. Firstly, we've created a
Random object and then using doubles() we retrieved a stream of random double values and printed
first value.

Collected & Prepared By: T. N.RANGANADHAM Page 26 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

package com.tutorialspoint;

import java.util.Random;
import java.util.stream.DoubleStream;

public class RandomDemo {


public static void main( String args[] ) {

// create random object


DoubleStream randomNoStream = new Random().doubles();
// print a random double value
randomNoStream.limit(1).forEach( i -> System.out.println(i));
}
}
Output
0.5129590222446587

Java date time package


There have been several problems with the existing date and time related classes in java, some of them
are:

Java Date Time classes are not defined consistently, we have Date Class in both java.util as well as
java.sql packages. Again formatting and parsing classes are defined in java.text package.
java.util.Date contains both date and time values whereas java.sql.Date contains only date value. Having
this in java.sql package doesn’t make any sense. Also, both the classes have the same name, which is a
very bad design itself.
There are no clearly defined classes for time, timestamp, formatting, and parsing. We have
java.text.DateFormat abstract class for parsing and formatting need. Usually, the SimpleDateFormat
class is used for parsing and formatting.
All the Date classes are mutable, so they are not thread-safe. It’s one of the biggest problems with Java
Date and Calendar classes.
Date class doesn’t provide internationalization, there is no timezone support. So java.util.Calendar and
java.util.TimeZone classes were introduced, but they also have all the problems listed above.
Date Time API Packages

Collected & Prepared By: T. N.RANGANADHAM Page 27 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Java 8 Date Time API consists of following packages.

java.time: This is the base package of the new Java Date Time API. All the major base classes are part of
this package, such as LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration, etc. All of these
classes are immutable and thread-safe. Most of the time, these classes will be sufficient for handling
common requirements.
java.time.chrono: This package defines generic APIs for non-ISO calendar systems. We can extend
AbstractChronology class to create our own calendar system.
java.time.format: This package contains classes used for formatting and parsing date-time objects. Most
of the time we would not be directly using them because of principle classes in java.time package
provides formatting and parsing methods.
java.time.temporal: This package contains temporal objects and we can use it to find out the specific
dates or times related to the date/time objects. For example, we can use these to find out the first or
last day of the month. You can identify these methods easily because they always have the format
“withXXX”.
java.time.zone Package: This package contains classes for supporting different time zones and their
rules.

Java 8 Date Time API Classes Examples


1. LocalDate
LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use
now() method to get the current date. We can also provide input arguments for year, month and date to
create LocalDate instance.
package com.aits.java8.time;

import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;

public class LocalDateExample {

public static void main(String[] args) {

//Current Date
LocalDate today = LocalDate.now();
System.out.println("Current Date="+today);

Collected & Prepared By: T. N.RANGANADHAM Page 28 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

//Creating LocalDate by providing input arguments


LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1);
System.out.println("Specific Date="+firstDay_2014);

//Try creating date by providing invalid inputs


//LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
//Exception in thread "main" java.time.DateTimeException:
//Invalid date 'February 29' as '2014' is not a leap year

//Current date in "Asia/Kolkata", you can get it from ZoneId javadoc


LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Current Date in IST="+todayKolkata);

//java.time.zone.ZoneRulesException: Unknown time-zone ID: IST


//LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));

//Getting date from the base date i.e 01/01/1970


LocalDate dateFromBase = LocalDate.ofEpochDay(365);
System.out.println("365th day from base date= "+dateFromBase);

LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100);


System.out.println("100th day of 2014="+hundredDay2014);
}

Output:
Current Date=2014-04-28
Specific Date=2014-01-01
Current Date in IST=2014-04-29
365th day from base date= 1971-01-01

Collected & Prepared By: T. N.RANGANADHAM Page 29 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

100th day of 2014=2014-04-10

2. LocalTime
LocalTime is an immutable class whose instance represents a time in the human readable format. It’s
default format is hh:mm:ss.zzz. Just like LocalDate, this class provides time zone support and creating
instance by passing hour, minute and second as input arguments.

package com.journaldev.java8.time;

import java.time.LocalTime;
import java.time.ZoneId;

/**
* LocalTime Examples
* @author pankaj
*
*/
public class LocalTimeExample {

public static void main(String[] args) {

//Current Time
LocalTime time = LocalTime.now();
System.out.println("Current Time="+time);

//Creating LocalTime by providing input arguments


LocalTime specificTime = LocalTime.of(12,20,25,40);
System.out.println("Specific Time of Day="+specificTime);

//Try creating time by providing invalid inputs


//LocalTime invalidTime = LocalTime.of(25,20);
//Exception in thread "main" java.time.DateTimeException:
//Invalid value for HourOfDay (valid values 0 - 23): 25
Collected & Prepared By: T. N.RANGANADHAM Page 30 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

//Current date in "Asia/Kolkata", you can get it from ZoneId javadoc


LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Current Time in IST="+timeKolkata);

//java.time.zone.ZoneRulesException: Unknown time-zone ID: IST


//LocalTime todayIST = LocalTime.now(ZoneId.of("IST"));

//Getting date from the base date i.e 01/01/1970


LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
System.out.println("10000th second time= "+specificSecondTime);

}
Output:
Current Time=15:51:45.240
Specific Time of Day=12:20:25.000000040
Current Time in IST=04:21:45.276
10000th second time= 02:46:40
3. LocalDateTime
LocalDateTime is an immutable date-time object that represents a date-time with default format as
yyyy-MM-dd-HH-mm-ss.zzz. It provides a factory method that takes LocalDate and LocalTime input
arguments to create LocalDateTime instance.
package com.journaldev.java8.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class LocalDateTimeExample {


Collected & Prepared By: T. N.RANGANADHAM Page 31 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

public static void main(String[] args) {

//Current Date
LocalDateTime today = LocalDateTime.now();
System.out.println("Current DateTime="+today);

//Current Date using LocalDate and LocalTime


today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Current DateTime="+today);

//Creating LocalDateTime by providing input arguments


LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
System.out.println("Specific Date="+specificDate);

//Try creating date by providing invalid inputs


//LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1);
//Exception in thread "main" java.time.DateTimeException:
//Invalid value for HourOfDay (valid values 0 - 23): 25

//Current date in "Asia/Kolkata", you can get it from ZoneId javadoc


LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Current Date in IST="+todayKolkata);

//java.time.zone.ZoneRulesException: Unknown time-zone ID: IST


//LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

//Getting date from the base date i.e 01/01/1970


LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0,
ZoneOffset.UTC);
System.out.println("10000th second time from 01/01/1970= "+dateFromBase);

Collected & Prepared By: T. N.RANGANADHAM Page 32 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
Output:
Current DateTime=2014-04-28T16:00:49.455
Current DateTime=2014-04-28T16:00:49.493
Specific Date=2014-01-01T10:10:30
Current Date in IST=2014-04-29T04:30:49.493
10000th second time from 01/01/1970= 1970-01-01T02:46:40
4. Instant
Instant class is used to work with machine readable time format. Instant stores date time in unix
timestamp.
package com.journaldev.java8.time;

import java.time.Duration;
import java.time.Instant;

public class InstantExample {

public static void main(String[] args) {


//Current timestamp
Instant timestamp = Instant.now();
System.out.println("Current Timestamp = "+timestamp);

//Instant from timestamp


Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
System.out.println("Specific Time = "+specificTime);

//Duration example
Duration thirtyDay = Duration.ofDays(30);
System.out.println(thirtyDay);
}

}
Collected & Prepared By: T. N.RANGANADHAM Page 33 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Output:
Current Timestamp = 2014-04-28T23:20:08.489Z
Specific Time = 2014-04-28T23:20:08.489Z
PT720H

Java 8 Date Parsing and Formatting


It’s very common to format date into different formats and then parse a String to get the Date Time
objects.
package com.journaldev.java8.time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateParseFormatExample {

public static void main(String[] args) {

//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("Default format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

LocalDateTime dateTime = LocalDateTime.now();


//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
Collected & Prepared By: T. N.RANGANADHAM Page 34 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu
HH::mm::ss")));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

Instant timestamp = Instant.now();


//default format
System.out.println("Default format of Instant="+timestamp);

//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt);
}

}
Output:
Default format of LocalDate=2014-04-28
28::Apr::2014
20140428
Default format of LocalDateTime=2014-04-28T16:25:49.341
28::Apr::2014 16::25::49
20140428
Default format of Instant=2014-04-28T23:25:49.342Z
Default format after parsing = 2014-04-27T21:39:48

The Temporal Package


The java.time.temporal package provides a collection of interfaces, classes, and enums that support
date and time code and, in particular, date and time calculations.

Temporal and TemporalAccessor


The Temporal interface provides a framework for accessing temporal-based objects, and is implemented
by the temporal-based classes, such as Instant, LocalDateTime, and ZonedDateTime. This interface
provides methods to add or subtract units of time, making time-based arithmetic easy and consistent
across the various date and time classes. The TemporalAccessor interface provides a read-only version
of the Temporal interface.

Collected & Prepared By: T. N.RANGANADHAM Page 35 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Both Temporal and TemporalAccessor objects are defined in terms of fields, as specified in the
TemporalField interface. The ChronoField enum is a concrete implementation of the TemporalField
interface and provides a rich set of defined constants, such as DAY_OF_WEEK, MINUTE_OF_HOUR, and
MONTH_OF_YEAR.

Temporal Adjuster
The TemporalAdjuster interface, in the java.time.temporal package, provides methods that take a
Temporal value and return an adjusted value. The adjusters can be used with any of the temporal-based
types.

If an adjuster is used with a ZonedDateTime, then a new date is computed that preserves the original
time and time zone values.

Predefined Adjusters
The TemporalAdjusters class (note the plural) provides a set of predefined adjusters for finding the first
or last day of the month, the first or last day of the year, the last Wednesday of the month, or the first
Tuesday after a specific date, to name a few examples. The predefined adjusters are defined as static
methods and are designed to be used with the static import statement.

The following example uses several TemporalAdjusters methods, in conjunction with the with method
defined in the temporal-based classes, to compute new dates based on the original date of 15 October
2000:
LocalDate date = LocalDate.of(2000, Month.OCTOBER, 15);
DayOfWeek dotw = date.getDayOfWeek();
System.out.printf("%s is on a %s%n", date, dotw);

System.out.printf("first day of Month: %s%n",


date.with(TemporalAdjusters.firstDayOfMonth()));
System.out.printf("first Monday of Month: %s%n",
date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
System.out.printf("last day of Month: %s%n",
date.with(TemporalAdjusters.lastDayOfMonth()));
System.out.printf("first day of next Month: %s%n",
date.with(TemporalAdjusters.firstDayOfNextMonth()));

Collected & Prepared By: T. N.RANGANADHAM Page 36 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

System.out.printf("first day of next Year: %s%n",


date.with(TemporalAdjusters.firstDayOfNextYear()));
System.out.printf("first day of Year: %s%n",
date.with(TemporalAdjusters.firstDayOfYear()));
output:

2000-10-15 is on a SUNDAY
first day of Month: 2000-10-01
first Monday of Month: 2000-10-02
last day of Month: 2000-10-31
first day of next Month: 2000-11-01
first day of next Year: 2001-01-01
first day of Year: 2000-01-01

Custom Adjusters
You can also create your own custom adjuster. To do this, you create a class that implements the
TemporalAdjuster interface with a adjustInto(Temporal) method. The nest example is the
PaydayAdjuster custom adjuster. It evaluates the passed-in date and returns the next payday, assuming
that payday occurs twice a month: on the 15th, and again on the last day of the month. If the computed
date occurs on a weekend, then the previous Friday is used. The current calendar year is assumed.

public class PaydayAdjuster implements TemporalAdjuster {


/**
* The adjustInto method accepts a Temporal instance
* and returns an adjusted LocalDate. If the passed in
* parameter is not a LocalDate, then a DateTimeException is thrown.
*/
public Temporal adjustInto(Temporal input) {
LocalDate date = LocalDate.from(input);
int day;
if (date.getDayOfMonth() < 15) {
day = 15;
} else {
day = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();

Collected & Prepared By: T. N.RANGANADHAM Page 37 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
date = date.withDayOfMonth(day);
if (date.getDayOfWeek() == DayOfWeek.SATURDAY ||
date.getDayOfWeek() == DayOfWeek.SUNDAY) {
date = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
}

return input.with(date);
}
}
Output:
Given the date: 2013 Jun 3
the next payday: 2013 Jun 14

Given the date: 2013 Jun 18


the next payday: 2013 Jun 28

EXCEPTION HANDLING
Introduction

o An exception is an event that occurs during the execution of a program


that disrupts the normal flow of instruction.
Or
o An abnormal condition that disrupts Normal program flow.
o There are many cases where abnormal conditions happen during
program execution, such as
o Trying to access an out - of – bounds array elements.
o The file you try to open may not exist.
o The file we want to load may be missing or in the wrong format.
o The other end of your network connection may be non – existence.
o If these cases are not prevented or at least handled properly, either the
program will be aborted abruptly, or the incorrect results or status will be
produced.
o When an error occurs with in the java method, the method creates an
exception object and hands it off to the runtime system.
o The exception object contains information about the exception including
its type and the state of the program when the error occurred. The
runtime system is then responsible for finding some code to handle the
error.
Collected & Prepared By: T. N.RANGANADHAM Page 38 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

o In java creating an exception object and handling it to the runtime system


is called throwing an exception.
o Exception is an object that is describes an exceptional ( i.e. error)
condition that has occurred in a piece of code at run time.
o When a exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That
method may choose to handle the exception itself, or pass it on. Either
way, at some point, the exception is caught and processed.
o Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
o System generated exceptions are automatically thrown by the Java runtime
system

General form of Exception


Handling block try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...

finally {
// block of code to be executed before try block ends

Collected & Prepared By: T. N.RANGANADHAM Page 39 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Try Block

No

Exception Throws exception object

arise or
Catch Block
No Exceptional Handler
appropriate

Catch

block

Finally Block
Optional part

By using exception to managing errors, Java programs have have the


following advantage over traditional error management techniques:
– Separating Error handling code from regular code.
– Propagating error up the call stack.
– Grouping error types and error differentiation.

For Example:

class Exc0 {
public static void main(String
args[]) { int d = 0;
int a = 42 / d;
}
}

java.lang.ArithmeticException: /
by zero at Exc0.main(Exc0.java:4)
Notice how the class name, Exc0; the method name, main; the filename,
Exc0.java; and the line number, 4

Collected & Prepared By: T. N.RANGANADHAM Page 40 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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

Collected & Prepared By: T. N.RANGANADHAM Page 41 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Collected & Prepared By: T. N.RANGANADHAM Page 42 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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.

Collected & Prepared By: T. N.RANGANADHAM Page 43 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-
catch block.
Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.

1. String s=null;

Collected & Prepared By: T. N.RANGANADHAM Page 44 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there


may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block


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


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Collected & Prepared By: T. N.RANGANADHAM Page 45 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Syntax of try-finally block


1. try{
2. //code that may throw an exception
3. }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

The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Collected & Prepared By: T. N.RANGANADHAM Page 46 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Example 1
TryCatchExample1.java
1. public class TryCatchExample1 {
2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.
7. System.out.println("rest of the code");
8.
9. }
10.
11. }
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all
the code below the exception won't be executed.
Solution by exception handling
Let's see the solution of the above problem by a java try-catch block.
Example 2
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");
}

Collected & Prepared By: T. N.RANGANADHAM Page 47 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
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.

Flowchart of Multi-catch Block

Example 1

Let's see a simple example of java multi-catch block.


Collected & Prepared By: T. N.RANGANADHAM Page 48 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }

Output:

Arithmetic Exception occurs


rest of the code
Example 2

MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];

Collected & Prepared By: T. N.RANGANADHAM Page 49 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time only one exception
occurs and its corresponding catch block is executed.

MultipleCatchBlock3.java

1. public class MultipleCatchBlock3 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. System.out.println(a[10]);
9. }

Collected & Prepared By: T. N.RANGANADHAM Page 50 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }

Output:

Arithmetic Exception occurs


rest of the code
Example 4

In this example, we generate NullPointerException, but didn't provide the corresponding


exception type. In such case, the catch block containing the parent exception
class Exception will invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. String s=null;
7. System.out.println(s.length());
8. }
9. catch(ArithmeticException e)
10. {

Collected & Prepared By: T. N.RANGANADHAM Page 51 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

11. System.out.println("Arithmetic Exception occurs");


12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }

Output:

Parent Exception occurs


rest of the code
Example 5

Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).

MultipleCatchBlock5.java

1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }

Output:
Collected & Prepared By: T. N.RANGANADHAM Page 52 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Compile-time error

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

Java Nested try Example

Let's consider the following example. Here the try block within nested try block (inner try
block 2) do not handle the exception. The control is then transferred to its parent try
block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block
handles the exception. It is termed as nesting.

NestedTryBlock.java

1. public class NestedTryBlock2 {


2. public static void main(String args[])
3. { // outer (main) try block
4. try {
5. //inner try block 1
6. try {
7. // inner try block 2
8. try {
9. int arr[] = { 1, 2, 3, 4 };
10.
11. //printing the array element out of its bounds
12. System.out.println(arr[10]);
13. }
14. // to handles ArithmeticException
Collected & Prepared By: T. N.RANGANADHAM Page 53 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

15. catch (ArithmeticException e) {


16. System.out.println("Arithmetic exception");
17. System.out.println(" inner try block 2");
18. }
19. }
20.
21. // to handle ArithmeticException
22. catch (ArithmeticException e) {
23. System.out.println("Arithmetic exception");
24. System.out.println("inner try block 1");
25. }
26. }
27.
28. // to handle ArrayIndexOutOfBoundsException
29. catch (ArrayIndexOutOfBoundsException e4) {
30. System.out.print(e4);
31. System.out.println(" outer (main) try block");
32. }
33. catch (Exception e5) {
34. System.out.print("Exception");
35. System.out.println(" handled in main try-block");
36. }
37. }
38. }

Output:

Java finally block


Collected & Prepared By: T. N.RANGANADHAM Page 54 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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.
Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).
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.
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any exception, and
the finally block is executed after the try block.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{

Collected & Prepared By: T. N.RANGANADHAM Page 55 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

4. //below code do not throw any exception


5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:

Case 2: When an exception occur but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try block
and then the program terminates abnormally.
TestFinallyBlock1.java
1. public class TestFinallyBlock1{
2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
Collected & Prepared By: T. N.RANGANADHAM Page 56 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:

Case 3: When an exception occurs and is handled by the catch block


Example:
Let's see the following example where the Java code throws an exception and the catch
block handles the exception. Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.
TestFinallyBlock2.java
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. //below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }

Collected & Prepared By: T. N.RANGANADHAM Page 57 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

9. //handles the Arithmetic Exception / Divide by zero exception


10. catch(ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14.
15. //executes regardless of exception occured or not
16. finally {
17. System.out.println("finally block is always executed");
18. }
19.
20. System.out.println("rest of the code...");
21. }
22. }
Output:

Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked at
the compile time instead of runtime and we can create custom exceptions making the
code recovery and debugging easier.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.
Java throw keyword Example

Collected & Prepared By: T. N.RANGANADHAM Page 58 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Example 1: Throwing Unchecked Exception


In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a parameter. If the age
is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
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...");
}
}
Output:

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.
Example 2: Throwing Checked Exception
Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A
checked exception is everything else under the Throwable class.
Collected & Prepared By: T. N.RANGANADHAM Page 59 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

TestThrow2.java
import java.io.*;

public class TestThrow2 {

//function to check if person is eligible to vote or not


public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");


BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
Collected & Prepared By: T. N.RANGANADHAM Page 60 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// Calling constructor of parent Exception


super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:

Java Exception Propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack
to the previous method. If not caught there, the exception again drops down to the previous method,
and so on until they are caught or until they reach the very bottom of the call stack. This is called
exception propagation.
Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).
Exception Propagation Example
TestExceptionPropagation1.java
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
Collected & Prepared By: T. N.RANGANADHAM Page 61 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not handled, so it is propagated to
the previous n() method where it is not handled, again it is propagated to the p() method where
exception is handled.
Exception can be handled in any method in call stack either in the main() method, p() method, n()
method or m() method.

Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Exception Propagation Example
TestExceptionPropagation1.java
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();

Collected & Prepared By: T. N.RANGANADHAM Page 62 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}catch(Exception e){System.out.println("exception handeled");}


}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
}
Output:
Compile Time Error
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
}
Which exception should be declared?
Ans: Checked exception only, because:
unchecked exception: under our control so we can correct our code.
error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws Example
Let's see the example of Java throws clause which describes that checked exceptions can be propagated
by throws keyword.
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}

Collected & Prepared By: T. N.RANGANADHAM Page 63 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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...");
}
}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.
There are two cases:
Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
Case 2: We have declared the exception i.e. specified throws keyword with the method.
Case 1: Handle Exception Using try-catch block
In case we handle the exception, the code will be executed fine whether exception occurs during the
program or not.
Testthrows2.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

Collected & Prepared By: T. N.RANGANADHAM Page 64 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Case 2: Declare Exception


In case we declare the exception, if exception does not occur, the code will be executed fine.
In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.
Let's see examples for both the scenario.
A) If exception does not occur
Testthrows3.java
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:
device operation performed
normal flow...
B) If exception occurs
Testthrows4.java
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:
Collected & Prepared By: T. N.RANGANADHAM Page 65 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in signature
of the method.
There are many differences between throw and throws keywords. A list of differences between throw
and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used throw Java throws keyword is


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

2. Type of exception Using Using throws keyword, we can


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

3. Syntax The throw keyword is followed by The throws keyword is


an instance of Exception to be followed by class names
thrown. of Exceptions to be
thrown.

4. Declaration throw is used within the method. throws is used with the
method signature.

5. Internal implementation We are allowed to throw only one We can declare multiple
exception at a time i.e. we cannot exceptions using throws

Collected & Prepared By: T. N.RANGANADHAM Page 66 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

throw multiple exceptions. keyword that can be


thrown by the method.
For example, main()
throws IOException,
SQLException.

Java throw Example


TestThrow.java
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
Output:

Java throws Example


TestThrows.java
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}

Collected & Prepared By: T. N.RANGANADHAM Page 67 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

//main method
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


TestThrowAndThrows.java
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");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");

Collected & Prepared By: T. N.RANGANADHAM Page 68 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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

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

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

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

4. Execution Final method is Finally block is executed finalize method is

Collected & Prepared By: T. N.RANGANADHAM Page 69 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

executed only when as soon as the try-catch executed just before the
we call it. block is executed. object is destroyed.
It's execution is not
dependant on the
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
Let's see the below example where the 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[]){
Collected & Prepared By: T. N.RANGANADHAM Page 70 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

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()
{

Collected & Prepared By: T. N.RANGANADHAM Page 71 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

System.out.println("Called the finalize() method");


}
}
Output:

Exception Handling with Method Overriding in Java


There are many rules if we talk about method overriding with exception handling.
Some of the rules are listed below:
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.
If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
Let's consider following example based on the above rule.
TestExceptionChild.java
import java.io.*;
class Parent{

// defining the method


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

public class TestExceptionChild extends Parent{

// overriding the method in child class


// gives compile time error
void msg() throws IOException {
System.out.println("TestExceptionChild");
}

Collected & Prepared By: T. N.RANGANADHAM Page 72 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

public static void main(String args[]) {


Parent p = new TestExceptionChild();
p.msg();
}
}
Output:

Rule 2: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.
TestExceptionChild1.java
import java.io.*;
class Parent{
void msg() {
System.out.println("parent method");
}
}

class TestExceptionChild1 extends Parent{


void msg()throws ArithmeticException {
System.out.println("child method");
}

public static void main(String args[]) {


Parent p = new TestExceptionChild1();
p.msg();
}
}
Output:

If the superclass method declares an exception


Rule 1: If the superclass method declares an exception, subclass overridden method can
declare the same subclass exception or no exception but cannot declare parent exception.
Collected & Prepared By: T. N.RANGANADHAM Page 73 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Example in case subclass overridden method declares parent exception


TestExceptionChild2.java
import java.io.*;
class Parent{
void msg()throws ArithmeticException {
System.out.println("parent method");
}
}

public class TestExceptionChild2 extends Parent{


void msg()throws Exception {
System.out.println("child method");
}

public static void main(String args[]) {


Parent p = new TestExceptionChild2();

try {
p.msg();
}
catch (Exception e){}

}
}
Output:

Example in case subclass overridden method declares same exception


TestExceptionChild3.java
import java.io.*;
class Parent{
void msg() throws Exception {
System.out.println("parent method");
}
}

public class TestExceptionChild3 extends Parent {


Collected & Prepared By: T. N.RANGANADHAM Page 74 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

void msg()throws Exception {


System.out.println("child method");
}

public static void main(String args[]){


Parent p = new TestExceptionChild3();

try {
p.msg();
}
catch(Exception e) {}
}
}
Output:

Example in case subclass overridden method declares subclass exception


TestExceptionChild4.java
import java.io.*;
class Parent{
void msg()throws Exception {
System.out.println("parent method");
}
}

class TestExceptionChild4 extends Parent{


void msg()throws ArithmeticException {
System.out.println("child method");
}

public static void main(String args[]){


Parent p = new TestExceptionChild4();

try {
p.msg();
}
catch(Exception e) {}
}

Collected & Prepared By: T. N.RANGANADHAM Page 75 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
Output:

Example in case subclass overridden method declares no exception


TestExceptionChild5.java
import java.io.*;
class Parent {
void msg()throws Exception{
System.out.println("parent method");
}
}

class TestExceptionChild5 extends Parent{


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

public static void main(String args[]){


Parent p = new TestExceptionChild5();

try {
p.msg();
}
catch(Exception e) {}

}
}
Output:

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our
own Exception is known as custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.

Collected & Prepared By: T. N.RANGANADHAM Page 76 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the programming.
However, we sometimes need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
To catch and provide specific treatment to a subset of existing Java exceptions.
Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful
for the application users or the developers to understand the exact problem.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
Consider the following example, where we create a custom exception named WrongFileNameException:
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
Note: We need to write the constructor that takes the String as the error message and it is
called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent class
Exception using the super() method. Also the constructor of Exception class can be called without using
a parameter and calling super() method is not mandatory.
TestCustomException1.java
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){
Collected & Prepared By: T. N.RANGANADHAM Page 77 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

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


}
}
Output:

Example 2:
TestCustomException2.java
// class representing custom exception
class MyCustomException extends Exception
{

Collected & Prepared By: T. N.RANGANADHAM Page 78 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// class that uses custom exception MyCustomException


public class TestCustomException2
{
// main method
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}

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


}
}
Output:

Collected & Prepared By: T. N.RANGANADHAM Page 79 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Java IO : Input-output in Java

Java brings various Streams with its I/O package that helps the user to perform all the input-output
operations. These streams support all the types of objects, data-types, characters, files etc to fully
execute the I/O operations.

Standard I/O Streams in Java


3 standard or default streams that Java has to provide which are also most common in use:

1. System.in: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a program on
an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:

print(): This method in Java is used to display a text on the console. This text is passed as the parameter
to this method in the form of String. This method prints the text on the console and the cursor remains
at the end of the text at the console. The next printing takes place from just here.
Syntax:
System.out.print(parameter);
Example:
// Java code to illustrate print()
import java.io.*;

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

Collected & Prepared By: T. N.RANGANADHAM Page 80 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
Output:

GfG! GfG! GfG!

println(): This method in Java is also used to display a text on the console. It prints the text on the
console and the cursor moves to the start of the next line at the console. The next printing takes place
from the next line.
Syntax:
System.out.println(parameter);
Example:
// Java code to illustrate println()

import java.io.*;

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

// using println()
// all are printed in the
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
Output:

GfG!
GfG!
GfG!

printf(): This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and
System.out.println() take a single argument, but printf() may take multiple arguments. This is used to
format the output in Java.
Example:

Collected & Prepared By: T. N.RANGANADHAM Page 81 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// A Java program to demonstrate working of printf() in Java


class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf(
"Printing simple"
+ " integer: x = %d\n",
x);

// this will print it upto


// 2 decimal places
System.out.printf(
"Formatted with"
+ " precision: PI = %.2f\n",
Math.PI);

float n = 5.2f;

// automatically appends zero


// to the rightmost part of decimal
System.out.printf(
"Formatted to "
+ "specific width: n = %.4f\n",
n);

n = 2324435.3f;

// here number is formatted from


// right margin and occupies a
// width of 20 characters
System.out.printf(
"Formatted to "
+ "right margin: n = %20.4f\n",
n);
}
}

Output:

Printing simple integer: x = 100


Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

Collected & Prepared By: T. N.RANGANADHAM Page 82 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

3. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:

print()
println()
printf()
Example:
// Java code to illustrate standard
// input output streams

import java.io.*;
public class SimpleIO {

public static void main(String args[])


throws IOException
{

// InputStreamReader class to read input


InputStreamReader inp = null;

// Storing the input in inp


inp = new InputStreamReader(System.in);

System.out.println("Enter characters, "


+ " and '0' to quit.");
char c;
do {
c = (char)inp.read();
System.out.println(c);
} while (c != '0');
}
}

Input:

GeeksforGeeks0
Output:

Enter characters, and '0' to quit.


G
e
e
k

Collected & Prepared By: T. N.RANGANADHAM Page 83 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

s
f
o
r
G
e
e
k
s
0

Types of Streams:

Depending on the type of operations, streams can be divided into two primary classes:
1.Input Stream: These streams are used to read data that must be taken as an input from a source array
or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream
etc.

2.Output Stream: These streams are used to write data as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.

Collected & Prepared By: T. N.RANGANADHAM Page 84 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Depending on the types of file


Streams can be divided into two primary classes which can be further divided into other classes as can
be seen through the diagram below followed by the explanations.

ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to
read from the source and FileOutputStream is used to write to the destination. Here is the list of various
ByteStream Classes:

Collected & Prepared By: T. N.RANGANADHAM Page 85 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Stream class Description


BufferedInputStream It is used for Buffered Input Stream.
DataInputStream It contains method for reading java standard datatypes.
FileInputStream This is used to reads from a file
InputStream This is an abstract class that describes stream input.
PrintStream This contains the most used print() and println() method
BufferedOutputStream This is used for Buffered Output Stream.
DataOutputStream This contains method for writing java standard data types.
FileOutputStream This is used to write to a file.
OutputStream This is an abstract class that describe stream output.

// Java Program illustrating the


// Byte Stream to copy
// contents of one file to another file.
import java.io.*;
public class BStream {
public static void main(
String[] args) throws IOException
{

FileInputStream sourceStream = null;


FileOutputStream targetStream = null;

try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");

// Reading source file and writing


// content to target file byte by byte
int temp;
while ((
temp = sourceStream.read())
!= -1)
targetStream.write((byte)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}

Collected & Prepared By: T. N.RANGANADHAM Page 86 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

}
}

Output:

Shows contents of file test.txt

CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details).
Character stream automatically allows us to read/write data character by character. Though it has many
classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are
character streams used to read from the source and write to the destination respectively. Here is the list
of various CharacterStream Classes:

Stream class Description


BufferedReader It is used to handle buffered input stream.
FileReader This is an input stream that reads from file.
InputStreamReader This input stream is used to translate byte to character.
OutputStreamReader This output stream is used to translate character to byte.
Reader This is an abstract class that define character stream input.
PrintWriter This contains the most used print() and println() method
Writer This is an abstract class that define character stream output.
BufferedWriter This is used to handle buffered output stream.
FileWriter This is used to output stream that writes to file.

// Java Program illustrating that


// we can read a file in a human-readable
// format using FileReader

// Accessing FileReader, FileWriter,


// and IOException
import java.io.*;
public class GfG {
public static void main(
String[] args) throws IOException
{
FileReader sourceStream = null;
try {
sourceStream
= new FileReader("test.txt");

Collected & Prepared By: T. N.RANGANADHAM Page 87 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// Reading sourcefile and


// writing content to target file
// character by character.
int temp;
while ((
temp = sourceStream.read())
!= -1)
System.out.println((char)temp);
}
finally {
// Closing stream as no longer in use
if (sourceStream != null)
sourceStream.close();
}
}
}

Scanner Class in Java


In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double, etc. and strings.

To create an object of Scanner class, we usually pass the predefined object System.in, which represents
the standard input stream. We may pass an object of class File if we want to read input from a file.
To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to
read a value of type short, we can use nextShort()
To read strings, we use nextLine().
To read a single character, we use next().charAt(0). next() function returns the next token/word in the
input as a string and charAt(0) function returns the first character in that string.
The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that
have some meaning to the Java compiler.

Java Scanner Input Types


Scanner class helps to take the standard input stream in Java. So, we need some methods to extract
data from the stream. Methods used for extracting data are mentioned below:
Method Description
nextBoolean() Used for reading Boolean value
nextByte() Used for reading Byte value
nextDouble() Used for reading Double value
nextFloat() Used for reading Float value
nextInt() Used for reading Int value
nextLine() Used for reading Line value
nextLong() Used for reading Long value
nextShort() Used for reading Short value
Collected & Prepared By: T. N.RANGANADHAM Page 88 of 90
ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

// Java program to read data of various types


// using Scanner class.
import java.util.Scanner;

// Driver Class
public class ScannerDemo1 {
// main function
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();

// Character input
char gender = sc.next().charAt(0);

// Numerical data input


// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();

// Print the values to check if the input was


// correctly obtained.
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Mobile Number: " + mobileNo);
System.out.println("CGPA: " + cgpa);
}
}

Input

Geek
F
40
9876543210
9.9

Collected & Prepared By: T. N.RANGANADHAM Page 89 of 90


ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES :: RAJAMPET
AUTONOMOUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Regulation: Subject Code: Subject Name : Object Oriented Programming AY: 2024-2025
R23 23A0533T Through JAVA
CSE/CSA/CSD/AI&DS/AIML
Unit4 (Packages and Java Library, Exceptions, Java I/O, Files)

Output

Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9

Collected & Prepared By: T. N.RANGANADHAM Page 90 of 90

You might also like