1
UNIT-IV
Object Oriented Programming Through JAVA
INDEX
Sl. No. Topic Page No.
4.1 Introduction Package 2
4.1.1 Defining Package 2-3
4.1.2 Importing Packages and Classes into Programs 3-5
4.1.3 Path and Class Path 5-6
4.1.4 Access Control 6-8
4.1.5 Packages in Java SE 8-9
4.1.6 [Link] Package and its Classes 9-11
4.1.7 Class Object 11-13
4.1.8 Enumeration 13-15
4.1.9 class Math 15-16
4.1.10 Wrapper Classes 16-18
4.1.11 Auto-boxing and Auto-unboxing 18-19
4.1.12 Java util Classes and Interfaces 19-21
4.1.13 Formatter Class 21-22
4.1.14 Random Class 22-23
4.1.15 Time Package 23-25
4.1.16 Class Instant ([Link]) 25-27
4.1.17 Formatting for Date/Time in Java 27-28
4.1.18 Temporal Adjusters Class 28-29
4.1.19 Temporal Adjusters Class 30-31
4.2 Exception Handling: Introduction 31-33
4.2.1 Hierarchy of Standard Exception Classes 34-35
4.2.2 Keywords throws and throw, try, catch, and finally Blocks 35-37
4.2.3 Multiple Catch Clauses 37-39
4.2.4 Class Throwable 39-40
4.2.5 Unchecked Exceptions 41
4.2.6 Checked Exceptions 42-43
4.3 Java I/O and File: 43-44
4.3.1 Java I/O API 44-46
4.3.2 standard I/O streams, types 46-47
4.3.3 Byte streams 47-49
4.3.4 Character streams 50-52
4.3.5 Scanner class 52-53
4.3.6 Files in Java(Text Book 2) 53-56
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
2
4.1 Introduction Package
In Java, an Introduction Package is not a standard term, but it seems like you're referring to
either:
1. A basic Java package used to introduce Java programming concepts (i.e., a starter
package for learners),
2. Or simply the package keyword in Java, which is used to group related classes.
I'll explain both briefly and then give a simple example.
1. What is a package in Java?
A package in Java is a way to organize related classes and interfaces. Think of it like a folder
in your filesystem.
• Built-in packages: [Link], [Link], [Link], etc.
• Custom packages: You can create your own packages for better code organization.
2. A Simple "Introduction Package" Example
Let’s say you want to create a beginner-level Java package named introduction, which contains
a basic class called HelloWorld.
Folder Structure:
project-root/
└── introduction/
└── [Link]
File: [Link]
package introduction;
public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello, welcome to the Introduction Package!");
}
}
How to Compile and Run:
javac introduction/[Link]
java [Link]
Why Use Packages?
• Avoid class name conflicts.
• Make large projects easier to manage.
• Control access using public, protected, default, and private modifiers.
4.1.1 Defining Package
a package is defined using the package keyword at the very top of your .java file. It tells the
compiler that this class belongs to a specific package (which acts like a folder or namespace).
Syntax of Defining a Package
package package_name;
• This must be the first line (except for comments).
• The package name usually follows lowercase naming and reverse domain name
conventions in real projects.
Example: Defining and Using a Package
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
3
Step 1: Define a Package
Let's define a package called myintro.
File: [Link]
package myintro;
public class MyClass
{
public void sayHello()
{
[Link]("Hello from the myintro package!");
}
}
Step 2: Use the Package in Another Class
Create another class in a different file or directory to use MyClass.
File: [Link]
import [Link];
public class Test
{
public static void main(String[] args)
{
MyClass obj = new MyClass();
[Link]();
}
}
Step 3: Folder Structure
project-root/
├── myintro/
│ └── [Link]
└── [Link]
Step 4: Compile and Run
javac myintro/[Link]
javac -cp . [Link]
java Test
Output:
Hello from the myintro package!
4.1.2 Importing Packages and Classes into Programs
The import statement is used to bring in classes or entire packages into your code so you can
use them without fully qualifying their names every time.
1. Why Use import?
Without import, you'd have to write full class names like:
[Link] scanner = new [Link]([Link]);
With import:
import [Link];
Scanner scanner = new Scanner([Link]);
2. Importing Classes vs. Packages
Import a Single Class
import [Link];
➡ Allows direct use of Scanner.
Import All Classes in a Package
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
4
import [Link].*;
➡ Gives access to all classes in [Link], like Scanner, ArrayList, HashMap, etc.
This doesn't import sub-packages — just the classes in that package.
3. Example: Importing and Using a Class
File: [Link]
import [Link];
public class MyProgram
{
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name + "!");
}
}
Scanner is part of [Link], so we import it at the top.
4. Importing Your Own Custom Package
Let’s say you’ve created your own package:
File: mypack/[Link]
package mypack;
public class Greeting
{
public void sayHi()
{
[Link]("Hi from mypack!");
}
}
File: [Link]
import [Link];
public class MainApp
{
public static void main(String[] args)
{
Greeting g = new Greeting();
[Link]();
}
}
Compile and Run:
javac mypack/[Link]
javac [Link]
java MainApp
5. Static Import (for static members)
You can import static methods or constants like this:
import static [Link];
import static [Link];
public class MathDemo
{
public static void main(String[] args)
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
5
{
[Link]("PI = " + PI);
[Link]("Square root of 16 = " + sqrt(16));
}
}
Output:
PI = 3.141592653589793
Square root of 16 = 4.0
Summary Table
Syntax What it Does
import [Link]; Imports one class
import [Link].*; Imports all classes in [Link]
import [Link]; Imports your custom class
import static [Link].*; Imports all static members of Math
4.1.3 Path and Class Path
Path vs Classpath in Java
Both PATH and CLASSPATH are environment variables used by Java, but they serve different
purposes.
1. PATH — Tells OS where to find Java tools
The PATH variable is used by your operating system to locate the Java Development Kit
(JDK) tools like:
• javac → Java compiler
• java → Java runtime
• javadoc, jar, etc.
Example:
PATH = C:\Program Files\Java\jdk-21\bin;
This allows you to run javac, java, etc. from any folder in the terminal.
Without PATH set, you’d need to do:
C:\Program Files\Java\jdk-21\bin\javac [Link]
With PATH set correctly:
javac [Link]
2. CLASSPATH — Tells Java where to find .class files
The CLASSPATH is used by Java (not the OS) to locate:
• Compiled .class files
• External libraries (JARs)
• User-defined packages
Example:
CLASSPATH = C:\myprojects\classes;C:\libs\[Link];
It tells the JVM or compiler:
"Look here to find classes not in the default system libraries."
Example of Using CLASSPATH
Suppose you have:
project/
├── utils/
│ └── [Link]
└── [Link]
File: utils/[Link]
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
6
package utils;
public class Tools
{
public static void greet()
{
[Link]("Hello from Tools!");
}
}
File: [Link]
import [Link];
public class App
{
public static void main(String[] args)
{
[Link]();
}
}
Compile with classpath:
javac utils/[Link]
javac -cp . [Link]
Run with classpath:
java -cp . App
Or set the CLASSPATH permanently or temporarily:
set CLASSPATH=.;utils;
java App
The dot . refers to the current directory.
Summary: PATH vs CLASSPATH
Feature PATH CLASSPATH
Used by Operating System Java Compiler & JVM
Purpose Locate Java tools (java, javac) Locate classes and libraries
Includes JDK's bin/ directory Directories or .jar files
Set using OS Environment Variable OS Env Var or -cp / -classpath
4.1.4 Access Control
Java provides a clear access control mechanism to restrict or allow access to classes, variables,
and methods based on:
1. Access modifiers (public, protected, private, and default/no modifier),
2. Package structure.
Let’s break it down with a focus on package-level access.
Java Access Modifiers Overview
Modifier Same Same Subclass (Diff Other
Class Package Package) Packages
public
no modifier
(default/package-private)
protected
private
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
7
1. Default (Package-Private) Access
If you don’t specify an access modifier (i.e., use no keyword), Java uses package-private
access by default:
class MyClass
{
void sayHello()
{
[Link]("Hello!");
}
}
This class and its sayHello() method are:
• Accessible only from other classes in the same package.
• Not accessible from outside the package, even with import.
2. public Access
public class MyClass
{
public void sayHello()
{
[Link]("Hi!");
}
}
• The class and method can be accessed from anywhere, any package, if properly
imported.
3. private Access
class MyClass {
private void secretMethod()
{
[Link]("Top Secret");
}
}
• secretMethod() is accessible only inside MyClass, not even from other classes in the
same package.
4. protected Access
class MyClass
{
protected void welcome()
{
[Link]("Welcome!");
}
}
• Accessible:
o Within the same package
o From subclasses, even in different packages
• Not accessible from non-subclass classes in other packages.
Example: Package Access in Action
File: mypack/[Link]
package mypack;
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
8
class PackageClass
{
void display()
{
[Link]("Package-private access");
}
}
File: otherpack/[Link]
package otherpack;
import [Link];
public class TestAccess
{
public static void main(String[] args)
{
PackageClass pc = new PackageClass(); // Error: not public
[Link](); // Error: not accessible
}
}
This will fail because PackageClass is package-private — not visible to otherpack.
4.1.5 Packages in Java SE
In Java SE, packages are used to organize Java classes into namespaces and provide
modularity, access control, and reusability. Java SE comes with a rich set of built-in packages
that support everything from basic utilities to networking, GUI development, and more.
What Is a Package in Java SE?
• A package is a namespace that organizes a set of related classes and interfaces.
• Java SE provides predefined packages.
• You can also create user-defined packages.
Common Built-in Packages in Java SE
Here are the most widely used packages in Java SE:
Package Name Description
[Link] Core classes (automatically imported): String, Math, Object, System,
Thread, etc.
[Link] Utility classes: ArrayList, HashMap, Date, Collections, Random, etc.
[Link] Input and Output: File, InputStream, OutputStream, BufferedReader,
etc.
[Link] Non-blocking I/O (more modern and scalable alternative to [Link])
[Link] Networking classes: Socket, URL, HttpURLConnection, etc.
[Link] JDBC API for accessing databases: Connection, Statement,
ResultSet, etc.
[Link] Date and time API (Java 8+): LocalDate, LocalTime,
LocalDateTime, etc.
[Link] GUI components (Swing): JFrame, JButton, JLabel, etc.
[Link] Abstract Window Toolkit: Graphics, GUI components, layout
managers, etc.
[Link] Security and encryption: MessageDigest, KeyStore, etc.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
9
[Link] Big number support: BigInteger, BigDecimal
[Link] Multi-threading utilities: ExecutorService, ConcurrentHashMap,
CountDownLatch, etc.
Examples
Example 1: Using [Link] (manually imported)
import [Link];
public class Demo
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link](names);
}
}
Example 2: Using [Link] (auto-imported)
public class MathExample
{
public static void main(String[] args)
{
double result = [Link](25); // Math comes from [Link]
[Link]("Square root: " + result);
}
}
How to View Java SE Packages
To see all standard Java SE packages:
• Check the Java SE API documentation:
Java SE 21 API Docs (latest LTS)
There you'll see all the packages organized alphabetically, with full class listings.
Package Naming Convention
Java SE packages follow a standard naming scheme:
• java. → Core Java packages
• javax. → Extension packages (older), e.g., [Link], [Link]
• Newer Java modules introduced via Jigsaw (Java 9+) also define packages by
modules, like:
o [Link] (core modules)
o [Link] (GUI-related)
o [Link] (database access)
4.1.6 [Link] Package and its Classes
The [Link] package is one of the most fundamental and commonly used packages in Java.
It provides core classes and interfaces that are essential for Java programming, such as those
for:
• Primitive data type wrappers
• String and Math operations
• System and Runtime interaction
• Object and Class
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
10
• Multithreading basics (Thread, Runnable)
• Exception handling
Automatically imported — no need to write import [Link].*;
Key Features of [Link]
• Built-in and always available
• Contains essential classes required for every Java program
• Supports object-oriented, multi-threaded, and exception-handling features
Common Classes in [Link]
Class Description
Object Root class of all Java classes
Class Represents classes and interfaces at runtime
String Immutable sequence of characters
StringBuilder Mutable sequence of characters (not thread-safe)
StringBuffer Thread-safe mutable sequence of characters
Math Basic math functions: abs(), sqrt(), pow(), random(), etc.
System Provides system-related utilities: in, out, err, exit()
Runtime Access to the JVM runtime environment
Thread Supports multi-threading
Runnable Interface for creating threads
Exception Base class for all exceptions
Throwable Superclass of Exception and Error
Error Serious problems not intended to be caught
Integer, Double, Boolean, etc. Wrapper classes for primitives
Enum Base class for all enumerations
CharSequence Interface for readable sequences of characters
Comparable<T> Interface for natural ordering of objects
Examples of Using [Link] Classes
Example 1: String, System, Math
public class Example1
{
public static void main(String[] args)
{
String name = "Java";
[Link]("Welcome to " + name);
int square = (int) [Link](5, 2);
[Link]("5 squared is: " + square);
}
}
Example 2: Integer (Wrapper Class)
public class WrapperExample
{
public static void main(String[] args)
{
int x = 10;
Integer boxed = [Link](x); // Boxing
int unboxed = [Link](); // Unboxing
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
11
[Link]("Boxed: " + boxed);
[Link]("Unboxed: " + unboxed);
}
}
Example 3: Thread and Runnable
class MyThread implements Runnable
{
public void run()
{
[Link]("Running in a thread");
}
public static void main(String[] args)
{
Thread t = new Thread(new MyThread());
[Link]();
}
}
Notes on [Link]
• You don't need to import it explicitly.
• Essential for OOP, exception handling, and core logic.
• Many classes are immutable and thread-safe, e.g., String.
Full List (Partial) of [Link] Classes
Class Name Use
AbstractMethodError Thrown when an abstract
method is called incorrectly
ArithmeticException Error in arithmetic operations
ArrayIndexOutOfBoundsException Invalid array indexing
Boolean, Byte, Character, Short, Integer, Long, Float, Wrapper classes
Double
IllegalArgumentException, NullPointerException, Common runtime exceptions
IllegalStateException, etc.
Thread, ThreadGroup Multi-threading control
SecurityManager Security policy enforcement
4.1.7 Class Object
In Java, the Object class is the root class of the class hierarchy. Every class in Java implicitly
extends [Link], unless it explicitly extends another class.
This means that every Java class is a subclass of Object.
Location:
package [Link];
Why Is Object Important?
• It defines common methods that all Java objects inherit.
• Enables Java to treat all objects polymorphically.
• Useful for features like:
o Collections (e.g., ArrayList<Object>)
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
12
o Reflection
o Generic programming
Key Methods of the Object Class
Method Signature Description
boolean equals(Object obj) Compares two objects for equality
int hashCode() Returns hash code of the object
String toString() Returns string representation of the object
Class<?> getClass() Returns the runtime class of the object
Object clone() Creates and returns a copy of the object (requires
Cloneable)
void finalize() Called by garbage collector before reclaiming object
(deprecated)
void notify() Wakes up a single thread waiting on this object
void notifyAll() Wakes up all threads waiting on this object
void wait() Causes current thread to wait until another thread calls
notify()
void wait(long timeout) Waits for a specified time
void wait(long timeout, int Waits for specific time and nanoseconds
nanos)
Example: equals(), hashCode(), toString()
public class Person
{
String name;
int age;
Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
// Override equals
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return [Link]([Link]) && [Link] == [Link];
}
// Override hashCode
@Override
public int hashCode()
{
return [Link]() + age;
}
// Override toString
@Override
public String toString()
{
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
13
return "Person{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args)
{
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
[Link]([Link](p2)); // true
[Link]([Link]()); // hash code
[Link]([Link]()); // Person{name='Alice', age=30}
}
}
Real Use Cases of Object
• Collections API: Most classes like ArrayList, HashMap store values as Object,
allowing any type.
• Polymorphism: You can treat all objects as Object and still access their overridden
methods.
• Reflection: Using getClass() to inspect objects at runtime.
• Equality checking: Proper implementation of equals() and hashCode() is vital for
objects stored in HashSet, HashMap, etc.
4.1.8 Enumeration
In Java, enum (short for enumeration) is a special data type that enables you to define a set of
named constants. It was introduced in Java 5 as part of the [Link] package.
What is an enum?
• An enum is used when you have a fixed set of constant values.
• Java enums are type-safe, meaning you can’t assign any value that is not predefined.
• Unlike in some other languages, Java enums are full-fledged classes and can have:
o Fields
o Methods
o Constructors
o Implement interfaces
Basic Example
enum Day
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY
}
Usage:
public class TestEnum
{
public static void main(String[] args)
{
Day today = [Link];
if (today == [Link]) {
[Link]("It's almost the weekend!");
}
}
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
14
Enum Features in Java
1. Enums are classes
You can add fields, methods, and even constructors.
public enum Level {
LOW(1), MEDIUM(2), HIGH(3);
private final int priority;
Level(int priority)
{
[Link] = priority;
}
public int getPriority()
{
return priority;
}
}
Usage:
public class EnumTest
{
public static void main(String[] args)
{
Level l = [Link];
[Link]("Priority: " + [Link]()); // Output: 3
}
}
2. Switch with Enums
Day day = [Link];
switch (day)
{
case MONDAY:
[Link]("Back to work!");
break;
case SATURDAY:
case SUNDAY:
[Link]("Weekend!");
break;
default:
[Link]("Midweek day.");
}
3. Iterating Over Enum Values
for (Day d : [Link]())
{
[Link](d);
}
4. Built-in Methods
All enums extend [Link] and inherit several useful methods:
Method Description
values() Returns an array of enum constants
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
15
valueOf(String) Converts a string to an enum constant
name() Returns the name of the enum constant
ordinal() Returns the position/index (starts at 0)
Example:
Day d = [Link]("MONDAY");
[Link]([Link]()); // Output: 0
When to Use Enums
Use enum when you need:
• A fixed set of constants (e.g., days, directions, states, levels)
• Better type safety than int or String constants
• Readable and maintainable code
• Constants with associated data or behavior
4.1.9 class Math
The Math class in Java is part of the [Link] package and provides mathematical functions
and constants. It contains static methods for performing basic numeric operations such as
exponentiation, logarithms, square roots, trigonometric calculations, and more.
Key Characteristics of Math Class
• All methods are static — no need to create an instance of Math.
• Provides common math functions that are fast and reliable.
• Contains important constants like [Link] and Math.E.
• [Link] has been part of Java since its earliest versions.
Package
package [Link];
Commonly Used Methods
Method Signature Description Example
static double abs(double a) Returns absolute value [Link](-5) → 5
static double sqrt(double a) Returns square root [Link](16) → 4
static double pow(double a, Calculates a^b [Link](2, 3) → 8
double b)
static double sin(double a) Trigonometric sine (radians) [Link]([Link]/2) → 1.0
static double cos(double a) Trigonometric cosine [Link](0) → 1.0
(radians)
static double tan(double a) Trigonometric tangent [Link](0) → 0.0
(radians)
static double log(double a) Natural logarithm (base e) [Link](Math.E) → 1
static double exp(double a) e raised to the power a [Link](1) → 2.71828...
static int max(int a, int b) Returns the max of two [Link](3, 7) → 7
numbers
static int min(int a, int b) Returns the min of two [Link](3, 7) → 3
numbers
static double random() Returns a double between 0.0 [Link]() → e.g.,
and 1.0 0.24352
static long round(double a) Rounds to the nearest long [Link](3.6) → 4
Example Usage
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
16
public class MathExample
{
public static void main(String[] args)
{
double a = -10.5;
double b = 3;
[Link]("Absolute value of a: " + [Link](a));
[Link]("Square root of b: " + [Link](b));
[Link]("2 raised to 3: " + [Link](2, 3));
[Link]("Max of a and b: " + [Link](a, b));
[Link]("Random number: " + [Link]());
[Link]("Rounded value of 3.7: " + [Link](3.7));
}
}
Output:
Absolute value of a: 10.5
Square root of b: 1.7320508075688772
2 raised to 3: 8.0
Max of a and b: 3.0
Random number: 0.645367857 (varies)
Rounded value of 3.7: 4
Notes
• Trigonometric functions use radians, not degrees. Use [Link]() and
[Link]() to convert.
• [Link]() returns a double ≥ 0.0 and < 1.0.
• For advanced math (like complex numbers, matrices), use external libraries like
Apache Commons Math or JScience.
4.1.10 Wrapper Classes
In Java, wrapper classes provide a way to use primitive data types (like int, char, boolean) as
objects. Each primitive type has a corresponding wrapper class in the [Link] package.
Why Wrapper Classes?
• Object required: Some Java APIs (like Collections) require objects, not primitives.
• Utility methods: Wrapper classes provide useful methods for converting, parsing,
etc.
• Autoboxing/unboxing: Java automatically converts between primitives and wrapper
objects.
• Immutable: Wrapper objects are immutable.
Primitive Types and Their Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
17
char Character
boolean Boolean
Common Features of Wrapper Classes
• Conversion: Convert primitives to String and vice versa.
• Parsing: Parse strings into primitives ([Link](), [Link](), etc.).
• Constants: Define constants like Integer.MAX_VALUE.
• Comparison: Methods like equals(), compareTo().
Example: Autoboxing and Unboxing
public class WrapperExample
{
public static void main(String[] args)
{
// Autoboxing: primitive to object
Integer obj = 100; // same as [Link](100)
// Unboxing: object to primitive
int num = obj; // same as [Link]()
[Link]("Object: " + obj);
[Link]("Primitive: " + num);
}
}
Parsing Strings to Primitives
public class ParsingExample
{
public static void main(String[] args)
{
String str = "123";
int num = [Link](str);
double d = [Link]("3.14");
boolean b = [Link]("true");
[Link](num); // 123
[Link](d); // 3.14
[Link](b); // true
}
}
Useful Wrapper Class Methods
Method Description
valueOf(String s) Returns wrapper object for string
parseInt(String s) Converts string to primitive int
toString() Converts wrapper object to string
compareTo(T other) Compares two wrapper objects
equals(Object obj) Checks equality
xxxValue() Converts wrapper to primitive (e.g., intValue())
Notes
• Immutability: Wrapper objects cannot be changed after creation.
• Caching: Some wrapper classes cache frequently used values (like Integer values
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
18
from -128 to 127) for performance.
• Use wrapper classes when you need objects instead of primitives, e.g., in Collections
(List<Integer>, not List<int>).
Summary
Aspect Detail
Purpose Wrap primitives as objects
Location [Link] package
Autoboxing/unboxing Automatic conversions
Useful in Collections Collections store objects only
Supports parsing Parse strings to primitives
4.1.11 Auto-boxing and Auto-unboxing
Java auto-boxing and auto-unboxing are automatic conversions between primitive types and
their corresponding wrapper classes.
What is Auto-boxing?
Auto-boxing is the automatic conversion of a primitive type to its corresponding wrapper class
object.
Example: converting int to Integer automatically.
int num = 10;
Integer obj = num; // Auto-boxing: int → Integer
Behind the scenes, Java does:
Integer obj = [Link](num);
What is Auto-unboxing?
Auto-unboxing is the reverse: automatically converting a wrapper class object back to its
primitive type.
Example: converting Integer to int automatically.
Integer obj = [Link](20);
int num = obj; // Auto-unboxing: Integer → int
Java does this behind the scenes:
int num = [Link]();
Example Demonstrating Both
public class AutoBoxingExample
{
public static void main(String[] args)
{
// Auto-boxing: primitive to wrapper
Integer boxed = 100; // equivalent to [Link](100)
// Auto-unboxing: wrapper to primitive
int primitive = boxed; // equivalent to [Link]()
[Link]("Boxed Integer: " + boxed);
[Link]("Primitive int: " + primitive);
// Using wrapper in expressions
int sum = boxed + 50; // boxed unboxed automatically, sum = 150
[Link]("Sum: " + sum);
}
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
19
Why Auto-boxing & Auto-unboxing Matter
• Makes coding easier and cleaner: no need for manual conversion.
• Simplifies working with Collections like List<Integer>.
• Enables primitives to be used in contexts where objects are required.
Caution Points
• Performance: Frequent boxing/unboxing can cause overhead and create many
temporary objects.
• NullPointerException risk: Auto-unboxing a null wrapper throws
NullPointerException.
Integer obj = null;
int num = obj; // Throws NullPointerException!
• Use with care in tight loops or performance-critical code.
Summary
Feature Description
Auto-boxing Primitive → Wrapper (automatic)
Auto-unboxing Wrapper → Primitive (automatic)
Introduced in Java 5
Helps with Cleaner code, Collections usage
Watch for Performance cost, NullPointerException
4.1.12 Java util Classes and Interfaces
The [Link] package is one of the most important packages in Java. It provides utility classes
and interfaces that support:
• Collections Framework (Lists, Sets, Maps, Queues)
• Date and Time utilities
• Random number generation
• Data structures
• String tokenizing
• Scanner for input parsing
• Concurrency utilities (in [Link])
Key Classes in [Link]
Class Description
ArrayList Resizable array implementation of List
LinkedList Doubly linked list implementation of List
HashSet Implementation of Set backed by a hash table
TreeSet Sorted Set implementation using a Red-Black tree
HashMap Key-value mapping backed by hash table
TreeMap Sorted Map implementation
Collections Utility class with static methods for collections
Arrays Utility class with static methods for arrays
Date Represents date and time (legacy, replaced by [Link])
Calendar For manipulating dates (legacy)
Scanner Input parsing utility (reading from input streams)
Random Generates pseudo-random numbers
StringTokenizer Splits strings into tokens (legacy)
Optional Container for optional values (Java 8+)
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
20
Properties Key-value pairs for configuration
Key Interfaces in [Link]
Interface Description
Collection Root interface for collections
List Ordered collection (allows duplicates)
Set Collection with no duplicates
SortedSet Set with sorted order
NavigableSet Extends SortedSet with navigation methods
Queue Collection designed for holding elements prior to processing
Deque Double-ended queue
Map Key-value mapping interface
SortedMap Map with sorted keys
NavigableMap Extends SortedMap with navigation methods
Iterator For iterating over collections
ListIterator Bidirectional iterator for lists
Comparator For custom ordering of objects
Enumeration Legacy interface for iterating over collections
Observer & Observable For implementing observer pattern (deprecated in Java 9+)
Simple Example: Using ArrayList and HashMap
import [Link];
import [Link];
public class UtilExample
{
public static void main(String[] args)
{
// List example
ArrayList<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Fruits: " + fruits);
// Map example
HashMap<String, Integer> ages = new HashMap<>();
[Link]("Alice", 30);
[Link]("Bob", 25);
[Link]("Ages: " + ages);
}
}
Notes
• [Link] is vast; for more advanced data structures and utilities, Java provides
subpackages like [Link] and [Link].
• Since Java 8, many [Link] interfaces support default methods and lambda expressions
(e.g., [Link]).
• Use [Link] package for date and time operations instead of legacy Date and
Calendar.
Summary Table
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
21
Category Examples
Collections List, Set, Map, Queue, and their implementations like ArrayList, HashSet,
HashMap
Utility classes Collections, Arrays, Random, Scanner
Legacy Date, Calendar, StringTokenizer
classes
Others Properties, Optional
4.1.13 Formatter Class
The Formatter class in Java (found in the [Link] package) is used to format strings in a flexible
and powerful way, similar to C's printf functionality.
Package and Purpose
package [Link];
• It provides support for formatted output.
• Can format text, numbers, dates, and more.
• Supports locale-specific formatting.
Key Features
• Uses format strings with format specifiers (%d, %s, %f, etc.).
• Allows formatting of numbers, strings, dates, booleans.
• Can write formatted output to various destinations:
o StringBuilder
o OutputStream
o File
• Supports locales for language-specific formatting.
Basic Usage Example
import [Link];
public class FormatterExample
{
public static void main(String[] args)
{
Formatter formatter = new Formatter();
String name = "Alice";
int age = 25;
double salary = 12345.678;
[Link]("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
[Link](formatter);
[Link](); // Always good practice to close Formatter
}
}
Output:
Name: Alice, Age: 25, Salary: 12345.68
Common Format Specifiers
Specifier Description Example
%d Decimal integer 100
%f Floating-point number 3.1415
%s String "Hello"
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
22
%c Character 'A'
%b Boolean true or false
%x Hexadecimal integer 0xFF
%e Scientific notation 1.23e+03
%n Platform-specific newline (newline character)
Formatting Flags and Width
You can control:
• Width: Minimum number of characters to be written.
• Precision: Number of digits after decimal for floating point.
• Flags: For padding, alignment, signs, etc.
Example:
[Link]("|%10s|%-10s|%010d|", "right", "left", 123);
Output:
| right|left |0000000123|
Using Formatter with Other Destinations
You can create a Formatter to write formatted output directly to:
• File:
try (Formatter fileFormatter = new Formatter("[Link]")) {
[Link]("Hello %s", "World");
}
• OutputStream:
Formatter outFormatter = new Formatter([Link]);
[Link]("Value: %d%n", 100);
Alternative: [Link]()
Formatter functionality is often used via the static method:
String formatted = [Link]("Hello %s, your score is %d", "Bob", 95);
[Link](formatted);
Summary
Feature Description
Package [Link]
Purpose Format strings with placeholders
Output targets StringBuilder, OutputStream, File
Common usage [Link](), [Link]()
Format specifiers %d, %f, %s, %c, %b, %x
4.1.14 Random Class
the Random class is part of the [Link] package and is used to generate pseudo-random
numbers of different types such as int, float, double, long, and boolean.
Importing the Random Class
import [Link];
Creating an Instance
Random rand = new Random();
Common Methods of Random Class
Method Description
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
23
nextInt() Returns a random int
nextInt(int bound) Returns a random int between 0 (inclusive) and bound (exclusive)
nextDouble() Returns a random double between 0.0 and 1.0
nextFloat() Returns a random float between 0.0 and 1.0
nextBoolean() Returns a random boolean (true or false)
nextLong() Returns a random long
Example: Basic Usage
import [Link];
public class RandomExample
{
public static void main(String[] args)
{
Random rand = new Random();
int randomInt = [Link](); // Any int
int randomIntBounded = [Link](100); // 0 to 99
double randomDouble = [Link](); // 0.0 to 1.0
boolean randomBoolean = [Link](); // true or false
[Link]("Random int: " + randomInt);
[Link]("Random int (0-99): " + randomIntBounded);
[Link]("Random double: " + randomDouble);
[Link]("Random boolean: " + randomBoolean);
}
}
Seeding the Random Generator
You can provide a seed to get reproducible results:
Random rand = new Random(12345); // Fixed seed
Using the same seed will always produce the same sequence of random numbers.
4.1.15 Time Package
In Java, handling time and date is done through the [Link] package, introduced in Java 8 as
part of the Date and Time API. It’s modern, thread-safe, and much better than the older
[Link] and [Link].
[Link] Package Overview
Here are the main classes you’ll use:
Class Description
LocalDate Represents a date (year, month, day) without time
LocalTime Represents a time (hour, minute, second, etc.) without date
LocalDateTime Combines date and time (no timezone)
ZonedDateTime Date and time with timezone
Instant A timestamp (machine-readable time)
Duration Time-based amount of time (e.g., "5 minutes")
Period Date-based amount of time (e.g., "2 years, 3 months")
DateTimeFormatter Formatting and parsing date-time objects
ZoneId Timezone ID (e.g., "Asia/Kolkata")
Basic Examples
1. Getting Current Date and Time
import [Link].*;
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
24
public class TimeExample
{
public static void main(String[] args)
{
LocalDate date = [Link](); // Current date
LocalTime time = [Link](); // Current time
LocalDateTime dateTime = [Link](); // Current date & time
ZonedDateTime zonedDateTime = [Link](); // With timezone
[Link]("Date: " + date);
[Link]("Time: " + time);
[Link]("DateTime: " + dateTime);
[Link]("ZonedDateTime: " + zonedDateTime);
}
}
Output:
Date: 2025-10-09
Time: [Link].995658700
DateTime: 2025-10-09T[Link].995658700
ZonedDateTime: 2025-10-09T[Link].996658800+05:30[Asia/Calcutta]
2. Creating Specific Dates and Times
import [Link].*;
public class TimeExample
{
public static void main(String[] args)
{
LocalDate birthday = [Link](2000, [Link], 15);
LocalTime meeting = [Link](14, 30);
[Link]("Birthday:"+birthday+"Meeting "+meeting);
}
}
Output:
Birthday:2000-01-15Meeting 14:30
3. Working with Durations and Periods
// Period (date-based difference)
import [Link].*;
public class TimeExample
{
public static void main(String[] args)
{
LocalDate startDate = [Link](2020, 1, 1);
LocalDate endDate = [Link]();
Period period = [Link](startDate, endDate);
[Link]("Period: " + period);
// Duration (time-based difference)
LocalTime t1 = [Link](9, 0);
LocalTime t2 = [Link](17, 30);
Duration duration = [Link](t1, t2);
[Link]("Duration in hours: " + [Link]());
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
25
}
Output:
Period: P5Y9M8D
Duration in hours: 8
4. Formatting and Parsing Dates
import [Link].*;
import [Link];
public class TimeExample
{
public static void main(String[] args)
{
LocalDateTime now = [Link]();
DateTimeFormatter formatter = [Link]("dd-MM-yyyy HH:mm");
String formatted = [Link](formatter);
[Link]("Formatted DateTime: " + formatted);
// Parsing
LocalDate parsedDate = [Link]("2025-09-21");
[Link]("Parsed date: " + parsedDate);
}
}
Output:
Formatted DateTime: 09-10-2025 06:13
Parsed date: 2025-09-21
5. Working with Time Zones
import [Link].*;
import [Link];
public class TimeExample
{
public static void main(String[] args)
{
ZoneId zone = [Link]("Asia/Kolkata");
ZonedDateTime indiaTime = [Link](zone);
[Link]("India Time: " + indiaTime);
}
}
Output:
India Time: 2025-10-09T[Link].737633700+05:30[Asia/Kolkata]
4.1.16 Class Instant ([Link])
The Instant class in Java represents a specific moment on the timeline in UTC (Coordinated
Universal Time). It is the machine-friendly representation of a timestamp and is typically used
when you need to represent an exact point in time.
Package: [Link]
Class: [Link]
Represents: An instant in UTC, precise down to the nanosecond.
Common Use Cases
• Storing timestamps (e.g., logging or audit events)
• Measuring time durations (like benchmarks)
• Converting to/from legacy [Link]
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
26
• Time comparisons and calculations
Basic Usage
1. Get Current Timestamp
import [Link];
public class InstantExample
{
public static void main(String[] args)
{
Instant now = [Link](); // Current UTC timestamp
[Link]("Current Instant: " + now);
}
}
Output:
Current Instant: 2025-09-21T[Link].123Z
2. Create Instant from Epoch
import [Link];
public class InstantExample
{
public static void main(String[] args)
{
Instant fromEpochSeconds = [Link](1630000000);
Instant fromEpochMilli = [Link](1630000000000L);
[Link](fromEpochSeconds);
[Link](fromEpochMilli);
}
}
Output:
2021-08-26T[Link]Z
2021-08-26T[Link]Z
3. Convert Instant to Date (Legacy)
import [Link];
import [Link];
public class InstantExample
{
public static void main(String[] args)
{
Instant instant = [Link]();
Date date = [Link](instant); // Instant → Date
[Link](date);
}
}Output:
Thu Oct 09 [Link] IST 2025
4. Convert Date to Instant
Date date = new Date();
Instant instant = [Link](); // Date → Instant
5. Add or Subtract Time
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
27
Instant now = [Link]();
Instant future = [Link](3600); // Add 1 hour
Instant past = [Link](60000); // Subtract 1 minute
6. Compare Instants
Instant a = [Link]();
Instant b = [Link](10);
[Link]([Link](b)); // true
[Link]([Link](b)); // false
4.1.17 Formatting for Date/Time in Java
In Java, formatting and parsing of dates and times is handled by the DateTimeFormatter class
from the [Link] package (Java 8 and above).
Class: [Link]
This class is used to:
• Format a LocalDate, LocalTime, or LocalDateTime to a string.
• Parse a string back into a date/time object.
1. Import Statement
import [Link];
2. Formatting Dates and Times
import [Link];
import [Link];
public class FormatExample
{
public static void main(String[] args)
{
LocalDateTime now = [Link]();
DateTimeFormatter formatter = [Link]("dd-MM-yyyy HH:mm:ss");
String formatted = [Link](formatter);
[Link]("Formatted DateTime: " + formatted);
}
}
Output Example:
Formatted DateTime: 21-09-2025 [Link]
3. Common Format Patterns
Pattern Output Example Description
yyyy 2025 Year
MM 09 Month (2-digit)
MMM Sep Short month name
MMMM September Full month name
dd 21 Day of month
E or EEE Sun Short day name
EEEE Sunday Full day name
HH 17 Hour (24-hour format)
hh 05 Hour (12-hour format)
mm 45 Minutes
ss 22 Seconds
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
28
a PM AM/PM
z UTC Time zone
4. Parsing a String into a Date
String dateString = "21-09-2025 [Link]";
DateTimeFormatter formatter = [Link]("dd-MM-yyyy HH:mm:ss");
LocalDateTime parsedDateTime = [Link](dateString, formatter);
[Link]("Parsed: " + parsedDateTime);
5. Built-in Formatters
You can also use predefined constants in DateTimeFormatter:
Formatter Example Output
DateTimeFormatter.ISO_DATE 2025-09-21
DateTimeFormatter.ISO_TIME [Link].123
DateTimeFormatter.ISO_DATE_TIME 2025-09-21T[Link].123
DateTimeFormatter.RFC_1123_DATE_TIME Sun, 21 Sep 2025 [Link] GMT
6. Formatting with Time Zones
import [Link];
import [Link];
import [Link];
public class ZonedFormatExample
{
public static void main(String[] args)
{
ZonedDateTime zonedNow = [Link]([Link]("Asia/Kolkata"));
DateTimeFormatter formatter = [Link]("dd MMM yyyy hh:mm a z");
String formatted = [Link](formatter);
[Link]("Zoned DateTime: " + formatted);
}
}
Output:
Zoned DateTime: 21 Sep 2025 06:15 PM IST
4.1.18 Temporal Adjusters Class
The TemporalAdjusters class in Java is a utility class that provides predefined date adjustments
for objects like LocalDate, ZonedDateTime, etc.
It is part of the Java 8 Date and Time API.
Package:
import [Link];
Purpose:
To adjust dates easily to values like:
• First day of month
• Last day of month
• Next or previous day of the week (e.g., next Friday)
• First or last day of the year
• Nth day of the week in a month (e.g., second Tuesday)
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
29
Basic Usage
import [Link];
import [Link];
import [Link];
public class AdjusterExample
{
public static void main(String[] args)
{
LocalDate today = [Link]();
LocalDate firstDayOfMonth = [Link]([Link]());
LocalDate lastDayOfMonth = [Link]([Link]());
LocalDate nextMonday =
[Link]([Link]([Link]));
LocalDate previousFriday =
[Link]([Link]([Link]));
[Link]("Today: " + today);
[Link]("First Day of Month: " + firstDayOfMonth);
[Link]("Last Day of Month: " + lastDayOfMonth);
[Link]("Next Monday: " + nextMonday);
[Link]("Previous Friday: " + previousFriday);
}
}
Common Temporal Adjusters
Method Description
firstDayOfMonth() Sets date to 1st of current month
lastDayOfMonth() Sets date to last day of current month
firstDayOfNextMonth() First day of the next month
firstDayOfYear() Sets date to Jan 1 of the same year
lastDayOfYear() Dec 31 of the same year
firstInMonth(DayOfWeek) First specific day (e.g., Monday) in the current
month
lastInMonth(DayOfWeek) Last specific day in the current month
next(DayOfWeek) Next occurrence of the given day
nextOrSame(DayOfWeek) Next or current day if today matches
previous(DayOfWeek) Previous occurrence of the given day
previousOrSame(DayOfWeek) Previous or current day if today matches
dayOfWeekInMonth(n, e.g., 2nd Monday in the month
DayOfWeek)
Example: Get the Second Friday of the Month
LocalDate secondFriday = [Link]()
.with([Link](2, [Link]));
[Link]("Second Friday: " + secondFriday);
Custom Temporal Adjuster
You can create your own custom adjusters using the TemporalAdjuster interface, but for most
real-world cases, TemporalAdjusters has everything you need.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
30
4.1.19 Temporal Adjusters Class
The TemporalAdjusters class (from [Link] package) provides static methods that
return common temporal adjusters, which are used to manipulate dates (e.g., adjust to first day
of the month, next Monday, last day of the year, etc.).
It works with date/time classes that implement the Temporal interface — like LocalDate,
ZonedDateTime, etc.
Package:
import [Link];
Depends On:
import [Link];
import [Link];
Commonly Used Static Methods
Method Description
firstDayOfMonth() Adjusts to the first day of the current month
lastDayOfMonth() Adjusts to the last day of the current month
firstDayOfNextMonth() Adjusts to the first day of the next month
firstDayOfYear() Adjusts to January 1st of the current year
lastDayOfYear() Adjusts to December 31st of the current year
firstInMonth(DayOfWeek) Adjusts to the first specified weekday in the month
lastInMonth(DayOfWeek) Adjusts to the last specified weekday in the month
next(DayOfWeek) Adjusts to the next occurrence of the given day
nextOrSame(DayOfWeek) Adjusts to the next or same given day
previous(DayOfWeek) Adjusts to the previous occurrence of the given day
previousOrSame(DayOfWeek) Adjusts to the previous or same given day
dayOfWeekInMonth(n, Adjusts to the nth occurrence of a weekday in the
DayOfWeek) month
Example: Basic Usage
import [Link];
import [Link];
import [Link];
public class TemporalAdjustersExample
{
public static void main(String[] args)
{
LocalDate today = [Link]();
LocalDate firstDayOfMonth = [Link]([Link]());
LocalDate lastDayOfMonth = [Link]([Link]());
LocalDate nextMonday =
[Link]([Link]([Link]));
LocalDate lastFriday =
[Link]([Link]([Link]));
LocalDate secondTuesday = [Link]([Link](2,
[Link]));
[Link]("Today: " + today);
[Link]("First day of month: " + firstDayOfMonth);
[Link]("Last day of month: " + lastDayOfMonth);
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
31
[Link]("Next Monday: " + nextMonday);
[Link]("Last Friday of month: " + lastFriday);
[Link]("Second Tuesday of month: " + secondTuesday);
}
}
How It Works
All of the TemporalAdjusters methods return an instance of TemporalAdjuster, which you
can use with:
[Link](adjuster)
This allows chaining or applying to any Temporal object like LocalDate.
Custom Temporal Adjuster (Advanced)
You can create your own adjusters by implementing TemporalAdjuster.
import [Link];
import [Link];
import [Link];
public class NextWorkingDayAdjuster implements TemporalAdjuster
{
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate date = [Link](temporal);
do
{
date = [Link](1);
} while ([Link]() == [Link] || [Link]()
== [Link]);
return date;
}
}
Usage:
LocalDate today = [Link]();
LocalDate nextWorkingDay = [Link](new NextWorkingDayAdjuster());
[Link]("Next Working Day: " + nextWorkingDay);
4.2 Exception Handling: Introduction
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
32
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions
1. Checked Exception: The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions [Link], SQLException etc. Checked exceptions are checked at
compile-time.
2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.
3. Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.
Hierarchy of Java Exception classes
Why Use Exception Handling?
• To gracefully handle errors
• To maintain normal program flow
• To provide useful error messages
• To avoid abnormal termination
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
33
method.
Java try block must be followed by either catch or finally block.
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only. You can use
multiple catch block with a single try.
Basic Syntax: try-catch Block
try
{
// Code that generate an exception
}
catch (ExceptionType name)
{
// Code to handle the exception
}
Example:
public class ExceptionExample
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 0;
int result = a / b; // will throw ArithmeticException
}
catch (ArithmeticException e)
{
[Link]("Error: Cannot divide by zero.");
}
}
}
Throwing Exceptions
You can throw exceptions manually using throw:
throw new ArithmeticException("Custom error message");
Using throws Keyword
Use throws to declare that a method might throw an exception:
Summary
Keyword Purpose
try Block where exception might occur
catch Handles the exception
finally Always executes (cleanup)
throw Manually throw an exception
throws Declares exceptions a method might throw
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
34
4.2.1 Hierarchy of Standard Exception Classes
In Java, all exceptions and errors are subclasses of the class:
[Link]
This is the root class for anything that can be thrown using the throw statement.
1. Top-Level Hierarchy
[Link]
└── [Link]
├── [Link] --> (for exceptions you can catch)
│ ├── Checked Exceptions
│ └── Unchecked Exceptions (RuntimeException)
└── [Link] --> (serious system-level errors)
2. Detailed Exception Class Hierarchy
Throwable
• The superclass of all errors and exceptions.
Exception (Can be caught and handled)
a. Checked Exceptions
(Must be declared in method signature using throws or handled with try-catch)
Examples:
[Link]
├── IOException
│ ├── FileNotFoundException
│ └── EOFException
├── SQLException
├── ParseException
├── ClassNotFoundException
├── InterruptedException
└── InvocationTargetException
b. Unchecked Exceptions (RuntimeException)
(Do not need to be declared or caught)
Examples:
[Link]
├── ArithmeticException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
├── StringIndexOutOfBoundsException
├── IllegalArgumentException
│ └── NumberFormatException
├── IllegalStateException
├── ClassCastException
└── UnsupportedOperationException
Error (Serious issues that are not meant to be caught by your program)
Examples:
[Link]
├── OutOfMemoryError
├── StackOverflowError
├── VirtualMachineError
│ ├── InternalError
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
35
│ └── UnknownError
├── AssertionError
└── LinkageError
├── ClassCircularityError
├── ClassFormatError
└── NoClassDefFoundError
Summary Table
Type Subclass of Checked? Typical Causes
Throwable Object – Anything that can be thrown
Exception Throwable Application-level issues
RuntimeException Exception Programming errors (e.g., nulls)
Error Throwable JVM/internal problems
Visual Summary (Simplified)
Throwable
├── Exception (recoverable)
│ ├── IOException
│ ├── SQLException
│ └── RuntimeException (program bugs)
│ ├── NullPointerException
│ ├── ArithmeticException
│ └── IndexOutOfBoundsException
└── Error (unrecoverable)
├── OutOfMemoryError
└── StackOverflowError
4.2.2 Keywords throws and throw, try, catch, and finally Blocks
Java provides robust exception handling using five main keywords:
1. try Block
Used to wrap the code that might throw an exception.
try {
// risky code here
}
2. catch Block
Used to handle the exception thrown in the try block.
try
{
int x = 5 / 0;
}
catch (ArithmeticException e)
{
[Link]("Cannot divide by zero.");
}
You can use multiple catch blocks to handle different types of exceptions.
3. finally Block
Used to execute code regardless of whether an exception occurred or not. Typically used for
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
36
clean-up, like closing files or connections.
Syntax
try
{
// risky code
}
catch (Exception e)
{
// handle
}
finally
{
[Link]("Cleanup code here.");
}
Example:
try
{
int[] arr = {1, 2};
[Link](arr[5]); // will throw exception
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Index error!");
}
finally
{
[Link]("This block always runs.");
}
4. throw Keyword
Used to manually throw an exception.
Syntax
public void readFile() throws IOException
{
// code that might throw IOException
}
throw new ArithmeticException("Custom divide by zero message");
You can throw only one exception at a time using throw.
5. throws Keyword
Used in a method declaration to declare the exceptions that the method might throw.
public void readFile(String filename) throws IOException
{
// code that might throw IOException
}
You can declare multiple exceptions with throws:
public void connect() throws IOException, SQLException
{
// ...
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
37
}
Example:
import [Link].*;
class Main {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("[Link]");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
[Link](e);
}
}
}
Output:
[Link]: [Link] (No such file or directory)
Example Using All Keywords
import [Link].*;
public class ExceptionDemo
{
public static void riskyMethod() throws IOException
{
throw new IOException("File not found!");
}
public static void main(String[] args)
{
try
{
riskyMethod();
}
catch (IOException e)
{
[Link]("Caught Exception: " + [Link]());
}
finally
{
[Link]("Finally block executed.");
}
}
}
Summary Table
Keyword Use
try Wraps code that may throw an exception
catch Handles the exception
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
38
finally Executes cleanup code regardless of what happens
throw Manually throws an exception
throws Declares exceptions a method might throw
Difference Between throw and throws
throw throws
Used to actually throw an exception Used to declare an exception in method signature
Can throw one exception at a time Can declare multiple exceptions
Used inside a method Used in method declaration
Example: throw new IOException(); Example: void read() throws IOException
4.2.3 Multiple Catch Clauses
Java allows you to use multiple catch blocks to handle different types of exceptions that may
occur within a single try block.
This helps make your code more robust and organized, especially when you're expecting
multiple potential error types.
Syntax of Multiple Catch Blocks
try
{
// Code that might throw multiple exceptions
}
catch (ExceptionType1 e1)
{
// Handle ExceptionType1
}
catch (ExceptionType2 e2)
{
// Handle ExceptionType2
}
catch (Exception e)
{
// Handle all other exceptions (generic handler)
}
Example: Multiple Catch Clauses
public class MultiCatchExample
{
public static void main(String[] args)
{
try
{
int[] numbers = {1, 2, 3};
[Link](numbers[5]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Array index is invalid!");
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
39
catch (ArithmeticException e)
{
[Link]("Cannot divide by zero!");
}
catch (Exception e)
{
[Link]("General exception: " + e);
}
}
}
Output:
Array index is invalid!
Note: Once an exception is caught, the remaining catch blocks are skipped.
Important Rules
1. Order Matters
Place more specific exceptions first, and more general ones (like Exception) last.
2. // WRONG — will cause compile-time error
3. catch (Exception e) { }
4. catch (ArithmeticException e) { } // Unreachable
5. Only one catch block executes per try
As soon as an exception is caught, the rest of the catch blocks are skipped.
6. Optional finally block
You can optionally add a finally block after multiple catch blocks.
Java 7+ Feature: Multi-Catch (Single catch for multiple exceptions)
If different exception types have similar handling logic, you can combine them:
try
{
// risky code
}
catch (IOException | SQLException e)
{
[Link]("IO or SQL Exception occurred: " + [Link]());
}
In multi-catch, the exception variable e is implicitly final — you cannot reassign it.
Summary
Feature Description
Multiple catch blocks Handle different exceptions individually
Catch block order Specific → General (compile-time rule)
One catch per exception Only one is executed for each exception
Multi-catch (` `)
4.2.4 Class Throwable
Throwable is the superclass of all errors and exceptions in Java. Any object that can be thrown
using the throw statement must be a subclass of Throwable.
Package
[Link]
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
40
Overview
• Throwable is the root class for:
o Error (serious JVM problems)
o Exception (conditions your program might want to catch)
• It provides methods to inspect, print, and manage exceptions and errors.
• Objects of type Throwable can be caught by catch blocks.
Hierarchy (simplified)
[Link]
└── [Link]
├── [Link]
└── [Link]
└── [Link]
Key Methods of Throwable
Method Description
getMessage() Returns detailed message about the exception.
printStackTrace() Prints the stack trace to standard error.
getCause() Returns the cause of the throwable (another Throwable).
initCause(Throwable cause) Initializes the cause (for chaining).
toString() Returns a short description of the throwable.
Basic Usage Example
try
{
int result = 10 / 0; // Throws ArithmeticException
}
catch (Throwable t)
{
[Link]("Caught throwable: " + t);
[Link]();
}
Important Notes
• Generally, you catch Exception or its subclasses, not Throwable directly.
• Catching Throwable also catches Errors, which are usually not meant to be handled
(e.g., OutOfMemoryError).
• Use Throwable mainly when writing very generic exception handling, like in
frameworks or top-level error handlers.
Summary
Feature Description
Class [Link]
Role Base class of all errors/exceptions
Subclasses Error, Exception
Typical use Represents throwable conditions
Catchable Yes, but catching Errors is discouraged
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
41
4.2.5 Unchecked Exceptions
What are Unchecked Exceptions?
• Unchecked exceptions are exceptions that do not need to be declared or caught
explicitly.
• They occur during runtime and usually represent programming errors.
• These exceptions are subclasses of RuntimeException.
Key Points
Feature Description
Superclass [Link]
Checked/Unchecked Unchecked (no compile-time checking)
Typical Causes Bugs like logic errors, improper use of API
Must handle? No, but can be caught if desired
Common Examples NullPointerException, ArithmeticException,
ArrayIndexOutOfBoundsException
Common Unchecked Exceptions
Exception Cause
NullPointerException Accessing a method or field of a null object
ArithmeticException Illegal arithmetic, e.g., divide by zero
ArrayIndexOutOfBoundsException Accessing array elements outside valid index
IllegalArgumentException Passing illegal or inappropriate argument
ClassCastException Invalid casting of objects
Example: Unchecked Exception in Action
public class UncheckedExample
{
public static void main(String[] args)
{
String str = null;
[Link]([Link]()); // Throws NullPointerException at runtime
}
}
• The above code compiles fine but throws an exception at runtime.
Why Unchecked Exceptions?
• They represent programmer mistakes that should be fixed, not forced to be handled.
• Checking them at compile-time would clutter code with unnecessary try-catch.
• Java runtime lets you decide if you want to handle or let the program crash.
Difference Between Checked and Unchecked Exceptions
Aspect Checked Exception Unchecked Exception
Subclass of Exception (except RuntimeException
RuntimeException)
Compile-time Yes, must be caught or declared No
check
Cause Recoverable errors (e.g., IO Programming bugs (null refs,
failure) logic)
Handling Yes Optional
required?
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
42
4.2.6 Checked Exceptions
What are Checked Exceptions?
• Checked exceptions are exceptions that must be either caught or declared in the method
signature using the throws keyword.
• These exceptions are checked at compile time by the Java compiler.
• They usually represent recoverable conditions outside the program’s control (e.g., file
not found, network errors).
Key Points
Feature Description
Superclass [Link] (except RuntimeException and its subclasses)
Checked/Unchecked Checked (compile-time checking)
Must handle? Yes — either with try-catch or throws declaration
Typical Causes External conditions like I/O failures, missing files, invalid data
Examples IOException, SQLException, ClassNotFoundException
Example: Handling a Checked Exception
import [Link];
import [Link];
public class CheckedExceptionExample
{
public static void main(String[] args)
{
try
{
FileReader reader = new FileReader("[Link]"); // May throw FileNotFoundException
[Link]();
}
catch (IOException e)
{
[Link]("I/O error occurred: " + [Link]());
}
}
}
Declaring Checked Exceptions with throws
You can declare that a method throws a checked exception:
import [Link];
import [Link];
public class CheckedExceptionExample
{
public void readFile() throws IOException
{
FileReader reader = new FileReader("[Link]");
[Link]();
}
public static void main(String[] args)
{
CheckedExceptionExample example = new CheckedExceptionExample();
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
43
try
{
[Link]();
}
catch (IOException e)
{
[Link]("Caught IOException: " + [Link]());
}
}
}
Common Checked Exceptions
Exception Description
IOException General input/output failure
FileNotFoundException File to be read is missing
SQLException Database access errors
ClassNotFoundException Class not found dynamically
InterruptedException Thread interrupted during sleep/wait
Why Use Checked Exceptions?
• Force the programmer to handle exceptional conditions that can reasonably be
anticipated and recovered from.
• Encourage better error handling and more robust applications.
Summary Table
Aspect Checked Exception
Compile-time check Yes
Must handle? Yes, either try-catch or throws
Subclass of Exception (excluding RuntimeException)
Typical use cases I/O errors, database errors, missing files
4.3 Java I/O and File:
Java provides a powerful set of Input/Output (I/O) APIs in the [Link] and [Link] packages to
perform reading and writing of data to different sources like files, memory, network, etc.
Key Concepts:
• InputStream / OutputStream — for handling byte streams (binary data)
• Reader / Writer — for handling character streams (text data)
• File — represents file and directory pathnames
The [Link] Class
• Represents files and directories in the filesystem.
• Can be used to create, delete, check existence, get properties of files/folders.
Package
[Link]
Key Methods of File
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
44
Method Description
exists() Checks if file/directory exists
createNewFile() Creates a new empty file
mkdir() / mkdirs() Creates directory or directories
delete() Deletes file or directory
getName() Returns the file/directory name
getPath() Returns the path string
isFile() Checks if it’s a file
isDirectory() Checks if it’s a directory
length() Returns file size in bytes
listFiles() Lists files/directories in a directory
4.3.1 Java I/O API
Java I/O (Input/Output) API provides classes and interfaces to perform input and output
operations, such as reading from or writing to files, memory, network connections, and more.
Core Concepts
• Streams — Represent a continuous flow of data.
• Byte Streams — Handle raw binary data.
• Character Streams — Handle characters and support Unicode.
• Readers and Writers — For character streams.
• InputStream and OutputStream — For byte streams.
Package Structure
Package Purpose
[Link] Basic I/O classes (Streams, File, etc.)
[Link] New I/O (buffered, non-blocking I/O)
[Link] File and file system interfaces
Byte Stream Classes (Raw Binary)
Class Description Direction
InputStream Abstract superclass for byte input Read
OutputStream Abstract superclass for byte output Write
FileInputStream Reads bytes from a file Read
FileOutputStream Writes bytes to a file Write
BufferedInputStream Buffers input bytes for efficiency Read
BufferedOutputStream Buffers output bytes for efficiency Write
Character Stream Classes (Text Data)
Class Description Direction
Reader Abstract superclass for character input Read
Writer Abstract superclass for character output Write
FileReader Reads characters from a file Read
FileWriter Writes characters to a file Write
BufferedReader Buffers characters for efficiency Read
BufferedWriter Buffers characters for efficiency Write
Key Interfaces
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
45
Interface Purpose
Closeable Supports closing stream/resources
Flushable Supports flushing buffered data
Serializable Supports object serialization
Example: Reading a File with BufferedReader
import [Link];
import [Link];
import [Link];
public class BufferedReaderExample
{
public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null)
{
[Link](line);
}
}
catch (IOException e)
{
[Link]();
}
}
}
Example: Writing a File with BufferedWriter
import [Link];
import [Link];
import [Link];
public class BufferedWriterExample
{
public static void main(String[] args)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]")))
{
[Link]("Hello, Java I/O!");
[Link]();
[Link]("Writing to a file using BufferedWriter.");
}
catch (IOException e)
{
[Link]();
}
}
}
Java NIO (New I/O)
• Introduced in Java 7.
• Provides non-blocking I/O and efficient buffer management.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
46
• Classes: Path, Files, ByteBuffer, Channels, etc.
Example reading all lines from a file:
import [Link];
import [Link];
import [Link];
import [Link];
public class NIOExample
{
public static void main(String[] args)
{
try
{
List<String> lines = [Link]([Link]("[Link]"));
[Link]([Link]::println);
}
catch (IOException e)
{
[Link]();
}
}
}
Summary
Category Stream Type Example Classes
Byte Streams InputStream/OutputStream FileInputStream, BufferedOutputStream
Character Streams Reader/Writer FileReader, BufferedWriter
New I/O (NIO) Buffer and Channels Path, Files, ByteBuffer
4.3.2 standard I/O streams, types
Java provides standard input/output streams as part of the [Link] class to interact
with the console or terminal.
Standard Streams in Java
Stream Description Type (Class)
[Link] Standard input stream (keyboard input) InputStream
[Link] Standard output stream (console output) PrintStream
[Link] Standard error output stream (error messages) PrintStream
Details About Each Stream
[Link]
• Used to read input from the keyboard.
• Type: InputStream (byte stream).
• Often wrapped in InputStreamReader and BufferedReader or Scanner to read text or
formatted input.
Example reading from [Link] using Scanner:
import [Link];
public class InputExample
{
public static void main(String[] args)
{
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
47
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
[Link]();
}
}
[Link]
• Used for standard output (usually console).
• Type: PrintStream.
• Provides convenient methods like print(), println(), and printf().
Example:
[Link]("Hello, World!");
[Link]("Age: %d\n", 25);
[Link]
• Used for error output.
• Also of type PrintStream.
• Useful for printing error messages or logging errors separately from standard output.
• By default, [Link] and [Link] print to the console but can be redirected
separately.
Example:
[Link]("This is an error message.");
Summary Table
Stream Direction Type Usage
[Link] Input InputStream Reading user input
[Link] Output PrintStream Standard output (console)
[Link] Output PrintStream Error messages
Wrapping [Link] for Character Input
Since [Link] is a byte stream, it's common to wrap it for easier text input:
import [Link];
import [Link];
import [Link];
public class BufferedReaderInput
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter something: ");
String input = [Link]();
[Link]("You typed: " + input);
}
}
4.3.3 Byte streams
What are Byte Streams?
• Byte streams provide a way to read and write raw binary data (bytes).
• They are useful for handling all kinds of data — text files, images, audio, video, etc.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
48
• Byte streams work at the lowest level, dealing with 8-bit bytes.
Key Classes in [Link] for Byte Streams
Class Description Direction
InputStream Abstract base class for reading bytes Read
OutputStream Abstract base class for writing bytes Write
FileInputStream Reads bytes from a file Read
FileOutputStream Writes bytes to a file Write
BufferedInputStream Buffers input bytes for efficiency Read
BufferedOutputStream Buffers output bytes for efficiency Write
DataInputStream Reads primitive data types from stream Read
DataOutputStream Writes primitive data types to stream Write
How Byte Streams Work
• InputStream and OutputStream are abstract classes.
• You work with their concrete subclasses like FileInputStream, FileOutputStream.
• Operations happen at the byte level (int read(), void write(int b)).
Basic Example: Reading and Writing Bytes
Writing bytes to a file
import [Link];
import [Link];
public class ByteStreamWrite
{
public static void main(String[] args)
{
String data = "Hello Byte Stream!";
try (FileOutputStream fos = new FileOutputStream("[Link]"))
{
byte[] bytes = [Link](); // Convert string to bytes
[Link](bytes);
[Link]("Data written successfully.");
}
catch (IOException e)
{
[Link]();
}
}
}
Reading bytes from a file
import [Link];
import [Link];
public class ByteStreamRead
{
public static void main(String[] args)
{
try (FileInputStream fis = new FileInputStream("[Link]"))
{
int b;
while ((b = [Link]()) != -1)
{ // Read byte by byte
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
49
[Link]((char) b);
}
}
catch (IOException e)
{
[Link]();
}
}
}
Buffered Byte Streams
• For better performance, wrap streams in buffered variants.
• Buffers reduce the number of physical read/write operations.
Example with BufferedInputStream and BufferedOutputStream:
import [Link].*;
public class BufferedByteStreamExample
{
public static void main(String[] args)
{
try (BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("[Link]"));
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("[Link]")))
{
String text = "Buffered Byte Stream Example!";
[Link]([Link]());
[Link]();
int data;
while ((data = [Link]()) != -1)
{
[Link]((char) data);
}
}
catch (IOException e)
{
[Link]();
}
}
}
Summary Table
Class Purpose
InputStream Abstract byte input stream
OutputStream Abstract byte output stream
FileInputStream Read bytes from a file
FileOutputStream Write bytes to a file
BufferedInputStream Buffer reads to improve speed
BufferedOutputStream Buffer writes to improve speed
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
50
4.3.4 Character streams
What are Character Streams?
• Character streams handle text data (characters) using Unicode.
• They work with 16-bit char units, which makes them ideal for reading/writing text
files.
• Built on top of byte streams but abstract away encoding details.
Key Classes in [Link] for Character Streams
Class Description Direction
Reader Abstract base class for reading characters Read
Writer Abstract base class for writing characters Write
FileReader Reads characters from a file Read
FileWriter Writes characters to a file Write
BufferedReader Buffers characters for efficient reading and provides Read
readLine() method
BufferedWriter Buffers characters for efficient writing Write
PrintWriter Writes formatted text output Write
Why Use Character Streams?
• Automatically handle character encoding and decoding.
• Support for Unicode makes them suitable for internationalization.
• Provide convenient methods like readLine() to read text line by line.
Basic Example: Writing Characters to a File
import [Link];
import [Link];
public class CharacterStreamWrite
{
public static void main(String[] args)
{
try (FileWriter writer = new FileWriter("[Link]"))
{
[Link]("Hello Character Stream!\n");
[Link]("Writing text is simple.");
[Link]("Data written successfully.");
}
catch (IOException e)
{
[Link]();
}
}
}
Basic Example: Reading Characters from a File
import [Link];
import [Link];
public class CharacterStreamRead
{
public static void main(String[] args)
{
try (FileReader reader = new FileReader("[Link]"))
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
51
{
int ch;
while ((ch = [Link]()) != -1)
{
[Link]((char) ch);
}
}
catch (IOException e)
{
[Link]();
}
}
}
Using BufferedReader for Efficient Reading
BufferedReader lets you read lines conveniently with readLine():
import [Link];
import [Link];
import [Link];
public class BufferedReaderExample
{
public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("[Link]")))
{
String line;
while ((line = [Link]()) != null)
{
[Link](line);
}
}
catch (IOException e)
{
[Link]();
}
}
}
Using BufferedWriter for Efficient Writing
BufferedWriter buffers data before writing, improving efficiency:
import [Link];
import [Link];
import [Link];
public class BufferedWriterExample
{
public static void main(String[] args)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]", true))) {
[Link]("\nAppended using BufferedWriter.");
[Link]();
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
52
catch (IOException e)
{
[Link]();
}
}
}
Summary Table
Class Purpose Notes
Reader Abstract character input stream Base class for all readers
Writer Abstract character output stream Base class for all writers
FileReader Reads characters from a file Simple, default charset
FileWriter Writes characters to a file Simple, default charset
BufferedReader Buffered reading, line-based Efficient, provides readLine()
BufferedWriter Buffered writing Efficient, buffers output
PrintWriter Formatted text output Supports print, println, printf
4.3.5 Scanner class
What is the Scanner Class?
• The Scanner class, part of [Link] package, is a simple text scanner used to parse
primitive types and strings using regular expressions.
• Commonly used for reading input from the console, files, or other input streams.
• Provides easy methods to read various data types (int, double, String, etc.).
Package
import [Link];
Creating a Scanner
Scanner scanner = new Scanner([Link]); // For console input
You can also create a Scanner for:
• Reading from a file:
Scanner fileScanner = new Scanner(new File("[Link]"));
• Reading from a String:
Scanner stringScanner = new Scanner("1 2 3 4 5");
Key Methods of Scanner
Method Description
next() Reads the next token (word)
nextLine() Reads the entire line
nextInt() Reads the next integer
nextDouble() Reads the next double
hasNext() Returns true if there is another token
hasNextInt() Returns true if next token is an int
close() Closes the scanner and underlying resource
Example: Reading User Input from Console
import [Link];
public class ScannerExample
{
public static void main(String[] args)
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
53
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]();
}
}
Example: Reading Numbers from a File
import [Link];
import [Link];
import [Link];
public class FileScannerExample
{
public static void main(String[] args)
{
try
{
Scanner scanner = new Scanner(new File("[Link]"));
while ([Link]()) {
int number = [Link]();
[Link]("Read number: " + number);
}
[Link]();
}
catch (FileNotFoundException e)
{
[Link]();
}
}
}
Notes
• Scanner uses whitespace as the default delimiter but you can change it using
useDelimiter() method.
• Always close the Scanner to release the underlying resources (like files or input
streams).
• Useful for quick and easy parsing of input data.
4.3.6 Files in Java(Text Book 2)
Java provides multiple ways to work with files—reading from and writing to files, checking
file properties, creating and deleting files, and more.
The [Link] Class
• Represents a file or directory path in the filesystem.
• Does not handle file contents; it’s just a path abstraction.
• You can use it to check if a file exists, create or delete files/directories, get file info
(name, size), and list directory contents.
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
54
Example: Basic File Operations
import [Link];
import [Link];
public class FileDemo
{
public static void main(String[] args)
{
File file = new File("[Link]");
// Check if file exists
if ([Link]())
{
[Link]("File exists: " + [Link]());
[Link]("File size: " + [Link]() + " bytes");
}
else
{
[Link]("File does not exist, creating...");
try
{
boolean created = [Link]();
if (created)
{
[Link]("File created successfully.");
}
}
catch (IOException e)
{
[Link]("Error creating file.");
[Link]();
}
}
}
}
Reading Text Files in Java
Using BufferedReader and FileReader
• Efficient way to read text files line by line.
• BufferedReader buffers input for efficiency and provides readLine() method.
import [Link];
import [Link];
import [Link];
public class ReadFileExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
55
}
}
}
Writing Text Files in Java
Using BufferedWriter and FileWriter
• BufferedWriter buffers output, improving performance.
• Use write() to write strings, and newLine() for new lines.
import [Link];
import [Link];
import [Link];
public class WriteFileExample
{
public static void main(String[] args)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]")))
{
[Link]("Hello, Java file handling!");
[Link]();
[Link]("This is written using BufferedWriter.");
}
catch (IOException e)
{
[Link]();
}
}
}
Using [Link] (Since Java 7)
• Modern, easier way to read and write files.
• Provides many utility methods.
Reading All Lines at Once
import [Link];
import [Link];
import [Link];
import [Link];
public class NIOReadExample
{
public static void main(String[] args)
{
Try
{
List<String> lines = [Link]([Link]("[Link]"));
for (String line : lines)
{
[Link](line);
}
}
catch (IOException e)
{
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA
56
[Link]();
}
}
}
Writing Lines to a File
import [Link];
import [Link];
import [Link];
import [Link];
public class NIOWriteExample
{
public static void main(String[] args)
{
try
{
[Link]([Link]("[Link]"), [Link]("First line", "Second line"));
[Link]("File written successfully.");
}
catch (IOException e)
{
[Link]();
}
}
}
Checking File Properties
You can use File methods:
Method Description
exists() Checks if file/directory exists
isFile() Checks if it is a file
isDirectory() Checks if it is a directory
length() Returns file size in bytes
getName() Returns file name
getAbsolutePath() Returns full path
Deleting and Renaming Files
File file = new File("[Link]");
if ([Link]())
{
[Link]("File deleted successfully.");
}
else
{
[Link]("Failed to delete file.");
}
File newFile = new File("[Link]");
boolean renamed = [Link](newFile);
if (renamed) {
[Link]("File renamed successfully.");
}
Dr. [Link] REDDY SRIT,Proddatur OOPS Through JAVA