r23 Java Unit4 Ay 2024 25
r23 Java Unit4 Ay 2024 25
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.
//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
//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
//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.
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
//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
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)
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{}
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
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.
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)
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) {
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;
}
// Constructor
public Test(Day day) {
this.day = day;
}
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.
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
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)
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)
// Comparison operators
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)
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...
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)
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';
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 GFG {
public static void main(String[] args)
{
// byte data type
byte a = 1;
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)
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);
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)
// wrapper class
class Maximum {
private int maxi = 0;
private int size = 0;
//
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);
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)
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
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(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.
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(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.
Class methods
Sr.No. Method & Description
void close()
1
This method closes this formatter.
void flush()
2
This method flushes this formatter.
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)
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.
import java.util.Formatter;
import java.util.Locale;
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 !
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).
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.
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.
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;
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
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.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.
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
//Current Date
LocalDate today = LocalDate.now();
System.out.println("Current Date="+today);
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 Date=2014-04-28
Specific Date=2014-01-01
Current Date in IST=2014-04-29
365th day from base date= 1971-01-01
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. 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 {
//Current Time
LocalTime time = LocalTime.now();
System.out.println("Current Time="+time);
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 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;
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
LocalDateTime today = LocalDateTime.now();
System.out.println("Current DateTime="+today);
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;
//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
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
//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));
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));
//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
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);
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)
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.
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
EXCEPTION HANDLING
Introduction
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 (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
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
arise or
Catch Block
No Exceptional Handler
appropriate
Catch
block
Finally Block
Optional part
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
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 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:
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)
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 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.
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.
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)
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
1. String s=null;
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
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
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.
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 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.
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 {
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.
Example 1
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
Output:
MultipleCatchBlock2.java
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:
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
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:
MultipleCatchBlock4.java
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:
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
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.
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
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:
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{
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: 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:
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)
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).
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 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.*;
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)
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();
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)
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...
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("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)
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
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)
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");
}
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:
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.
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.
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:
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)
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)
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");
}
}
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 {
p.msg();
}
catch (Exception e){}
}
}
Output:
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 {
p.msg();
}
catch(Exception e) {}
}
}
Output:
try {
p.msg();
}
catch(Exception e) {}
}
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:
try {
p.msg();
}
catch(Exception e) {}
}
}
Output:
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);
}
}
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[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
Example 2:
TestCustomException2.java
// class representing custom exception
class MyCustomException extends Exception
{
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)
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 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.
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)
{
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:
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:
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)
float n = 5.2f;
n = 2324435.3f;
Output:
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 {
Input:
GeeksforGeeks0
Output:
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.
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)
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:
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 {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");
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:
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:
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)
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.
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 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);
Input
Geek
F
40
9876543210
9.9
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