KEMBAR78
OOPS Through JAVA - Unit4 | PDF | Class (Computer Programming) | Library (Computing)
0% found this document useful (0 votes)
32 views119 pages

OOPS Through JAVA - Unit4

Uploaded by

Gousejan Shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views119 pages

OOPS Through JAVA - Unit4

Uploaded by

Gousejan Shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

BYTEXL

Unit 4
Packages and Java Library, Exception Handling,
Java I/O and File
Introduction to Packages

Definition:
In Java, packages are used to group related classes and interfaces. They help to organize the code into
manageable sections and avoid naming conflicts.

What is a Package in Java?

In Java, a package is essentially a directory structure used to group related classes, interfaces, and sub-
packages based on their functionality. It provides an organized way to manage your code and makes it easier
to locate and use different components. Java includes several built-in packages, such as java.lang, java.util,
java.io, and java.net, each designed to categorize and manage related functionality systematically.

Real-Life Analogy of Packages in Java

Consider how you organize files on your computer: you might create separate folders for movies, music, or
games. Similarly, in Java, a package acts like a library where classes and interfaces are grouped. Each package
is like a category in the library, and its classes and interfaces are akin to books that can be referenced and
reused as needed. This organization simplifies programming by making code reuse more straightforward and
maintaining clarity within a project.

When developing software in Java, you may work with hundreds or thousands of classes and interfaces. To
keep things manageable, these elements are grouped into packages with meaningful names, facilitating easier
reuse and better organization across different programs.

Advantages of Using Packages in Java

1. Maintenance: Packages help maintain code by grouping related files together. This structure allows new
developers to quickly locate and work with the necessary files.
2. Reusability: Common code can be placed in a shared package, making it accessible to all developers and
projects that need it.
3. Name Conflict Resolution: Packages resolve naming conflicts by keeping classes with the same name in
different packages. For example, Student.java in stdPack1 and Student.java in stdPack2 are distinct due to
their package names.
4. Organization: Packages help keep files organized within a project, making the codebase more
manageable.
5. Access Protection: Packages provide access control by limiting the visibility of class members to other
elements within the same package, enhancing security and encapsulation.

Types of Packages in Java

Java offers two main types of packages:

1. User-Defined Packages: Created by developers to organize their own classes and interfaces.
2. Built-In Packages: Predefined by Java, such as java.lang, java.util, java.io, and java.net.
Built-in Packages
Built-in packages are pre-existing Java packages provided with the Java Development Kit (JDK). These packages
include classes and interfaces that help in various programming tasks. Some commonly used built-in packages
are java.lang, java.util, and java.io.

Example: Using java.util Package

import java.util.HashMap;

class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apples", 10);
map.put("Bananas", 5);
map.put("Oranges", 8);

System.out.println(map);
}
}

Output:

{Apples=10, Bananas=5, Oranges=8}

In this example, the HashMap class from the java.util package is used to store and manage a collection of key-
value pairs. To use HashMap, we import the java.util package with the import statement:

import java.util.HashMap;
User-defined Packages
Java allows you to create your own packages, known as user-defined packages. These packages help you
organize your classes and interfaces into a logical structure, making it easier to manage and avoid name
conflicts.

How to Define a Java Package


1. Create a Directory Structure:

• Packages correspond to directories in the file system. For example, if you want to create a package named
com.example.myapp, your directory structure should look like this:
└── com
└── example
└── myapp
└── MyClass.java

2. Package Statement:

• At the beginning of your Java source file, include a package statement to declare the package to which the
class belongs.

package com.example.myapp;

public class MyClass {


public static void main(String[] args) {
System.out.println("Welcome to the custom package!");
}
}

Output:

Welcome to the custom package!

In this example, the MyClass class belongs to the com.example.myapp package. To ensure the class is correctly
placed in this package, the package statement must match the directory structure.

Package Naming Conventions

• Package names should be unique and follow a specific naming convention to avoid conflicts. A common
practice is to use a reversed domain name structure. For example, if your domain is example.com, your
package might be com.example.

• Example Directory Structure for Package Naming:

└── com
└── example
└── utilities
└── UtilityClass.java

UtilityClass.java:

package com.example.utilities;

public class UtilityClass {


public static void displayMessage() {
System.out.println("This is a utility class.");
}
}
Defining Packages

User-Defined Java Packages


User-defined packages in Java are a powerful way to group related classes, interfaces, and other types into a
single namespace. This organization helps in avoiding naming conflicts, managing access control, and
improving code maintainability. Here’s how you can define and use packages in Java:

Creating a Java Package


1. Package Statement:
To define a package, include a package statement at the top of your source file. This statement should be the
first line in the file and applies to all types within the file.

Example:
package library;
This declares that all classes, interfaces, and types in the file belong to the library package.

2. Source File Structure:

If no package statement is included, the classes and interfaces are placed in the default package.
Example Source File:

package library;

public class Book {


private String title;

public Book(String title) {


this.title = title;
}

public String getTitle() {


return title;
}
}

Compiling with Java Packages


To compile Java files with package statements, use the -d option with the javac command to specify the
destination directory for compiled class files. This command ensures the directory structure reflects the
package hierarchy.

Command:

javac -d Destination_folder FileName.java

Explanation: This compiles the source files and places the resulting class files into the directory structure
corresponding to the package names.
Example of Creating and Using a Java Package
1. Define a Package:

Class Definition in Package library:


/* File name: Book.java */
package library;

public class Book {


private String title;

public Book(String title) {


this.title = title;
}

public String getTitle() {


return title;
}
}

Class Implementation in the Same Package:

/* File name: LibraryManagement.java */


package library;

public class LibraryManagement {


public static void main(String[] args) {
Book book = new Book("Java Programming");
System.out.println("Book Title: " + book.getTitle());
}
}

2. Compile the Package:

Commands:

javac -d . Book.java
javac -d . LibraryManagement.java

These commands will create a library directory in the current directory and place the compiled Book.class and
LibraryManagement.class files inside it.

3. Execute the Class File:

Command:

java library.LibraryManagement

Output:

Book Title: Java Programming


Do It Yourself

1. What is the purpose of using the package statement in a Java source file?
2. How do packages prevent naming conflicts in Java?
3. Describe the process of compiling and running a Java program that uses user-defined packages.
4. What happens if the package statement is omitted in a Java file?
5. Explain the difference between the default package and user-defined packages.

Quiz

1. How should you declare a package in Java?


A. package myLibrary;
B. package MyLibrary;
C. package My_Library;
D. myLibrary package;

Answer: A. package myLibrary;

2. Which command correctly compiles Java files into the specified directory structure for a package?
A. javac -d . FileName.java
B. javac FileName.java -d .
C. java -d . FileName.java
D. javac -d FileName.java

Answer: A. javac -d . FileName.java

3. What will happen if you have the same package name in multiple Java files?
A. Compilation fails due to duplicate packages
B. The files are combined into the same package
C. Only one file is compiled
D. The files are ignored

Answer: B. The files are combined into the same package

4. After compiling Java files with packages, where are the compiled class files located?
A. In the root directory
B. In the directory specified by the -d option
C. In the default package directory
D. In the user’s home directory

Answer: B. In the directory specified by the -d option

5. What is the effect of omitting the package statement in a Java source file?
A. The file is compiled into the default package
B. The file is not compiled
C. The file will result in a compilation error
D. The file is ignored by the compiler

Answer: A. The file is compiled into the default package

Importing Packages in Java


In Java, the import statement allows you to access classes and interfaces from other packages. This can be
done in two primary ways: importing specific classes or importing all classes from a package.

Syntax for Importing Packages:

1. Importing a Specific Class:


import package.name.ClassName; // Imports only the specified class

2. Importing All Classes in a Package:

import package.name.*; // Imports all classes from the specified package

Examples:

1. Importing a Single Class:

import java.util.Calendar; // Imports only the Calendar class from java.util package

public class CalendarExample {


public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date: " + calendar.getTime());
}
}

2. Importing All Classes from a Package:

import java.text.*; // Imports all classes from java.text package

public class DateFormatExample {


public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = dateFormat.format(new java.util.Date());
System.out.println("Formatted Date: " + formattedDate);
}
}

Using Fully Qualified Names:

If you prefer not to use the import statement, you can use the fully qualified name of a class, which includes its
package hierarchy.

Example:
public class FullyQualifiedNameExample {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println("Today's Date: " + today);
}
}

Example: Defining and Importing a Custom Package

Suppose you have created a package named com.example.util with a class Formatter:

File Structure:

└── com
└── example
└── util
└── Formatter.java

Formatter.java:

package com.example.util;

public class Formatter {


public static String formatCurrency(double value) {
return String.format("$%.2f", value);
}
}

To use the Formatter class in another file, you would import it as follows:

Main.java:

import com.example.util.Formatter;

public class Main {


public static void main(String[] args) {
double amount = 123.45;
String formattedAmount = Formatter.formatCurrency(amount);
System.out.println("Formatted Amount: " + formattedAmount);
}
}

Output:

Formatted Amount: $123.45

Import Statement Placement:

The import statements should be placed after the package statement (if it exists) and before the class
definition.
Example:

package com.example;

import com.example.util.Formatter; // Importing a specific class

public class ExampleClass {


// Class body
}

Do It Yourself

1. Create a package named com.tools with a class Tool that has a method performTask(). Write a program in
another package to use this class and call the method.

2. Define a package com.math containing a class Calculator with a method add(int a, int b). Import this class
in a new file and use it to add two numbers.

Quiz

1. Which import statement brings in all classes from the java.util package?
A. import java.util.*;
B. import java.util;
C. import *;
D. import java.util.All;

Answer: A. import java.util.*;

2. What is the effect of using the fully qualified name of a class?


A. It imports the class into your file
B. It allows you to reference the class without an import statement
C. It compiles the class automatically
D. It generates the class file

Answer: B. It allows you to reference the class without an import statement

3. What should you do if you encounter a class name conflict between two packages?
A. Use only one package
B. Rename the classes
C. Use fully qualified class names to distinguish between them
D. Avoid using packages

Answer: C. Use fully qualified class names to distinguish between them

4. Where should the import statements be placed in a Java file?


A. Before the package statement
B. After the package statement and before the class definition
C. After the class definition
D. At the end of the file

Answer: B. After the package statement and before the class definition
5. Which statement is correct regarding the import statement?
A. It is mandatory for all Java classes
B. It allows access to classes from other packages
C. It automatically imports all classes from the JDK
D. It is used to define new packages

Answer: B. It allows access to classes from other packages

Path and Class Path


Definition:
The path and classpath are environment variables that tell the Java Virtual Machine (JVM) and Java compiler
where to find classes and packages.

• Path: This environment variable specifies the directories or JAR files where executable files (like java and
javac) are located. It helps the operating system locate Java commands.
• Classpath: This environment variable tells the JVM and Java compiler where to find class files, libraries,
and JAR files needed to run or compile Java programs. It includes paths to directories or JAR files where
Java classes are stored.

Syntax:

• Setting Path (Windows):

set PATH=C:\Program Files\Java\jdk-14\bin;%PATH%

• Setting Classpath (Windows):

set CLASSPATH=C:\myclasses;C:\mylibs\mylib.jar

• Setting Path (Linux/Mac):

export PATH=/usr/local/java/jdk-14/bin:$PATH

• Setting Classpath (Linux/Mac):

export CLASSPATH=/home/user/myclasses:/home/user/mylibs/mylib.jar

Example:

Assuming you have a Java program HelloWorld.java and a library utils.jar:

• To compile HelloWorld.java with the utils.jar library:

javac -cp utils.jar HelloWorld.java

• To run HelloWorld.class with the utils.jar library:

java -cp .;utils.jar HelloWorld


Comparison:
S. PATH CLASSPATH
No.

1. An environment variable used by the operating An environment variable used by the Java
system to locate executable files like java and compiler and JVM to locate compiled class
javac. files.

2. Sets up the environment for the OS to find and Sets up the environment for Java to find and
execute binary files. load classes and libraries.

3. Refers to the operating system's executable Refers to the Java runtime and development
search path. environment's class search path.

4. The PATH variable should include the directory The CLASSPATH variable should include paths
path where the Java executables are located to directories or .jar files containing the
(e.g., .bin folder). compiled .class files.

5. Used by the command prompt or terminal to Used by the JVM and compiler to locate class
locate binary files for execution. files and libraries for execution and
compilation.

Explanation:
The -cp or -classpath option is used to specify the classpath for the compiler or JVM. The classpath tells Java
where to look for classes and libraries required during compilation and execution.

Do It Yourself

1. Create a simple Java program that uses an external JAR file. Compile and run it using the classpath.
2. Set up the classpath for a project with multiple packages and demonstrate how to compile and run the
program.

Quiz

1. Which environment variable is used to specify the directories where Java commands are located?
a) CLASSPATH
b) PATH
c) JAVA_HOME
d) JAVA_PATH

Answer: b) PATH

2. How do you specify additional directories or JAR files for Java classpath?
a) Use -d option.
b) Use -classpath or -cp option.
c) Set the CLASSPATH environment variable.
d) Use -path option.
Answer: b) Use -classpath or -cp option.
3. What happens if the required classes are not found in the classpath during execution?
a) The program runs but without some features.
b) The JVM throws a ClassNotFoundException.
c) The compilation fails.
d) The program executes with default classes.
Answer: b) The JVM throws a ClassNotFoundException.

4. What is the effect of setting the CLASSPATH environment variable?


a) It specifies the locations of Java compiler executable.
b) It tells the JVM where to find classes and libraries.
c) It sets the location of Java source files.
d) It defines the location of Java documentation.

Answer: b) It tells the JVM where to find classes and libraries.

5. How do you include multiple JAR files in the classpath?


a) Use a comma to separate the JAR files.
b) Use a semicolon (Windows) or colon (Linux/Mac) to separate the JAR files.
c) List them on separate lines.
d) Use a pipe character to separate the JAR files.

Answer: b) Use a semicolon (Windows) or colon (Linux/Mac) to separate the JAR files.

Access Control
In Java, packages are used not only to group related classes and interfaces but also to control access to these
elements. Access control determines the visibility and accessibility of classes, methods, and other members
within a package and from outside packages.
Access Modifiers in Java
Java provides four access modifiers to control the visibility of classes, methods, and fields:
1. public: The member is accessible from any other class in any package.
2. protected: The member is accessible within its own package and by subclasses (even if they are in
different packages).
3. default (no modifier): The member is accessible only within its own package.
4. private: The member is accessible only within the class it is defined in.

Access Control within a Package


• Public Classes: Can be accessed from any other class in any package.
• Protected Members: Accessible within the same package and by subclasses in other packages.
• Default (Package-Private) Members: Accessible only within the same package.
• Private Members: Accessible only within the same class.
Examples of Access Control in Packages
1. Public Access
// File: com/example/PublicClass.java
package com.example;

public class PublicClass {


public void display() {
System.out.println("Public method in PublicClass.");
}
}

// File: com/example/AnotherClass.java
package com.example;

public class AnotherClass {


public static void main(String[] args) {
PublicClass obj = new PublicClass();
obj.display(); // Accessible because PublicClass is public
}
}

2. Protected Access
// File: com/example/BaseClass.java
package com.example;

public class BaseClass {


protected void show() {
System.out.println("Protected method in BaseClass.");
}
}

// File: com/example/DerivedClass.java
package com.example;

public class DerivedClass extends BaseClass {


public void display() {
show(); // Accessible because show() is protected and DerivedClass is a subclass
}
}

3. Default Access
// File: com/example/DefaultClass.java
package com.example;

class DefaultClass {
void print() {
System.out.println("Default method in DefaultClass.");
}
}

// File: com/example/AnotherClass.java
package com.example;

public class AnotherClass {


public static void main(String[] args) {
DefaultClass obj = new DefaultClass();
obj.print(); // Accessible because DefaultClass and AnotherClass are in the same package
}
}
4. Private Access
// File: com/example/PrivateClass.java
package com.example;

public class PrivateClass {


private void secret() {
System.out.println("Private method in PrivateClass.");
}

public void accessSecret() {


secret(); // Accessible because it's within the same class
}
}

// File: com/example/AnotherClass.java
package com.example;

public class AnotherClass {


public static void main(String[] args) {
PrivateClass obj = new PrivateClass();
obj.accessSecret(); // Accessible because accessSecret() is public
// obj.secret(); // Not accessible because secret() is private
}
}

Summary
• Public members are accessible from any other class.
• Protected members are accessible within the same package and by subclasses.
• Default (Package-Private) members are accessible only within the same package.
• Private members are accessible only within the same class.

Do It Yourself

1. Create a class with all access modifiers and demonstrate their usage in a separate class within the same
package.
2. Write a program with a class that has private and protected members, and access them from a subclass in
a different package.

Quiz

1. Which access modifier allows access to a class member from any other class?
a) protected
b) default
c) public
d) private

Answer: c) public

2. What is the default access level for class members without an explicit modifier?
a) public
b) protected
c) default
d) private

Answer: c) default

3. Which access modifier is the most restrictive?


a) default
b) protected
c) public
d) private

Answer: d) private

4. Can a protected member of a class be accessed outside its package?


a) Yes, by any class.
b) No, it can only be accessed by subclasses.
c) Yes, but only by classes within the same package.
d) No, it can only be accessed within the same package.

Answer: b) No, it can only be accessed by subclasses.

5. What is the result of accessing a private member from a different class in the same package?
a) The member can be accessed.
b) The member cannot be accessed and a compile-time error occurs.
c) The member is accessible if it is inherited.
d) The member can be accessed using reflection.

Answer: b) The member cannot be accessed and a compile-time error occurs.

Packages in Java SE
Overview
In Java SE (Standard Edition), packages are used to group related classes, interfaces, and sub-packages into a
single unit. This helps in organizing the code, avoiding naming conflicts, and providing access protection. Java
SE includes a number of built-in packages such as java.lang, java.util, and java.io, which contain commonly
used classes and interfaces.

Common Packages:

• java.lang: Contains fundamental classes like String, Math, and Object.


• java.util: Contains utility classes like ArrayList, HashMap, and Date.
• java.io: Provides classes for input and output operations.
• java.net: Contains classes for networking operations.
Syntax
To use a package in Java, you need to:

1. Declare a package: Use the package keyword at the top of your Java file.
package com.example.myapp;

2. Import a package: Use the import keyword to bring classes or entire packages into visibility.

import java.util.List; // Imports a specific class


import java.util.*; // Imports all classes in the package

Built-in Packages in Java SE


1. java.lang: This package is automatically imported and contains fundamental classes such as String, Math,
Object, Thread, and more.

String str = "Hello";


int length = str.length();

2. java.util: Contains utility classes such as collections framework classes (ArrayList, HashMap), date and
time utilities, and more.

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();


list.add("One");
list.add("Two");

3. java.io: Provides classes for input and output operations, including file handling, serialization, and stream
handling.
import java.io.File;

File file = new File("example.txt");

4. java.net: Contains classes for networking, including sockets, URLs, and network interfaces.

import java.net.URL;

URL url = new URL("http://www.example.com");

5. java.sql: Provides classes for database access and SQL operations.

import java.sql.Connection;

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

Examples
Example 1: Using java.util Package

import java.util.ArrayList;

public class ListExample {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

System.out.println(fruits);
}
}

Example 2: Using java.io Package

import java.io.File;
import java.io.IOException;

public class FileExample {


public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Example 3: Creating and Using a Custom Package

File: com/example/util/MathUtil.java

package com.example.util;

public class MathUtil {


public static int square(int number) {
return number * number;
}
}

File: Main.java

import com.example.util.MathUtil;

public class Main {


public static void main(String[] args) {
int result = MathUtil.square(5);
System.out.println("Square of 5 is: " + result);
}
}

Example 4: Using Fully Qualified Names

public class FullyQualifiedExample {


public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println("Today's date: " + today);
}
}

Do It Yourself

1. List some commonly used packages in Java SE.


2. Explain the purpose of the java.util package.
3. Write a program using classes from java.net to create a simple socket connection.
4. Describe the java.lang package and its importance in Java.

Quiz

1. Which package is automatically imported in every Java program?


A) java.util
B) java.lang
C) java.io
D) java.net

Answer: B) java.lang

2. Which of the following statements correctly imports all classes from the java.util package?
A) import java.util.*;
B) import java.util;
C) import java.util.All;
D) import * from java.util;

Answer: A) import java.util.*;

3. Which package provides classes for working with collections like ArrayList and HashMap?
a) java.io
b) java.util
c) java.lang
d) java.net

Answer: b) java.util

4. Which package contains the String class?

a) java.io
b) java.util
c) java.lang
d) java.net
Answer: c) java.lang
Answer: C) .java source files
5. Which command is used to compile Java files with packages?
A) javac -cp
B) javac -classpath
C) javac -d
D) javac -dir

Answer: C) javac -d

Java.lang Package and its Classes


Definition:
The java.lang package is automatically imported by all Java programs. It contains fundamental classes that are
essential for Java programming.

Key Classes:
• Object: The root class of the Java class hierarchy.
• String: Represents a sequence of characters.
• Math: Provides mathematical functions and constants.
• System: Provides access to system-related features.

Syntax and Examples:


Key Classes in java.lang
1. Object: The root class of the Java class hierarchy. Every class in Java implicitly extends Object. It provides
basic methods such as equals(), hashCode(), toString(), and getClass().

public class Example {


public static void main(String[] args) {
Object obj = new Object();
System.out.println(obj.toString()); // Prints the object's string representation
}
}

2. String: Represents a sequence of characters. It is immutable and provides methods for string manipulation
such as length(), substring(), toLowerCase(), toUpperCase(), and concat().

public class StringExample {


public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.length()); // Prints the length of the string
System.out.println(str.toUpperCase()); // Converts the string to uppercase
}
}

3. Math: Contains mathematical functions and constants. It includes methods for basic arithmetic,
trigonometric functions, logarithms, and constants such as PI and E.

public class MathExample {


public static void main(String[] args) {
double squareRoot = Math.sqrt(16); // Calculates the square root
double power = Math.pow(2, 3); // Calculates 2 raised to the power of 3
System.out.println("Square root: " + squareRoot);
System.out.println("Power: " + power);
}
}

4. System: Provides access to system-level operations and properties. It includes methods for standard
input/output, environment variables, and system properties. Key methods include System.out.println(),
System.currentTimeMillis(), and System.getenv().

public class SystemExample {


public static void main(String[] args) {
long startTime = System.currentTimeMillis(); // Gets the current time in milliseconds
System.out.println("Current time: " + startTime);
}
}

Do It Yourself

1. Write a program using String methods to manipulate and display a string.


2. Use the Math class to perform various mathematical operations and display results.

Quiz

1. Which class is the root of the Java class hierarchy?


a) String
b) Object
c) Math
d) System

Answer: b) Object

2. Which method of the String class converts all characters to uppercase?


a) toLowerCase()
b) toUpperCase()
c) trim()
d) substring()

Answer: b) toUpperCase()

3. What does the Math.sqrt() method do?


a) Calculates the square of a number.
b) Calculates the square root of a number.
c) Calculates the cube root of a number.
d) Calculates the exponential of a number.

Answer: b) Calculates the square root of a number.

4. Which class provides access to system-related features like standard input and output?
a) Math
b) String
c) System
d) Object
Answer: c) System

5. Which method of the Object class is used to get the class type of an object?
a) getClass()
b) getType()
c) className()
d) getObject()

Answer: a) getClass()

Class Object in Java


In Java, the Object class is the superclass of all classes. Every class in Java is either directly or indirectly derived
from the Object class. If a class does not explicitly extend another class, it implicitly inherits from the Object
class. The Object class is defined in the java.lang package, and it provides several fundamental methods that
are inherited by all Java classes.

Key Methods of the Object Class


1. toString(): Returns a string representation of the object. By default, this method returns the class name
followed by the @ symbol and the object's hash code in hexadecimal format. It is generally overridden to
provide a more meaningful string representation of an object.

Syntax:

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Example:

public class Car {


private String model;

public Car(String model) {


this.model = model;
}

@Override
public String toString() {
return "Car{model='" + model + "'}";
}

public static void main(String[] args) {


Car car = new Car("Tesla");
System.out.println(car.toString()); // Output: Car{model='Tesla'}
}
}

2. equals(Object obj): Compares the current object with another object for equality. The default
implementation checks if the two object references are the same. It is often overridden to provide meaningful
equality checks.

Syntax:

public boolean equals(Object obj) {


return (this == obj);
}

Example:

public class Car {


private String model;

public Car(String model) {


this.model = model;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Car car = (Car) obj;
return model.equals(car.model);
}
public static void main(String[] args) {
Car car1 = new Car("Tesla");
Car car2 = new Car("Tesla");
System.out.println(car1.equals(car2)); // Output: true
}
}

3. hashCode(): Returns a hash code value for the object. The default implementation converts the internal
memory address of the object to an integer. This method is commonly overridden along with equals() to
ensure that equal objects return the same hash code.

Syntax:

public int hashCode() {


return System.identityHashCode(this);
}

Example:
public class Car {
private String model;

public Car(String model) {


this.model = model;
}

@Override
public int hashCode() {
return model.hashCode();
}

public static void main(String[] args) {


Car car = new Car("Tesla");
System.out.println(car.hashCode());
}
}

4. getClass(): Returns the runtime class of the object. It is used to retrieve metadata about the object’s class.
This method is final, meaning it cannot be overridden.

Syntax:

public final Class<?> getClass() {


return Class.forName(getClass().getName());
}
Example:

public class Main {


public static void main(String[] args) {
Object obj = new String("Hello");
System.out.println(obj.getClass().getName()); // Output: java.lang.String
}
}

5. finalize(): This method is called before an object is garbage collected. It is used to perform cleanup actions
before the object is destroyed. This method has been deprecated since Java 9 due to unreliability and
performance issues, and developers are advised to use other means for resource management.

Example:

public class Resource {


@Override
protected void finalize() throws Throwable {
System.out.println("Finalize called");
}
public static void main(String[] args) {
Resource resource = new Resource();
resource = null;
System.gc(); // Triggers garbage collection
}
}
6. clone(): Creates and returns a copy (clone) of this object. The clone() method in the Object class provides
a shallow copy mechanism. To use this method, a class must implement the Cloneable interface.

Example:

public class Car implements Cloneable {


private String model;

public Car(String model) {


this.model = model;
}

@Override
protected Car clone() throws CloneNotSupportedException {
return (Car) super.clone();
}

public static void main(String[] args) throws CloneNotSupportedException {


Car car1 = new Car("Tesla");
Car car2 = car1.clone();
System.out.println(car1 == car2); // Output: false (different objects)
}
}

7. wait(), notify(), notifyAll(): These methods are used in thread synchronization. The wait() method causes
the current thread to wait until another thread calls notify() or notifyAll() on the same object. notify() wakes
up a single thread waiting on this object's monitor, while notifyAll() wakes up all the threads waiting on the
object's monitor.

Example:

public class ThreadExample {


public static void main(String[] args) {
final Object lock = new Object();

Thread t1 = new Thread(() -> {


synchronized (lock) {
try {
System.out.println("Thread 1 waiting...");
lock.wait();
System.out.println("Thread 1 resumed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

Thread t2 = new Thread(() -> {


synchronized (lock) {
System.out.println("Thread 2 notifying...");
lock.notify();
}
});

t1.start();
try { Thread.sleep(100); } catch (InterruptedException e) {}
t2.start();
}
}

Summary of Methods in the Object Class


• toString(): Returns a string representation of the object.
• equals(Object obj): Compares this object with the specified object for equality.
• hashCode(): Returns a hash code value for the object.
• getClass(): Returns the runtime class of the object.
• finalize(): Called before the object is garbage collected.
• clone(): Creates and returns a copy of the object.
• wait(), notify(), notifyAll(): Used for thread synchronization.

Example: Using All Object Class Methods


public class Book implements Cloneable {
private String title;
private String author;
private int year;

public Book(String title, String author, int year) {


this.title = title;
this.author = author;
this.year = year;
}

@Override
public String toString() {
return title + " by " + author + " (" + year + ")";
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book book = (Book) obj;
return year == book.year && title.equals(book.title) && author.equals(book.author);
}

@Override
public int hashCode() {
int result = 17;
result = 31 * result + title.hashCode();
result = 31 * result + author.hashCode();
result = 31 * result + year;
return result;
}
@Override
public Book clone() {
try {
return (Book) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}

@Override
protected void finalize() throws Throwable {
System.out.println("Finalizing " + this);
}

public static void main(String[] args) {


Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
Book book2 = book1.clone();

System.out.println(book1);
System.out.println(book2);
System.out.println("book1 equals book2: " + book1.equals(book2));
System.out.println("book1 hash code: " + book1.hashCode());
System.out.println("book2 hash code: " + book2.hashCode());

book1 = null;
System.gc(); // Calls finalize on book1
}
}
Output:
The Great Gatsby by F. Scott Fitzgerald (1925)
The Great Gatsby by F. Scott Fitzgerald (1925)
book1 equals book2: true
book1 hash code: 1677824753
book2 hash code: 1677824753
Finalizing The Great Gatsby by F. Scott Fitzgerald (1925)

In this example, we demonstrated the use of all the key methods of the Object class in Java.

Do It Yourself

1. Override the toString() method in a custom class and print its object.
2. Implement the equals() method in a class and test equality of objects.

Quiz

1. Which method of the Object class returns a string representation of the object?
a) getClass()
b) toString()
c) equals()
d) hashCode()

Answer: b) toString()
2. What is the result of comparing two objects using the equals() method?
a) It compares object references.
b) It compares the memory addresses of objects.
c) It checks if the two objects are logically equivalent.
d) It always returns true.

Answer: c) It checks if the two objects are logically equivalent.

3. Which method should be overridden when overriding the equals() method?


a) hashCode()
b) toString()
c) getClass()
d) clone()

Answer: a) hashCode()

4. What does the getClass() method return?


a) The name of the class as a string.
b) The runtime class of the object.
c) The superclass of the object.
d) The memory address of the object.

Answer: b) The runtime class of the object.

5. Which of the following methods is used to get a unique identifier for an object?
a) toString()
b) getClass()
c) equals()
d) hashCode()

Answer: d) hashCode()

Enumeration in Java
Enumeration (enum) is a special data type in Java that enables a variable to be a set of predefined constants. It
is useful when you have a fixed set of related values, such as days of the week, directions (NORTH, SOUTH,
EAST, WEST), or status flags (READY, BUSY, WAITING).

The enum keyword was introduced in Java 5 and is part of the java.lang package. Enums in Java are more
powerful than in other programming languages because they can have constructors, methods, and instance
variables.
1. Syntax of enum in Java
The basic syntax for defining an enum in Java is as follows:

enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}

• EnumName: The name of the enum.


•CONSTANT1, CONSTANT2, CONSTANT3: The constants that represent the values of the enum.
2. Example of Enum
Let's define an enum to represent the days of the week.

enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

public class EnumExample {


public static void main(String[] args) {
Day today = Day.SUNDAY;
System.out.println("Today is: " + today);
}
}

Output:

Today is: SUNDAY

In this example, we defined an enum Day and assigned a value SUNDAY to the variable today.

3. Enum with Constructors and Methods


In Java, enums can have constructors and methods just like a class. This makes Java enums powerful because
each enum constant can be associated with data and have behavior.

Let's create an enum to represent the different levels of a severity rating (LOW, MEDIUM, HIGH), each with a
priority level.

enum Severity {
LOW(1), MEDIUM(2), HIGH(3);

private int priorityLevel;

// Constructor
Severity(int priorityLevel) {
this.priorityLevel = priorityLevel;
}

// Method to get the priority level


public int getPriorityLevel() {
return priorityLevel;
}
}

public class EnumWithConstructorExample {


public static void main(String[] args) {
Severity severity = Severity.HIGH;
System.out.println("Severity level: " + severity + " with priority " + severity.getPriorityLevel());
}
}
Output:
Severity level: HIGH with priority 3

In this example:
• We created an enum Severity with three levels: LOW, MEDIUM, and HIGH.
• Each level has an associated priority value.
• The enum has a constructor that assigns a priority value to each constant, and a method getPriorityLevel()
to access that value.

4. Enum Methods
Java provides several built-in methods to work with enums:
• values(): Returns an array of all enum constants.
• valueOf(String name): Returns the enum constant with the specified name.
• ordinal(): Returns the ordinal position of the enum constant (0-based index).

enum Season {
WINTER, SPRING, SUMMER, FALL;
}

public class EnumMethodsExample {


public static void main(String[] args) {
// Using values() method
for (Season s : Season.values()) {
System.out.println(s);
}

// Using valueOf() method


Season currentSeason = Season.valueOf("SUMMER");
System.out.println("Current season is: " + currentSeason);

// Using ordinal() method


System.out.println("Ordinal of SUMMER is: " + currentSeason.ordinal());
}
}

Output:

WINTER
SPRING
SUMMER
FALL
Current season is: SUMMER
Ordinal of SUMMER is: 2

5. Enum in Switch Case Statements


Enums are commonly used in switch statements, making it easier to handle multiple constant values.

enum TrafficSignal {
RED, YELLOW, GREEN;
}
public class EnumSwitchExample {
public static void main(String[] args) {
TrafficSignal signal = TrafficSignal.GREEN;

switch (signal) {
case RED:
System.out.println("Stop!");
break;
case YELLOW:
System.out.println("Get Ready!");
break;
case GREEN:
System.out.println("Go!");
break;
}
}
}

Output:

Go!

In this example, the TrafficSignal enum is used inside a switch statement to control the flow based on the
current signal.

6. Enum Constants with Fields and Methods


Enums in Java can contain fields and methods just like a regular class. This allows each enum constant to have
its own values or behavior.

enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6);

private final double mass; // in kilograms


private final double radius; // in meters

// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}

public double getMass() {


return mass;
}

public double getRadius() {


return radius;
}
}
public class EnumWithFieldsExample {
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.println(p + ": mass = " + p.getMass() + ", radius = " + p.getRadius());
}
}
}

Output:

MERCURY: mass = 3.303E23, radius = 2439700.0


VENUS: mass = 4.869E24, radius = 6051800.0
EARTH: mass = 5.976E24, radius = 6378140.0
MARS: mass = 6.421E23, radius = 3397200.0

In this example, each planet has its own mass and radius. These values are assigned when the enum constants
are declared.

Do It Yourself

1. Create an enum for the days of the week and demonstrate its usage in a switch statement.
2. Write a program to list all values of an enum using the values() method.
3. Write a program that defines an enum for the days of the week and prints whether the day is a weekday
or a weekend.
4. Create an enum for the four cardinal directions (NORTH, SOUTH, EAST, WEST) and write a program that
prints the opposite direction of a given direction.
5. Write a program that defines an enum for the planets in the solar system, each with its own gravity value,
and computes the weight of an object on each planet.

Quiz

1. What is the purpose of an enum in Java?


a) To define constants.
b) To handle errors.
c) To perform arithmetic operations.
d) To handle user input.

Answer: a) To define constants.

2. Which method is used to get all constants of an enum type?


a) values()
b) getConstants()
c) list()
d) enumValues()

Answer: a) values()

3. Can enums in Java have methods?


a) Yes, enums can have methods.
b) No, enums cannot have methods.
c) Enums can only have static methods.
d) Enums can have methods only in Java 8 and above.

Answer: a) Yes, enums can have methods.

4. What will be the output of the following code snippet?

public enum Color {


RED, GREEN, BLUE;
}

public class TestColor {


public static void main(String[] args) {
System.out.println(Color.RED.ordinal());
}
}

a) 0
b) 1
c) RED
d) Color.RED

Answer: a) 0

5. Which statement is true about enums?


a) Enums are mutable.
b) Enums can extend other classes.
c) Enums are implicitly final.
d) Enums cannot have constructors.

Answer: c) Enums are implicitly final.

The java.lang.Math Class


The java.lang.Math class is a part of the java.lang package in Java and provides a collection of static methods
for performing basic mathematical operations like exponentiation, logarithms, square roots, and trigonometric
calculations. Since these methods are static, they can be called without creating an instance of the Math class.
Key Features of Math Class
• All methods in the Math class are static, so you can directly invoke them without creating an object.
• The class cannot be instantiated because it has a private constructor.
• The Math class includes constants for commonly used mathematical values like PI and E.

Commonly Used Constants


• Math.PI: The value of pi (π), which is approximately 3.14159.
• Math.E: The base of natural logarithms (e), which is approximately 2.71828.
Commonly Used Methods in Math Class
Method Description

Math.abs(a) Returns the absolute value of a.

Math.max(a, b) Returns the greater of two values a and b.


Method Description

Math.min(a, b) Returns the smaller of two values a and b.

Math.pow(a, b) Returns a raised to the power of b (a^b).

Math.sqrt(a) Returns the square root of a.

Math.log(a) Returns the natural logarithm (base e) of a.

Math.log10(a) Returns the base 10 logarithm of a.

Math.sin(a) Returns the sine of a, where a is in radians.

Math.cos(a) Returns the cosine of a, where a is in radians.

Math.tan(a) Returns the tangent of a, where a is in radians.

Math.random() Returns a random number between 0.0 and 1.0.

Math.ceil(a) Returns the smallest integer greater than or equal to a.

Math.floor(a) Returns the largest integer less than or equal to a.

Math.round(a) Rounds the floating-point value a to the nearest integer.

Math.toRadians(a) Converts the value a from degrees to radians.

Math.toDegrees(a) Converts the value a from radians to degrees.

Examples of Math Methods


Example 1: Using Math.abs(), Math.max(), and Math.min()
public class MathExample1 {
public static void main(String[] args) {
int x = -10;
int y = 5;
int z = 20;

System.out.println("Absolute value of x: " + Math.abs(x)); // 10


System.out.println("Maximum of y and z: " + Math.max(y, z)); // 20
System.out.println("Minimum of y and z: " + Math.min(y, z)); // 5
}
}

Output:

Absolute value of x: 10
Maximum of y and z: 20
Minimum of y and z: 5

Example 2: Using Math.pow() and Math.sqrt()


public class MathExample2 {
public static void main(String[] args) {
double base = 5;
double exponent = 2;

System.out.println(base + " raised to the power of " + exponent + " is: " + Math.pow(base, exponent)); //
25.0
System.out.println("Square root of 25 is: " + Math.sqrt(25)); // 5.0
}
}

Output:

5.0 raised to the power of 2.0 is: 25.0


Square root of 25 is: 5.0

Example 3: Using Math.random()


public class MathExample3 {
public static void main(String[] args) {
double randomValue = Math.random(); // Generates a random number between 0.0 and 1.0
System.out.println("Random value: " + randomValue);
}
}

Output:

Random value: 0.635434634

Example 4: Using Trigonometric Functions


public class MathExample4 {
public static void main(String[] args) {
double angle = 45.0; // angle in degrees
double radians = Math.toRadians(angle); // Convert angle to radians

System.out.println("Sine of 45 degrees: " + Math.sin(radians));


System.out.println("Cosine of 45 degrees: " + Math.cos(radians));
System.out.println("Tangent of 45 degrees: " + Math.tan(radians));
}
}

Output:

Sine of 45 degrees: 0.7071067811865475


Cosine of 45 degrees: 0.7071067811865476
Tangent of 45 degrees: 0.9999999999999999

Explanation of Some Important Methods


• Math.abs(): The absolute value of a number is its distance from zero, without considering the sign. For
example, Math.abs(-10) returns 10.
• Math.pow(a, b): This method returns a raised to the power of b. For example, Math.pow(2, 3) returns 8.0
(i.e., 2^3).
• Math.sqrt(a): This method returns the square root of the number a. For example, Math.sqrt(25) returns
5.0.
• Math.random(): This method generates a random double value between 0.0 and 1.0. You can scale it to
generate a random number in a specific range.
• Math.ceil() and Math.floor(): These methods are used to round a number up or down to the nearest
integer. For example, Math.ceil(5.3) returns 6.0, and Math.floor(5.3) returns 5.0.

Do It Yourself

1. Write a program that calculates the hypotenuse of a right triangle using the Math.sqrt() method.
2. Use Math.pow() to compute the result of different exponential calculations.
3. Write a program to calculate the maximum of three numbers using Math.max().
4. Create a program that generates 5 random integers between 1 and 100 using Math.random().
5. Write a program that takes an angle in degrees from the user and calculates its sine, cosine, and tangent
using the Math.sin(), Math.cos(), and Math.tan() methods.

Quiz

1. Which method is used to calculate the square root of a number in Java?


a) Math.pow()
b) Math.sqrt()
c) Math.log()
d) Math.abs()

Answer: b) Math.sqrt()

2. What does the Math.pow() method do?


a) Computes the square root.
b) Computes the power of a number.
c) Computes the logarithm.
d) Computes the absolute value.

Answer: b) Computes the power of a number.

3. Which method would you use to find the smaller of two numbers?
a) Math.max()
b) Math.min()
c) Math.sqrt()
d) Math.abs()

Answer: b) Math.min()

4. How can you find the absolute value of a number using the Math class?
a) Math.abs()
b) Math.max()
c) Math.min()
d) Math.sqrt()

Answer: a) Math.abs()

5. What does the Math.max() method return?


a) The minimum of two values.
b) The maximum of two values.
c) The absolute difference between two values.
d) The average of two values.
Answer: b) The maximum of two values.
Wrapper Classes in Java
In Java, Wrapper Classes are used to convert primitive data types (such as int, float, char, etc.) into
corresponding objects. Java provides these wrapper classes for all primitive data types to allow them to be
used as objects. This is particularly useful in situations where objects are required, such as in Collections like
ArrayList, which cannot hold primitive types.
List of Wrapper Classes in Java
Each primitive type in Java has a corresponding wrapper class, as shown in the table below:

Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean
Why Use Wrapper Classes?
• Collections Framework: Classes like ArrayList, HashMap, and others from Java’s Collections Framework
cannot store primitive types. Wrapper classes are used to store primitives as objects.

• Object Manipulation: Wrapper classes allow primitives to be treated as objects and manipulated
accordingly (such as passing them to methods that expect objects).

• Autoboxing and Unboxing: Starting from Java 5, automatic conversion between primitive types and their
corresponding wrapper classes is supported by the compiler. This feature is known as autoboxing and
unboxing.

• Autoboxing: Automatic conversion of a primitive type into its corresponding wrapper class object.
• Unboxing: Automatic conversion of a wrapper class object into its corresponding primitive type.

Wrapper Class Syntax and Example


Syntax of Wrapper Classes
// Example of creating wrapper class objects:
Integer intObj = Integer.valueOf(10); // Autoboxing example
Double doubleObj = Double.valueOf(15.6);
Example of Autoboxing and Unboxing
public class WrapperExample {
public static void main(String[] args) {
// Autoboxing: converting primitive to wrapper object
int num = 100;
Integer obj = num; // Autoboxing
// Unboxing: converting wrapper object to primitive
Integer numObj = Integer.valueOf(200);
int newNum = numObj; // Unboxing

System.out.println("Primitive value: " + num);


System.out.println("Autoboxed object: " + obj);
System.out.println("Unboxed primitive: " + newNum);
}
}

Output:

Primitive value: 100


Autoboxed object: 100
Unboxed primitive: 200

Example of Autoboxing in Collections


import java.util.ArrayList;

public class WrapperClassInCollection {


public static void main(String[] args) {
// Using wrapper class Integer in ArrayList
ArrayList<Integer> list = new ArrayList<>();

// Autoboxing - automatically converts int to Integer


list.add(10);
list.add(20);

// Unboxing - automatically converts Integer to int


int firstElement = list.get(0);

System.out.println("First Element: " + firstElement);


System.out.println("Complete List: " + list);
}
}

Output:

First Element: 10
Complete List: [10, 20]

Methods of Wrapper Classes


Each wrapper class comes with useful methods for operations like converting to strings, parsing, etc.

Method Description

parseInt(String s) Converts the string argument into an integer (int).

valueOf(String s) Returns the wrapper object containing the value represented by the
string.
Method Description

intValue(), doubleValue(), Extracts the primitive value from the wrapper object.
etc.

toString() Returns a string representation of the wrapper object.

compare() Compares two values (either as primitive or wrapper).

Example: Using parseInt() and valueOf() Methods


public class ParseAndValueOfExample {
public static void main(String[] args) {
// Using parseInt() to convert String to int
String numberStr = "100";
int num = Integer.parseInt(numberStr);

// Using valueOf() to get wrapper class object


Integer numberObj = Integer.valueOf(numberStr);

System.out.println("Primitive value from parseInt: " + num);


System.out.println("Wrapper object from valueOf: " + numberObj);
}
}

Output:

Primitive value from parseInt: 100


Wrapper object from valueOf: 100

Practice Programs
1. Program to Convert String to Integer Using Wrapper Class

public class StringToInteger {


public static void main(String[] args) {
String str = "123";
int num = Integer.parseInt(str);
System.out.println("Converted Integer: " + num);
}
}

2. Using Wrapper Class Methods for Conversion

public class WrapperMethods {


public static void main(String[] args) {
Integer num = 100;
String strNum = num.toString();

System.out.println("String representation of number: " + strNum);


}
}
Do It Yourself

1. Write a Java program to convert a given string into a primitive float using the wrapper class method.
2. Write a program that accepts a user’s input as a string and converts it into a primitive int, then performs
arithmetic operations on it.
3. Create a Java program that stores int values in an ArrayList using wrapper classes, and calculate the sum
of the list.
4. Demonstrate the difference between == and .equals() when comparing wrapper class objects.

Quiz

1. Which of the following is a wrapper class for the primitive int?


A) Integer
B) Float
C) Double
D) Character

Answer: A) Integer

2. Which method is used to convert a String into an int?


A) Integer.toString()
B) Integer.valueOf()
C) Integer.parseInt()
D) Integer.intValue()

Answer: C) Integer.parseInt()

3. Which of the following is true about autoboxing?


A) It automatically converts an object into a primitive type.
B) It converts a primitive type into its corresponding wrapper class.
C) It allows comparisons between two primitive types.
D) None of the above.

Answer: B) It converts a primitive type into its corresponding wrapper class.

4. What is the result of the following code?

Integer a = 100;
Integer b = 100;
System.out.println(a == b);
A) true
B) false
C) Compilation Error
D) Runtime Error

Answer: A) true
5. What is the correct way to convert the string "100" to the primitive int value?
A) int x = Integer.valueOf("100");
B) int x = Integer.parseInt("100");
C) int x = Integer.intValue("100");
D) int x = Integer.toString("100");

Answer: B) int x = Integer.parseInt("100");

Auto-boxing and Auto-unboxing


In Java, Auto-boxing and Auto-unboxing are features introduced in Java 5 (JDK 1.5) that automatically convert
between primitive data types and their corresponding wrapper class objects. This makes coding more seamless
and avoids unnecessary conversions between primitive types and wrapper objects.

Auto-boxing
Auto-boxing is the automatic conversion of a primitive data type into its corresponding wrapper class object.

For example:
• int is converted to Integer
• double is converted to Double

Syntax:
int num = 10;
Integer obj = num; // Auto-boxing: primitive int to Integer object

In the above example, the primitive int value num is automatically converted into an Integer object obj.
Example of Auto-boxing:
public class AutoBoxingExample {
public static void main(String[] args) {
int num = 5;
Integer obj = num; // Auto-boxing
System.out.println("Primitive int: " + num);
System.out.println("Boxed Integer: " + obj);
}
}

Output:

Primitive int: 5
Boxed Integer: 5

Auto-unboxing
Auto-unboxing is the automatic conversion of a wrapper class object to its corresponding primitive data type.
Syntax:
Integer obj = 100;
int num = obj; // Auto-unboxing: Integer object to primitive int

In this case, the Integer object obj is automatically converted into the primitive int value num.

Example of Auto-unboxing:
public class AutoUnboxingExample {
public static void main(String[] args) {
Integer obj = 10; // Auto-boxing
int num = obj; // Auto-unboxing
System.out.println("Boxed Integer: " + obj);
System.out.println("Primitive int: " + num);
}
}

Output:

Boxed Integer: 10
Primitive int: 10

Auto-boxing and Auto-unboxing in Expressions


Auto-boxing and Auto-unboxing can also occur when performing arithmetic operations or using expressions
involving wrapper class objects and primitive types.
Example:
public class AutoBoxingUnboxingExample {
public static void main(String[] args) {
Integer obj1 = 10; // Auto-boxing
Integer obj2 = 20; // Auto-boxing
int sum = obj1 + obj2; // Auto-unboxing occurs during addition
System.out.println("Sum: " + sum);
}
}

Output:

Sum: 30

In this example, obj1 and obj2 are Integer objects, but during the arithmetic operation, they are automatically
unboxed to int for addition, and the result is stored in a primitive int variable.

Advantages of Auto-boxing and Auto-unboxing


• Simplicity: Reduces manual conversions between primitive types and wrapper class objects.
• Code readability: Makes code more readable and concise.
• Less boilerplate code: Eliminates the need for writing redundant type conversion code.

Potential Issues with Auto-boxing and Auto-unboxing


• Performance overhead: Auto-boxing/unboxing introduces slight performance overhead, especially in
loops where repetitive boxing and unboxing happen.
• NullPointerException: If a null object is auto-unboxed, it can lead to NullPointerException.

Example of NullPointerException due to auto-unboxing:


public class NullPointerAutoUnboxing {
public static void main(String[] args) {
Integer obj = null;
int num = obj; // Throws NullPointerException
}
}

Output:

Exception in thread "main" java.lang.NullPointerException


Practice Program
Write a Java program that demonstrates both auto-boxing and auto-unboxing, and performs arithmetic
operations on boxed types.

public class AutoBoxingUnboxingPractice {


public static void main(String[] args) {
Double d1 = 50.5; // Auto-boxing
Double d2 = 25.5; // Auto-boxing

// Auto-unboxing during subtraction


double result = d1 - d2;

System.out.println("Result of subtraction: " + result);


}
}

Do It Yourself

1. Write a program that demonstrates auto-boxing with a Character wrapper class.


2. Write a program that demonstrates auto-unboxing using the Float wrapper class.
3. What is the advantage of auto-boxing and auto-unboxing in Java?
4. Explain a situation where auto-boxing can cause performance overhead in a program.
5. Write a program that demonstrates both auto-boxing and auto-unboxing with a Boolean wrapper class.

Quiz

1. What is auto-boxing in Java?

A) Automatic conversion of a wrapper object into its corresponding primitive data type
B) Automatic conversion of a primitive data type into its corresponding wrapper object
C) Conversion of one data type into another
D) None of the above

Answer: B

2. Which version of Java introduced auto-boxing and auto-unboxing?

A) Java 1.4
B) Java 1.5
C) Java 1.6
D) Java 1.7

Answer: B

3. What will happen if a null wrapper object is auto-unboxed?

A) It will convert to 0
B) It will cause a compilation error
C) It will throw a NullPointerException
D) It will convert to the default value of the type

Answer: C
4. Which of the following is an example of auto-unboxing?

A) Integer i = 5;
B) int x = new Integer(10);
C) Integer i = new Integer(20);
D) int x = i;

Answer: D

5. What is the main advantage of auto-boxing and auto-unboxing?

A) Reduces performance
B) Simplifies code by eliminating manual conversion
C) Helps in memory management
D) Enables multi-threading

Answer: B

Java Util Classes and Interfaces: Detailed Reading Material


The java.util package is one of the most commonly used in Java, as it provides classes and interfaces that
support various useful functionalities like data structures (such as lists and maps), date and time operations,
random number generation, and more. This package is fundamental for developing any substantial Java
application, as it contains utility classes and interfaces that simplify a lot of operations.
Key Classes and Interfaces in java.util
1. List Interface: Represents an ordered collection of elements.
2. ArrayList Class: A resizable array implementation of the List interface.
3. HashMap Class: A collection that maps keys to values.
4. HashSet Class: Implements a set backed by a hash table.
5. Date Class: Represents date and time in Java.
6. Collections Class: A utility class that provides static methods to operate on collections (like sort, reverse,
shuffle, etc.).

1. List Interface
The List interface represents an ordered collection (also known as a sequence). It extends the Collection
interface.
Syntax:
List<Type> list = new ArrayList<Type>();
Example:
import java.util.List;
import java.util.ArrayList;

public class ListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}

Output:

Apple
Banana
Cherry

Explanation:
• The List interface ensures elements are stored in the order they are added.
• The ArrayList class implements the List interface, providing dynamic array behavior.

2. ArrayList Class
The ArrayList class is a resizable array, which grows dynamically as elements are added or removed.
Syntax:
ArrayList<Type> arrayList = new ArrayList<Type>();
Example:
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

System.out.println("Numbers in ArrayList: " + numbers);


}
}

Output:

Numbers in ArrayList: [10, 20, 30]


Explanation:
• The ArrayList class provides methods like add(), remove(), and get() for easy manipulation of the dynamic
array.

3. HashMap Class
The HashMap class provides a way to store key-value pairs. Keys must be unique, but values can be duplicated.
Syntax:
HashMap<KeyType, ValueType> hashMap = new HashMap<>();

Example:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

System.out.println("Value for Apple: " + map.get("Apple"));


}
}

Output:

Value for Apple: 1

Explanation:
• The HashMap uses a hash table for storing key-value pairs, making lookups and insertions fast.
• The get() method retrieves a value using the associated key.

4. HashSet Class
The HashSet class implements the Set interface and stores elements uniquely (no duplicates).

Syntax:
HashSet<Type> hashSet = new HashSet<Type>();

Example:
import java.util.HashSet;

public class HashSetExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate entry

System.out.println("Elements in HashSet: " + set);


}
}

Output:

Elements in HashSet: [Apple, Banana]

Explanation:
• The HashSet does not allow duplicate elements.
• It is useful when you need to ensure uniqueness in a collection.

5. Date Class
The Date class represents a specific instant in time, with millisecond precision.
Syntax:
Date date = new Date();
Example:
import java.util.Date;

public class DateExample {


public static void main(String[] args) {
Date date = new Date();
System.out.println("Current Date: " + date);
}
}

Output:

Current Date: Mon Sep 09 10:00:00 UTC 2024

Explanation:
• The Date class is used to work with date and time. However, it is largely replaced by the java.time package
in Java 8 and later versions.

6. Collections Class
The Collections class provides static methods to operate on or return collections, such as sorting or reversing
lists.

Syntax:
Collections.sort(list);

Example:
import java.util.ArrayList;
import java.util.Collections;

public class CollectionsExample {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(20);
numbers.add(10);
numbers.add(30);

Collections.sort(numbers);
System.out.println("Sorted List: " + numbers);
}
}

Output:

Sorted List: [10, 20, 30]

Explanation:
• The Collections.sort() method sorts elements in ascending order.
• The Collections class also has methods for reversing, shuffling, and searching collections.
Do It Yourself

1. Write a program to add elements to an ArrayList and display them.


2. Create a HashMap to store the names of cities as keys and their population as values. Retrieve a city's
population using its name.
3. Write a program to sort a list of student names using the Collections.sort() method.
4. Implement a HashSet to store unique words from a sentence.
5. Write a program that uses the Date class to display the current date and time.

Quiz

1. Which class in java.util is used to store key-value pairs?


a) ArrayList
b) HashSet
c) HashMap
d) List
Answer: c) HashMap

2. What is the output of the following code snippet?

HashSet<String> set = new HashSet<>();


set.add("A");
set.add("B");
set.add("A");
System.out.println(set.size());

a) 1
b) 2
c) 3
d) 0
Answer: b) 2

3. Which of the following is a method of the Collections class?


a) add()
b) sort()
c) remove()
d) contains()
Answer: b) sort()

4. What is the main purpose of the Date class?

a) To manipulate strings
b) To represent and manipulate dates and times
c) To store key-value pairs
d) To manage collections
Answer: b) To represent and manipulate dates and times

5. What is the result of calling Collections.sort() on a list of integers?


a) The list is reversed.
b) The list is sorted in ascending order.
c) The list is unchanged.
d) The list is shuffled.
Answer: b) The list is sorted in ascending order.

Formatter Class in Java: Detailed Reading Material


The Formatter class in Java is part of the java.util package and provides support for creating formatted output.
It is useful for formatting data into a specific structure, similar to how printf works in C. The Formatter class
allows you to format strings, numbers, dates, and other objects and supports localization.
Syntax
Formatter formatter = new Formatter();
formatter.format(formatString, arguments);

The format string consists of regular text and format specifiers. Format specifiers begin with a % symbol,
followed by the format type. For example:

• %d for integers
• %f for floating-point numbers
• %s for strings
Common Format Specifiers
Specifier Description

%d Decimal integer

%f Floating-point numbers

%s String

%x Hexadecimal integer

%o Octal integer

%n Platform-specific newline

Example 1: Formatting an Integer and a String


import java.util.Formatter;

public class FormatterExample {


public static void main(String[] args) {
Formatter formatter = new Formatter();

int num = 42;


String text = "students";

formatter.format("There are %d %s in the class.", num, text);


System.out.println(formatter);

formatter.close();
}
}

Output:

There are 42 students in the class.


Example 2: Formatting Floating-Point Numbers
import java.util.Formatter;

public class FloatFormatterExample {


public static void main(String[] args) {
Formatter formatter = new Formatter();

double value = 123.456;

formatter.format("The value is %.2f", value); // Rounds to two decimal places


System.out.println(formatter);

formatter.close();
}
}

Output:

The value is 123.46

Explanation
• Formatter Class: The Formatter class can be used to format multiple types of data. It can write formatted
output to various destinations, such as files, strings, or System.out.

• Specifiers: Format specifiers allow flexibility in how data is displayed. For example, %d displays integers,
while %.2f formats floating-point numbers to two decimal places.

• Closing the Formatter: It’s important to close the Formatter object to free up resources after use.

Example 3: Formatting with Localization


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

public class LocaleFormatterExample {


public static void main(String[] args) {
Formatter formatter = new Formatter(Locale.FRANCE);

double price = 99.99;

formatter.format("The price in France is €%.2f", price);


System.out.println(formatter);

formatter.close();
}
}
Output:

The price in France is €99,99


Practice Program
Create a program that formats student information (name, grade, and GPA) using the Formatter class:

import java.util.Formatter;

public class StudentFormatter {


public static void main(String[] args) {
Formatter formatter = new Formatter();

String name = "Alice";


int grade = 10;
double gpa = 3.75;

formatter.format("Name: %s%nGrade: %d%nGPA: %.2f", name, grade, gpa);


System.out.println(formatter);

formatter.close();
}
}

Do It Yourself

1. Write a Java program that uses the Formatter class to format a person's age, name, and height.
2. Format a floating-point number to three decimal places using Formatter.
3. Create a program that formats a date in the form "Day/Month/Year" using the Formatter class.
4. Write a program that formats a product's name and price using Formatter.
5. Practice using format specifiers to display hexadecimal and octal numbers.

Quiz

1. What is the purpose of the Formatter class in Java?

a) To format data for display.


b) To sort numbers.
c) To calculate the sum of numbers.
d) To read data from files.

Answer: a) To format data for display.

2. What does the %d format specifier represent in Formatter?

a) Decimal integer
b) Floating-point number
c) Hexadecimal number
d) String

Answer: a) Decimal integer


3. Which method is used to close a Formatter object?

a) end()
b) finish()
c) close()
d) terminate()

Answer: c) close()

4. How do you format a floating-point number to two decimal places using Formatter?

a) %.2f
b) %2f
c) %f
d) %2.0f

Answer: a) %.2f

5. What will be the output of the following code?

Formatter f = new Formatter();


f.format("%d", 42);
System.out.println(f);
f.close();

a) 42
b) 042
c) Error
d) "Formatted number: 42"

Answer: a) 42

Random Class in Java:


The Random class in Java is part of the java.util package and is used to generate pseudo-random numbers. It
provides several methods to generate random numbers of different data types like int, double, float, long, etc.
It can be initialized with an optional seed, which determines the starting point for the sequence of pseudo-
random numbers.

Key Features of the Random Class:


• Generates pseudo-random numbers for various data types.
• Can be seeded to produce a predictable sequence of numbers.
• Commonly used for generating random numbers in simulations, games, cryptography (although it's not
secure), and for generating random test data.

Syntax:
To use the Random class, import the java.util.Random package:

import java.util.Random;
Creating an instance of the Random class:

Random random = new Random(); // No seed


Random randomWithSeed = new Random(100); // With seed

Methods of Random Class:


1. nextInt(): Returns a random integer.
2. nextInt(int bound): Returns a random integer between 0 (inclusive) and the specified bound (exclusive).
3. nextDouble(): Returns a random double value between 0.0 and 1.0.
4. nextFloat(): Returns a random float value between 0.0 and 1.0.
5. nextLong(): Returns a random long value.
6. nextBoolean(): Returns a random boolean value (true or false).

Examples of Random Class


Example 1: Generating a Random Integer
import java.util.Random;

public class RandomExample {


public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt();
System.out.println("Random Integer: " + randomNumber);
}
}

Output:

Random Integer: 123456789 (The output will vary each time)


Example 2: Generating a Random Integer within a Range
import java.util.Random;

public class RandomBoundExample {


public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(50); // Generates a number between 0 and 49
System.out.println("Random Integer (0-49): " + randomNumber);
}
}

Output:

Random Integer (0-49): 23 (The output will vary each time)

Example 3: Generating Random Double, Float, Long, and Boolean


import java.util.Random;

public class RandomDataTypesExample {


public static void main(String[] args) {
Random random = new Random();
System.out.println("Random Double: " + random.nextDouble());
System.out.println("Random Float: " + random.nextFloat());
System.out.println("Random Long: " + random.nextLong());
System.out.println("Random Boolean: " + random.nextBoolean());
}
}

Output:

Random Double: 0.5435783


Random Float: 0.7374783
Random Long: -9214567890123456789
Random Boolean: true

Explanation
• Seeding: When you provide a seed to the Random class, it generates the same sequence of random
numbers every time. This can be useful in situations where reproducibility is important (e.g., simulations).
If no seed is provided, the numbers generated are truly pseudo-random and will differ between
executions.

Example 4: Seeding Random Numbers


import java.util.Random;

public class RandomSeedExample {


public static void main(String[] args) {
Random random = new Random(100);
System.out.println("Random Integer with Seed: " + random.nextInt());
System.out.println("Random Double with Seed: " + random.nextDouble());
}
}

Output:

Random Integer with Seed: 1732584193


Random Double with Seed: 0.7232309478433456

(The output will be the same every time you run this program due to the seed.)

Practice Programs
Practice Program 1: Generate 10 Random Numbers
Write a Java program to generate and print 10 random integers between 1 and 100.

import java.util.Random;

public class GenerateTenRandomNumbers {


public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int num = random.nextInt(100) + 1; // Generates numbers between 1 and 100
System.out.println("Random Number " + (i+1) + ": " + num);
}
}
}

Practice Program 2: Random Boolean Generator


Create a program that generates 5 random boolean values and counts how many are true and how many are
false.

import java.util.Random;

public class RandomBooleanCounter {


public static void main(String[] args) {
Random random = new Random();
int trueCount = 0, falseCount = 0;

for (int i = 0; i < 5; i++) {


boolean bool = random.nextBoolean();
if (bool) {
trueCount++;
} else {
falseCount++;
}
System.out.println("Random Boolean " + (i+1) + ": " + bool);
}

System.out.println("Number of true values: " + trueCount);


System.out.println("Number of false values: " + falseCount);
}
}

Practice Program 3: Random Dice Roll


Simulate rolling two dice and calculate the sum of their values.

import java.util.Random;

public class RandomDiceRoll {


public static void main(String[] args) {
Random random = new Random();
int dice1 = random.nextInt(6) + 1;
int dice2 = random.nextInt(6) + 1;

System.out.println("Dice 1: " + dice1);


System.out.println("Dice 2: " + dice2);
System.out.println("Sum of two dice: " + (dice1 + dice2));
}
}

Explanation of Key Concepts:


• Pseudo-random Numbers: The numbers generated by the Random class are pseudo-random, meaning
they are not truly random but are generated using a deterministic algorithm.
• Seeding: When a seed is provided to the Random class, the same sequence of numbers will be generated
every time, making it useful for testing and simulations where repeatability is important.

Do It Yourself

1. Write a program to generate a random password of 8 characters, containing both letters and numbers.
2. Create a Java program to generate 5 random floating-point numbers between 0 and 1.
3. Simulate flipping a coin 100 times and count how many times it lands on heads (true) and tails (false).
4. Write a program that generates a random date between the years 2000 and 2024.

Quiz

1. What does the nextInt() method do in the Random class?

a) Returns a random integer within a specified bound.


b) Returns a random integer without any bounds.
c) Returns a random double.
d) Returns a random boolean.
Answer: b) Returns a random integer without any bounds.

2. What will be the output of the following code?

Random random = new Random();


System.out.println(random.nextInt(10));
a) A random integer between 0 and 9.
b) A random integer between 1 and 10.
c) A random integer between 0 and 10.
d) A random integer between 1 and 9.
Answer: a) A random integer between 0 and 9.

3. Which method of Random is used to generate a random boolean?

a) nextBoolean()
b) nextInt()
c) nextLong()
d) nextDouble()
Answer: a) nextBoolean()

4. What will be the result if you use a seed in the Random constructor?
a) Generates truly random numbers every time.
b) Generates a predictable sequence of random numbers.
c) Does not affect the random number generation.
d) Generates numbers only within a range.
Answer: b) Generates a predictable sequence of random numbers.

5. Which of the following methods generates a random floating-point number between 0.0 and 1.0?

a) nextFloat()
b) nextInt()
c) nextDouble()
d) Both a and c.
Answer: d) Both a and c.
`
Time Package Classes
1. LocalDate Class
LocalDate represents a date without time. It provides methods to handle operations related to the date such
as manipulation and comparison.

Common Operations:

Getting the current date:

LocalDate today = LocalDate.now();


System.out.println("Today's Date: " + today);

Creating a specific date:

LocalDate specificDate = LocalDate.of(2024, 9, 9);


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

Manipulating dates:

LocalDate nextWeek = today.plusWeeks(1);


System.out.println("Next Week: " + nextWeek);

2. LocalTime Class
LocalTime represents time without date. It’s useful for applications that need to work with time values without
concern for the date.

Common Operations:

Getting the current time:

LocalTime now = LocalTime.now();


System.out.println("Current Time: " + now);

Creating a specific time:

LocalTime specificTime = LocalTime.of(15, 30);


System.out.println("Specific Time: " + specificTime);

Adding time:

LocalTime newTime = now.plusHours(2);


System.out.println("Time After 2 Hours: " + newTime);

3. LocalDateTime Class
LocalDateTime combines both date and time without any timezone information. It is ideal for working with
complete date-time values.

Common Operations:
Getting the current date and time:

LocalDateTime now = LocalDateTime.now();


System.out.println("Current DateTime: " + now);

Creating a specific date and time:

LocalDateTime specificDateTime = LocalDateTime.of(2024, 9, 9, 10, 30);


System.out.println("Specific DateTime: " + specificDateTime);

Manipulating date and time:

LocalDateTime futureDateTime = now.plusMonths(1);


System.out.println("DateTime After 1 Month: " + futureDateTime);

4. ZonedDateTime Class
ZonedDateTime represents date and time with timezone information. It’s useful for applications needing to
handle global time zones.

Common Operations:

Getting the current date, time, and zone:

ZonedDateTime now = ZonedDateTime.now();


System.out.println("Current ZonedDateTime: " + now);

Creating a specific date, time, and timezone:

ZoneId zoneId = ZoneId.of("America/New_York");


ZonedDateTime specificZonedDateTime = ZonedDateTime.of(2024, 9, 9, 10, 30, 0, 0, zoneId);
System.out.println("Specific ZonedDateTime: " + specificZonedDateTime);

Changing the timezone:

ZonedDateTime newTimeZone = now.withZoneSameInstant(ZoneId.of("Europe/London"));


System.out.println("DateTime in London: " + newTimeZone);

5. Duration Class
Duration represents the amount of time between two Temporal objects, such as hours, minutes, and seconds.

Common Operations:

Finding the duration between two times:


LocalTime startTime = LocalTime.of(9, 0);
LocalTime endTime = LocalTime.of(17, 30);
Duration duration = Duration.between(startTime, endTime);
System.out.println("Duration: " + duration);

Adding duration:

Duration addedDuration = duration.plusHours(1);


System.out.println("Duration Plus 1 Hour: " + addedDuration);
6. Period Class
Period represents a period of time in terms of years, months, and days.

Common Operations:

Finding the period between two dates:

LocalDate startDate = LocalDate.of(2020, 1, 1);


LocalDate endDate = LocalDate.now();
Period period = Period.between(startDate, endDate);
System.out.println("Period: " + period);

Adding period:

Period addedPeriod = period.plusMonths(6);


System.out.println("Period Plus 6 Months: " + addedPeriod);

Practice Programs

1. Display the Current Date, Time, and Time Zone:

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class DisplayCurrentZonedDateTime {


public static void main(String[] args) {
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
System.out.println("Current ZonedDateTime: " + currentZonedDateTime);
}
}

2. Calculate Duration Between Two LocalTime Instances:

import java.time.LocalTime;
import java.time.Duration;

public class CalculateDuration {


public static void main(String[] args) {
LocalTime start = LocalTime.of(8, 0);
LocalTime end = LocalTime.of(17, 0);
Duration duration = Duration.between(start, end);
System.out.println("Duration: " + duration);
}
}

3. Find the Period Between Two LocalDate Instances:

import java.time.LocalDate;
import java.time.Period;
public class CalculatePeriod {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2021, 1, 1);
LocalDate end = LocalDate.now();
Period period = Period.between(start, end);
System.out.println("Period: " + period);
}
}

4. Add 5 Hours to the Current Time Using Duration:

import java.time.LocalTime;
import java.time.Duration;

public class AddHours {


public static void main(String[] args) {
LocalTime now = LocalTime.now();
LocalTime newTime = now.plus(Duration.ofHours(5));
System.out.println("Time After 5 Hours: " + newTime);
}
}

Do It Yourself

1. Display the current date and time for the "Asia/Kolkata" time zone using ZonedDateTime.
2. Write a program to calculate the number of days between your birth date and today using Period.
3. Create a program that finds the difference between two LocalDateTime instances and displays it as days,
hours, and minutes.
4. Develop a program that subtracts 30 minutes from the current LocalTime and displays the result.
5. Write a Java program that displays the current date and time in two different time zones (e.g.,
"Europe/Paris" and "Asia/Tokyo") using ZonedDateTime.

Quiz

1. Which class is used to represent a date and time with timezone information in Java?
a) LocalDate
b) LocalTime
c) ZonedDateTime
d) LocalDateTime
Answer: c) ZonedDateTime

2. What does the Duration class measure in Java?

a) Days, months, and years


b) Hours, minutes, and seconds
c) Date and time with timezone
d) Timezones only
Answer: b) Hours, minutes, and seconds

3. Which method of LocalDate returns the current date?

a) getDate()
b) now()
c) current()
d) today()
Answer: b) now()

java.time.Instant Class
The Instant class in the java.time package represents a specific moment on the timeline in UTC (Coordinated
Universal Time) with nanosecond precision. It’s a part of the Java Date and Time API introduced in Java 8.
Instant is ideal for capturing timestamps and performing time-related operations.

1. Syntax and Overview


Creating an Instant Object:

Current Instant:

Instant now = Instant.now();


System.out.println("Current Instant: " + now);

Specific Instant:
Instant specificInstant = Instant.ofEpochSecond(1609459200); // 1st Jan 2021 00:00:00 UTC
System.out.println("Specific Instant: " + specificInstant);

From Epoch Milliseconds:


Instant instantFromMillis = Instant.ofEpochMilli(1609459200000L); // 1st Jan 2021 00:00:00 UTC
System.out.println("Instant from Milliseconds: " + instantFromMillis);

Manipulating Instants:

Adding Duration:

Instant now = Instant.now();


Instant futureInstant = now.plus(Duration.ofDays(10));
System.out.println("Instant After 10 Days: " + futureInstant);

Subtracting Duration:

Instant now = Instant.now();


Instant pastInstant = now.minus(Duration.ofHours(5));
System.out.println("Instant 5 Hours Ago: " + pastInstant);

Comparing Instants:

Before and After Comparison:

Instant now = Instant.now();


Instant futureInstant = now.plus(Duration.ofDays(1));
boolean isBefore = now.isBefore(futureInstant);
boolean isAfter = now.isAfter(futureInstant);
System.out.println("Is now before futureInstant? " + isBefore);
System.out.println("Is now after futureInstant? " + isAfter);
Practice Programs
1. Display the Current Instant:

import java.time.Instant;

public class DisplayCurrentInstant {


public static void main(String[] args) {
Instant now = Instant.now();
System.out.println("Current Instant: " + now);
}
}

2. Create an Instant for a Specific Date and Time:

import java.time.Instant;

public class SpecificInstant {


public static void main(String[] args) {
Instant specificInstant = Instant.ofEpochSecond(1609459200); // 1st Jan 2021
System.out.println("Specific Instant: " + specificInstant);
}
}

3. Add and Subtract Duration to/from an Instant:

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

public class DurationManipulation {


public static void main(String[] args) {
Instant now = Instant.now();
Instant futureInstant = now.plus(Duration.ofDays(10));
Instant pastInstant = now.minus(Duration.ofHours(5));
System.out.println("Instant After 10 Days: " + futureInstant);
System.out.println("Instant 5 Hours Ago: " + pastInstant);
}
}

4. Compare Two Instants:

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

public class CompareInstants {


public static void main(String[] args) {
Instant now = Instant.now();
Instant futureInstant = now.plus(Duration.ofDays(1));
System.out.println("Is now before futureInstant? " + now.isBefore(futureInstant));
System.out.println("Is now after futureInstant? " + now.isAfter(futureInstant));
}
}

Do It Yourself

1. Write a Java program that prints the current timestamp using Instant.
2. Create an Instant object for a timestamp representing 1st January 2022 at 12:00:00 UTC and display it.
3. Write a program that calculates and prints the Instant exactly 30 days from the current Instant.
4. Create an Instant object for a timestamp 5 hours before the current time and display it.
5. Compare two Instant objects—one representing the current time and another representing a time exactly
one week in the future—and print if the first one is before or after the second.

Quiz

1. Which method is used to obtain the current Instant?

a) Instant.create()
b) Instant.now()
c) Instant.current()
d) Instant.get()
Answer: b) Instant.now()

2. How do you create an Instant object from epoch seconds?


a) Instant.ofEpochSecond(long epochSecond)
b) Instant.ofEpochSeconds(long epochSecond)
c) Instant.fromEpochSecond(long epochSecond)
d) Instant.fromEpochSeconds(long epochSecond)
Answer: a) Instant.ofEpochSecond(long epochSecond)

3. Which class provides methods to manipulate time spans, such as adding or subtracting time?

a) DateTime
b) Duration
c) Period
d) Temporal
Answer: b) Duration

4. Which method checks if one Instant is before another?

a) isEarlier()
b) isBefore()
c) compareTo()
d) before()
Answer: b) isBefore()

5. What is the precision of Instant?

a) Seconds
b) Milliseconds
c) Nanoseconds
d) Minutes
Answer: c) Nanoseconds
Formatting for Date/Time
Formatting for date and time in Java is essential for converting date and time objects into readable string
representations and vice versa. The Java Date and Time API provides various classes and methods to handle
date/time formatting and parsing efficiently.

1. Overview
Java provides several classes for formatting date and time:

• DateTimeFormatter (Java 8 and later) - Provides comprehensive support for formatting and parsing date-
time objects.
• SimpleDateFormat (pre-Java 8) - A legacy class for formatting and parsing dates.

Note: For new development, it is recommended to use DateTimeFormatter from the java.time package
introduced in Java 8.

2. DateTimeFormatter Class
Overview:

• DateTimeFormatter is used to format and parse date-time objects.


• It is part of the java.time.format package.

Syntax:

• Create a Formatter:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

• Format a LocalDateTime:

LocalDateTime dateTime = LocalDateTime.now();


String formattedDateTime = dateTime.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);

• Parse a String to LocalDateTime:

String dateTimeStr = "2024-09-09 15:30:00";


LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, formatter);
System.out.println("Parsed DateTime: " + parsedDateTime);

Common Patterns:

• yyyy - Year
• MM - Month
• dd - Day
• HH - Hour (24-hour format)
• mm - Minutes
• ss – Seconds
Picture:
• DateTimeFormatter Pattern Examples

3. SimpleDateFormat Class
Overview:
• SimpleDateFormat is a legacy class from java.text package used for date formatting and parsing.
• It is still useful but is generally replaced by DateTimeFormatter in modern applications.

Syntax:

• Create a Formatter:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

• Format a Date:

Date date = new Date();


String formattedDate = formatter.format(date);
System.out.println("Formatted Date: " + formattedDate);

• Parse a String to Date:

String dateStr = "2024-09-09 15:30:00";


Date parsedDate = formatter.parse(dateStr);
System.out.println("Parsed Date: " + parsedDate);

Common Patterns:
• yyyy - Year
• MM - Month
• dd - Day
• HH - Hour (24-hour format)
• mm - Minutes
• ss - Seconds

4. Practice Programs
1. Format Current Date and Time:

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

public class FormatDateTime {


public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String formattedNow = now.format(formatter);
System.out.println("Current DateTime: " + formattedNow);
}
}
2. Parse a String to LocalDate:

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

public class ParseDate {


public static void main(String[] args) {
String dateStr = "2024-09-09";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(dateStr, formatter);
System.out.println("Parsed Date: " + date);
}
}

3. Convert Date to String with SimpleDateFormat:

import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertDateToString {


public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String formattedDate = formatter.format(now);
System.out.println("Formatted Date: " + formattedDate);
}
}

4. Parse a String to Date using SimpleDateFormat:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseStringToDate {


public static void main(String[] args) {
String dateStr = "09/09/2024 15:30:00";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date date = formatter.parse(dateStr);
System.out.println("Parsed Date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Do It Yourself
1. Write a program that formats the current date and time using DateTimeFormatter with the pattern dd-
MM-yyyy HH:mm:ss.
2. Create a program that parses a string representing a date in the format yyyy/MM/dd into a LocalDate
object.
3. Use SimpleDateFormat to format the current date in the pattern MMMM d, yyyy (e.g., September 9,
2024).
4. Write a program that parses a date string 01-01-2024 into a Date object using SimpleDateFormat.
5. Convert the current LocalDateTime to a string with the pattern yyyy-MM-dd'T'HH:mm:ss and then parse it
back to a LocalDateTime object.

Quiz

1. Which class is used for formatting and parsing date-time objects introduced in Java 8?

a) SimpleDateFormat
b) DateTimeFormatter
c) DateFormatter
d) TimeFormatter
Answer: b) DateTimeFormatter

2. How do you specify the pattern yyyy-MM-dd HH:mm:ss using DateTimeFormatter?

a) DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
b) DateTimeFormatter.create("yyyy-MM-dd HH:mm:ss")
c) DateTimeFormatter.pattern("yyyy-MM-dd HH:mm:ss")
d) DateTimeFormatter.format("yyyy-MM-dd HH:mm:ss")
Answer: a) DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

3. What is the purpose of the parse method in SimpleDateFormat?

a) To format a date object into a string.


b) To parse a string into a date object.
c) To convert a date object to a time object.
d) To validate a date string.
Answer: b) To parse a string into a date object.

4. Which pattern would you use to format a date as January 1, 2024 using SimpleDateFormat?
a) MMMM d, yyyy
b) dd/MM/yyyy
c) yyyy-MM-dd
d) MM-dd-yyyy
Answer: a) MMMM d, yyyy

5. What method of DateTimeFormatter returns the formatted string representation of a date-time object?

a) format()
b) parse()
c) toString()
d) display()
Answer: a) format()
TemporalAdjusters Class in Java
The TemporalAdjusters class in Java provides a powerful mechanism for manipulating date and time objects.
Adjusters allow us to modify a Temporal object, such as adjusting a date to the next Tuesday or setting the
date to the last day of the month. These adjusters simplify the process of modifying date and time values.
Introduction to TemporalAdjusters
The TemporalAdjuster interface defines a contract for classes that adjust temporal objects, such as LocalDate
or LocalDateTime. An adjuster takes a temporal object and returns a modified version of it. This modification
could be anything, such as changing the day of the month, moving to the next weekday, or adjusting the date
to the first day of the year.

There are two main ways to use a TemporalAdjuster:

1. Directly invoking the adjustInto method on the adjuster.


2. Using the with method on the Temporal object, passing the TemporalAdjuster as an argument.

Here’s an example demonstrating both ways, which produce equivalent results:

temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);

It is recommended to use the second approach because it is more readable and aligns with functional
programming principles.
Common Temporal Adjusters
The TemporalAdjusters class provides several predefined adjusters that can be used to modify temporal
objects. Here are some of the key methods:

Method Description

dayOfWeekInMonth(int ordinal, Returns a new date object set to the specified ordinal
DayOfWeek) occurrence of the given day-of-week within the current
month.

firstDayOfMonth() Returns a new date set to the first day of the current
month.

firstDayOfNextMonth() Returns a new date set to the first day of the next month.

firstDayOfNextYear() Returns a new date set to the first day of the next year.

firstDayOfYear() Returns a new date set to the first day of the current year.

firstInMonth(DayOfWeek) Returns a new date set to the first occurrence of the


specified day-of-week within the current month.

lastDayOfMonth() Returns a new date set to the last day of the current
month.

lastDayOfYear() Returns a new date set to the last day of the current year.
Method Description

lastInMonth(DayOfWeek) Returns a new date set to the last occurrence of the


specified day-of-week within the current month.

next(DayOfWeek) Returns a new date set to the next occurrence of the


specified day-of-week after the current date.

nextOrSame(DayOfWeek) Returns a new date set to the next occurrence of the


specified day-of-week after the current date, or the same
date if it’s already that day.

ofDateAdjuster(UnaryOperator<LocalDate>) Returns a TemporalAdjuster that wraps a custom date


adjuster.

previous(DayOfWeek) Returns a new date set to the previous occurrence of the


specified day-of-week before the current date.

previousOrSame(DayOfWeek) Returns a new date set to the previous occurrence of the


specified day-of-week before the current date, or the same
date if it’s already that day.
Examples of Using TemporalAdjusters
Below is an example implementation of the TemporalAdjusters class. The output will vary based on the date of
execution, as it adjusts the current date based on the specified conditions.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class TemporalAdjusterExample {


public static void main(String[] args) {
// Get the current date
LocalDate currentDate = LocalDate.now();
System.out.println("Today's date is: " + currentDate);

// Get the next Monday


LocalDate nextMonday = currentDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday is on: " + nextMonday);

// Get the second Saturday of the next month


LocalDate firstOfNextMonth = currentDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
LocalDate secondSaturday =
firstOfNextMonth.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY))
.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
System.out.println("Second Saturday of next month is on: " + secondSaturday);
}
}

Explanation of the Code:


1. Current Date: The program retrieves the current date using LocalDate.now() and prints it.
2. Next Monday: The method TemporalAdjusters.next(DayOfWeek.MONDAY) adjusts the current date to
the next Monday.
3. Second Saturday of Next Month:
• The program first gets the first day of the next month using plusMonths(1) and
with(TemporalAdjusters.firstDayOfMonth()).
• Then, it finds the second Saturday using two adjusters: first, nextOrSame(DayOfWeek.SATURDAY)
to get the first Saturday, followed by next(DayOfWeek.SATURDAY) to find the second.
Sample Output (assuming today is 2024-09-16):
Today's date is: 2024-09-16
Next Monday is on: 2024-09-23
Second Saturday of next month is on: 2024-10-12

The TemporalAdjusters class provides an efficient and readable way to manipulate date objects. Whether
you're adjusting dates to find the next Monday or the second Saturday of the month, TemporalAdjusters can
simplify the logic and make the code more maintainable.

What is Exception Handling?


Exception handling is a programming mechanism designed to manage runtime errors, such as
ClassNotFoundException, IOException, SQLException, and RemoteException. It allows developers to address
and resolve these issues gracefully without abruptly terminating the program.
Advantages of Exception Handling
The primary benefit of exception handling is that it ensures the continuous operation of an application even
when errors occur. Without exception handling, an error could halt the execution of the program, preventing
subsequent code from running. Here's an example to illustrate this:

Consider a Java program with the following sequence of statements:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

If an exception arises at statement 5, the remaining statements (statement 6 through statement 10) will not
be executed. Exception handling allows the program to manage the error at statement 5 and continue
executing the subsequent statements, thereby maintaining the normal flow of the application. This capability
is crucial for ensuring that the program remains functional and responsive even in the face of errors.
2. Hierarchy of Standard Exception Classes
In Java, exception handling is structured around a class hierarchy that helps manage errors in a systematic
way. Here's an overview of the key classes and interfaces in the Java exception hierarchy:
1. Throwable
• Definition: The base class for all errors and exceptions in Java. It has two main subclasses: Error and
Exception.
• Key Methods: getMessage(), printStackTrace(), toString()
2. Error
• Definition: Represents severe errors that are usually beyond the control of the application. These errors
are not meant to be caught by applications.
• Common Subclasses:
o OutOfMemoryError
o StackOverflowError
o VirtualMachineError
3. Exception
• Definition: Represents conditions that a reasonable application might want to catch. This is the superclass
of all exceptions.
• Key Subcategories:
o Checked Exceptions: Exceptions that must be either caught or declared in the method where they
might be thrown. They are checked at compile-time.
▪ IOException: Represents general input/output errors.
▪ SQLException: Represents database access errors.
▪ ClassNotFoundException: Thrown when an application tries to load a class at runtime but
cannot find its definition.
o Unchecked Exceptions: Also known as runtime exceptions, these do not need to be declared or
caught. They are checked at runtime.
▪ RuntimeException: The superclass of all unchecked exceptions.
▪ ArithmeticException: Thrown when an arithmetic operation fails, such as division
by zero.
▪ NullPointerException: Thrown when the application attempts to use null where an
object is required.
▪ ArrayIndexOutOfBoundsException: Thrown when an array is accessed with an
illegal index.
4. Exception Hierarchy Diagram
Here's a simplified diagram to illustrate the hierarchy:
3. Keywords throws and throw

Keywords throws and throw


In Java, exception handling is a crucial aspect of robust application development. The throws and throw
keywords are fundamental to handling exceptions in Java. Understanding how to use these keywords correctly
can help you manage errors effectively and ensure that your application runs smoothly.

The throw Keyword


Definition
The throw keyword is used to explicitly throw an exception from a method or a block of code. When you use
throw, you create an instance of an exception class and pass it to the Java runtime, which then handles it
according to the exception handling mechanism.
Syntax
throw new ExceptionType("Error message");
Example
Here’s an example of using the throw keyword to throw an ArithmeticException:

public class ThrowExample {


public static void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
System.out.println("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Output:

Caught Exception: Division by zero is not allowed.


Explanation: In this example, the throw keyword is used to explicitly throw an ArithmeticException when
attempting to divide by zero.

The throws Keyword


Definition
The throws keyword is used in a method declaration to specify that a method might throw one or more
exceptions. This informs the caller of the method that they need to handle these exceptions or propagate
them further.
Syntax
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// Method body
}
Example
Here’s an example of using the throws keyword to declare that a method may throw IOException:

import java.io.*;

public class ThrowsExample {


public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
reader.close();
}

public static void main(String[] args) {


try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Output:

Caught Exception: nonexistentfile.txt (No such file or directory)

Explanation: In this example, the readFile method declares that it may throw an IOException. The caller of this
method (in main) must handle this exception using a try-catch block.

Comparison and Use


When to Use throw
• Use throw when you want to manually throw an exception in a specific situation, often when a condition
arises that cannot be handled within the current method.
When to Use throws
• Use throws in a method declaration when you want to indicate that the method might throw exceptions
that need to be handled by the calling code.

Practice Programs
Program 1: Using throw Write a Java program that throws a NumberFormatException if the input is not a valid
integer.

import java.util.Scanner;

public class NumberFormatExceptionDemo {


public static void validateInteger(String input) {
try {
int number = Integer.parseInt(input);
System.out.println("Valid integer: " + number);
} catch (NumberFormatException e) {
throw new NumberFormatException("Invalid integer format: " + input);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
String input = scanner.nextLine();
try {
validateInteger(input);
} catch (NumberFormatException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Program 2: Using throws Write a Java program that declares a method readFile which throws an IOException
and handles the exception in the main method.

import java.io.*;

public class FileReadingDemo {


public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
reader.close();
}

public static void main(String[] args) {


try {
readFile("example.txt");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Do It Yourself
1. Write a program that uses the throw keyword to throw a custom exception when an invalid age (negative
number) is provided.
2. Create a method that declares multiple exceptions using throws and handle them in the main method.
3. Define a custom exception class and use it with the throw keyword in a Java program.
4. Write a program where an exception is thrown in one method and caught in another method that calls it.

Quiz

1. Which keyword is used to explicitly throw an exception?

A) throws
B) throw
C) try
D) catch
Answer: B) throw

2. What must a method do if it declares that it throws exceptions?

A) Handle the exception within the method


B) Declare the exception in its signature
C) Call the method without handling the exception
D) Propagate the exception to the caller

Answer: D) Propagate the exception to the caller

3. What is the correct syntax for declaring that a method might throw an IOException?

A) void methodName() throw IOException


B) void methodName() throws IOException
C) void methodName() throw new IOException
D) void methodName() throws new IOException

Answer: B) void methodName() throws IOException

4. What will happen if you use throw without specifying an exception object?

A) Compilation error
B) Runtime exception
C) The program will continue executing normally
D) It will be ignored
Answer: A) Compilation error

5. Which of the following is true about the throws keyword?

A) It is used within a method to handle exceptions.


B) It is used to declare that a method may throw exceptions.
C) It is used to catch exceptions in the code.
D) It is used to throw a specific exception.

Answer: B) It is used to declare that a method may throw exceptions.


4. try, catch, and finally Blocks

try, catch, and finally Blocks


Exception handling is a crucial concept in Java that helps in managing runtime errors gracefully. The try, catch,
and finally blocks are fundamental components of Java's exception handling mechanism. This material
provides a comprehensive overview of these blocks, including syntax, examples, explanations, and practice
exercises.
The try Block
Definition
The try block is used to enclose code that might throw an exception. It’s the starting point for exception
handling.
Syntax
try {
// Code that might throw an exception
}
Example
public class TryExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 100; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Explanation: In this example, the try block contains code that attempts to access an invalid array index, which
results in an ArrayIndexOutOfBoundsException.

The catch Block


Definition
The catch block is used to handle exceptions thrown by the try block. It catches exceptions of specified types
and allows you to handle them.
Syntax
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example
public class CatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught Exception: Division by zero is not allowed.");
}
}
}
Explanation: Here, the catch block handles the ArithmeticException thrown by the try block and prints an
appropriate message.

The finally Block


Definition
The finally block is used to execute code regardless of whether an exception was thrown or not. It’s often used
for closing resources like files or database connections.
Syntax
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}

Example
import java.io.*;

public class FinallyExample {


public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("test.txt");
// Perform file operations
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
System.out.println("Failed to close file: " + e.getMessage());
}
}
}
}

Explanation: In this example, the finally block ensures that the file is closed regardless of whether an exception
occurs or not.

Practice Programs
Program 1: Nested Try-Catch-Finally Write a Java program that demonstrates the use of nested try, catch, and
finally blocks.

public class NestedTryExample {


public static void main(String[] args) {
try {
System.out.println("Outer try block");
try {
System.out.println("Inner try block");
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: " + e.getMessage());
} finally {
System.out.println("Inner finally block");
}
} catch (Exception e) {
System.out.println("Outer catch block: " + e.getMessage());
} finally {
System.out.println("Outer finally block");
}
}
}
Program 2: Using Finally Block for Resource Management Write a program that uses the finally block to
ensure a resource is always closed.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnectionExample {


public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:invalid:url"); // This will throw SQLException
} catch (SQLException e) {
System.out.println("Caught SQLException: " + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Failed to close connection: " + e.getMessage());
}
}
}
}

Do It Yourself

1. Write a Java program that attempts to access a file that does not exist. Use try, catch, and finally blocks to
handle the exception and ensure that any resources are closed properly.
2. Create a Java program that demonstrates handling multiple exceptions using multiple catch blocks.
3. Write a program that opens a file for reading and ensures that the file is closed using the finally block.
4. implement a Java program that uses nested try, catch, and finally blocks to handle exceptions and ensure
proper cleanup.
5. Define a custom exception class and use it within a try-catch-finally block in a Java program.

Quiz
1. What will happen if an exception occurs in the try block?

A) The finally block will not execute.


B) The program will terminate immediately.
C) Control will pass to the catch block if it exists.
D) The catch block will execute, and then the finally block.
Answer: C) Control will pass to the catch block if it exists.

2. Which block will always execute, regardless of whether an exception occurs?


A) catch
B) try
C) finally
D) throw
Answer: C) finally

3. Can a finally block exist without a catch block?


A) Yes
B) No
C) Only in Java 8 and later versions
D) Only within a try-catch block
Answer: A) Yes

4. What happens if the finally block itself throws an exception?


A) The finally block is ignored, and the program terminates.
B) The exception is propagated, and the finally block's exception is handled by the caller.
C) The catch block handles the finally block's exception.
D) The program will terminate without handling the exception.

Answer: B) The exception is propagated, and the finally block's exception is handled by the caller.

5. Which of the following is true about the try block?


A) It must be followed by a catch block.
B) It must be followed by a finally block.
C) It can be followed by one or more catch blocks and an optional finally block.
D) It can exist without a catch block or finally block.

Answer: C) It can be followed by one or more catch blocks and an optional finally block.

5. Multiple Catch Clauses

In Java, you can handle multiple exceptions using multiple catch clauses. This approach allows you to respond
differently to different types of exceptions thrown by the try block. This document provides a comprehensive
overview of multiple catch clauses, including syntax, examples, explanations, practice programs, homework
questions, and multiple-choice questions.

Introduction to Multiple Catch Clauses


Definition
In Java, a try block can be followed by multiple catch blocks to handle different types of exceptions that may
be thrown. Each catch block is designed to handle a specific type of exception. When an exception is thrown,
the control transfers to the appropriate catch block based on the type of the exception.
Syntax
try {
// Code that might throw exceptions
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} catch (ExceptionType3 e3) {
// Code to handle ExceptionType3
}
Example
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 100; // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Explanation: In this example:

• ArrayIndexOutOfBoundsException is caught by the first catch block.


• If the first exception is not thrown, but an ArithmeticException is thrown, it is caught by the second catch
block.
• The third catch block will handle any other types of exceptions if they occur.

Handling Multiple Exceptions


Advantages
• Specific Handling: Allows different responses for different types of exceptions.
• Granularity: Provides control over exception handling by addressing each exception type separately.

Example
public class MultipleExceptionsHandling {
public static void main(String[] args) {
try {
String str = null;
int length = str.length(); // NullPointerException

int[] numbers = new int[5];


numbers[10] = 100; // ArrayIndexOutOfBoundsException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Explanation: Here, NullPointerException is handled first. If ArrayIndexOutOfBoundsException occurs, it is


caught by the second catch block. Any other exceptions are caught by the last catch block.

Practice Programs
Program 1: Handling Multiple Exceptions

Write a Java program that handles NumberFormatException and ArrayIndexOutOfBoundsException using


multiple catch blocks.

public class NumberFormatExample {


public static void main(String[] args) {
try {
String str = "abc";
int num = Integer.parseInt(str); // NumberFormatException

int[] array = new int[3];


array[5] = 10; // ArrayIndexOutOfBoundsException
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
}

Program 2: Order of Catch Blocks

Create a program to show that catch blocks should be ordered from the most specific exception type to the
most general.

public class OrderOfCatchBlocks {


public static void main(String[] args) {
try {
int[] arr = new int[1];
arr[2] = 5; // ArrayIndexOutOfBoundsException
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
}

Program 3: Catching Multiple Exceptions with Common Handling


Demonstrate how to handle multiple exceptions with similar handling code.
public class CommonHandlingExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 10; // ArrayIndexOutOfBoundsException
String str = null;
str.length(); // NullPointerException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Do It Yourself

1. Write a Java program that handles IOException, FileNotFoundException, and NumberFormatException


using multiple catch blocks.
2. Define a custom exception and use it in a try-catch block along with standard exceptions.
3. Write a program that demonstrates handling an exception thrown from within a catch block.
4. Create a Java program that shows how exceptions are propagated through methods with multiple catch
blocks.
5. Write a program that handles multiple exceptions using a single catch block.

Quiz

1. What will happen if multiple catch blocks handle the same type of exception?
A) Only the first catch block will execute.
B) All catch blocks will execute.
C) The catch blocks will be ignored.
D) The first catch block that matches the exception will execute.

Answer: D) The first catch block that matches the exception will execute.

2. Which exception type should be caught first when handling exceptions?


A) The most general exception
B) The most specific exception
C) Any exception type
D) It does not matter

Answer: B) The most specific exception

3. Can a catch block handle more than one exception type?


A) Yes, starting from Java 7.
B) No, it can handle only one exception type.
C) Yes, but only for checked exceptions.
D) Yes, but only for unchecked exceptions.

Answer: A) Yes, starting from Java 7.

4. What will the following code output?


try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
} catch (Exception e) {
System.out.println("Exception caught");
}

A) ArithmeticException caught
B) Exception caught
C) Both messages
D) No output

Answer: A) ArithmeticException caught

5. In the following code, which catch block will execute?

try {
throw new FileNotFoundException();
} catch (IOException e) {
System.out.println("IOException caught");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught");
}

A) IOException caught
B) FileNotFoundException caught
C) Both messages
D) No output

Answer: A) IOException caught

6. Class Throwable

Class Throwable
The Throwable class in Java is the superclass of all errors and exceptions in the Java language. This document
provides an in-depth exploration of the Throwable class, including its methods, examples, explanations,
practice programs, homework questions, and multiple-choice questions.

Introduction to Throwable Class


Definition
The Throwable class is the root class for all errors and exceptions in Java. It has two main subclasses: Error and
Exception. All exceptions and errors are derived from this class, making it the base class for error handling in
Java.
Hierarchy
• java.lang.Object
• java.lang.Throwable
• java.lang.Error
• java.lang.Exception
• java.lang.RuntimeException
• Other Exception subclasses (e.g., IOException, SQLException)
Syntax
The Throwable class has two main constructors:

public class Throwable {


// Default constructor
public Throwable();

// Constructor that accepts a detail message


public Throwable(String message);

// Constructor that accepts a detail message and cause


public Throwable(String message, Throwable cause);

// Constructor that accepts a cause


public Throwable(Throwable cause);
}
Methods
Some of the key methods in the Throwable class are:

• String getMessage(): Returns the detail message string of this throwable.


• String toString(): Returns a short description of this throwable.
• Throwable getCause(): Returns the cause of this throwable or null if the cause is nonexistent or unknown.
• StackTraceElement[] getStackTrace(): Provides the stack trace information.
• void printStackTrace(): Prints the stack trace of this throwable to the standard error stream.

Examples
Example 1: Basic Usage of Throwable
public class ThrowableExample {
public static void main(String[] args) {
try {
throw new Throwable("This is a throwable message");
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
t.printStackTrace();
}
}
}

Explanation: This example demonstrates how to throw and catch a Throwable. The message is retrieved using
getMessage(), and the stack trace is printed using printStackTrace().
Example 2: Custom Exception Using Throwable
public class CustomThrowable extends Throwable {
public CustomThrowable(String message) {
super(message);
}
}
public class CustomThrowableExample {
public static void main(String[] args) {
try {
throw new CustomThrowable("Custom Throwable Exception");
} catch (CustomThrowable e) {
System.out.println("Caught CustomThrowable: " + e.getMessage());
e.printStackTrace();
}
}
}

Explanation: This example creates a custom exception class that extends Throwable. The custom exception is
thrown and caught with specific handling.

Practice Programs
Program 1: Handling Generic Throwable Write a Java program that demonstrates how to catch all types of
throwables and print their messages and stack traces.

public class GenericThrowableHandling {


public static void main(String[] args) {
try {
throw new ArithmeticException("Arithmetic Exception");
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
t.printStackTrace();
}
}
}

Program 2: Exception with Cause Create a program where you throw a Throwable with a cause and
demonstrate how to retrieve and print the cause.

public class ThrowableWithCauseExample {


public static void main(String[] args) {
try {
Throwable cause = new Throwable("Root cause");
throw new Throwable("Exception with cause", cause);
} catch (Throwable t) {
System.out.println("Caught Throwable: " + t.getMessage());
System.out.println("Cause: " + t.getCause());
t.printStackTrace();
}
}
}

Program 3: Custom Exception with Stack Trace Define a custom exception that prints a custom stack trace
message.

public class CustomExceptionWithStackTrace extends Throwable {


public CustomExceptionWithStackTrace(String message) {
super(message);
}

@Override
public void printStackTrace() {
System.out.println("Custom stack trace message:");
super.printStackTrace();
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
try {
throw new CustomExceptionWithStackTrace("Custom Exception");
} catch (CustomExceptionWithStackTrace e) {
e.printStackTrace();
}
}
}

Do It Yourself

1. Write a program that demonstrates how to catch a Throwable and extract its message and stack trace.
2. Create a custom exception class that extends Throwable. Write a program that throws and catches this
custom exception.
3. Develop a program that throws a Throwable with a cause and demonstrates how to access the cause of
the throwable.
4. Write a program that uses printStackTrace() to print a stack trace and explains the information provided.
5. Modify a program to use multiple catch blocks, including one for Throwable, to demonstrate how
different types of exceptions are handled.

Quiz

1. What is the root class for all exceptions and errors in Java?
A) Error
B) Exception
C) Throwable
D) RuntimeException

Answer: C) Throwable

2. Which method of Throwable provides the cause of the exception?


A) getMessage()
B) toString()
C) getCause()
D) printStackTrace()

Answer: C) getCause()

3. What will be the output of the following code?


try {
throw new Throwable("Exception Message");
} catch (Throwable t) {
System.out.println(t.getMessage());
}
A) Exception Message
B) Throwable
C) null
D) No output

Answer: A) Exception Message

4. Which method in the Throwable class prints the stack trace to the standard error stream?
A) getMessage()
B) printStackTrace()
C) getCause()
D) toString()

Answer: B) printStackTrace()

5. How can you create a custom exception that includes a cause?


A) Extend Exception and use Throwable constructor with cause
B) Extend Throwable and use Throwable constructor with cause
C) Use Exception directly
D) Use Error class with a custom method

Answer: B) Extend Throwable and use Throwable constructor with cause

7. Unchecked Exceptions

Unchecked Exceptions
Unchecked exceptions are a critical concept in Java exception handling. They are exceptions that do not need
to be declared in a method's throws clause and are typically used to signal programming errors that should be
fixed in the code.
Introduction to Unchecked Exceptions
Definition
Unchecked exceptions are exceptions that derive from the RuntimeException class. Unlike checked exceptions,
these do not need to be caught or declared thrown in the method signatures. They are used to indicate errors
that are usually caused by bugs in the code or incorrect usage of APIs.
Hierarchy
• java.lang.Object
• java.lang.Throwable
• java.lang.Exception
• java.lang.RuntimeException
• Example subclasses: NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException

Common Unchecked Exceptions


• NullPointerException: Occurs when the application attempts to use null where an object is required.
• ArrayIndexOutOfBoundsException: Thrown when an array is accessed with an illegal index.
• ArithmeticException: Indicates errors in arithmetic operations, such as division by zero.
• IllegalArgumentException: Thrown when a method receives an illegal or inappropriate argument.

Syntax and Examples


Example 1: NullPointerException
public class NullPointerExample {
public static void main(String[] args) {
String str = null;
try {
int length = str.length(); // This line will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
}
}

Explanation: The NullPointerException occurs because str is null, and calling a method on null references
results in this exception.
Example 2: ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
int[] array = new int[5];
try {
int value = array[10]; // This line will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
}

Explanation: Accessing an array with an invalid index (10) throws an ArrayIndexOutOfBoundsException.


Example 3: ArithmeticException
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This line will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
}
}

Explanation: Dividing by zero throws an ArithmeticException.


Example 4: IllegalArgumentException
public class IllegalArgumentExceptionExample {
public static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}

public static void main(String[] args) {


try {
validateAge(-5); // This line will throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Caught IllegalArgumentException: " + e.getMessage());
}
}
}
Explanation: The IllegalArgumentException is used to indicate that a method has been passed an
inappropriate argument.

Practice Programs
Program 1: Handling Multiple Unchecked Exceptions Write a Java program that demonstrates handling
multiple unchecked exceptions (NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException).

public class MultipleUncheckedExceptions {


public static void main(String[] args) {
try {
String str = null;
int length = str.length(); // NullPointerException

int[] array = new int[5];


int value = array[10]; // ArrayIndexOutOfBoundsException

int result = 10 / 0; // ArithmeticException


} catch (NullPointerException | ArrayIndexOutOfBoundsException | ArithmeticException e) {
System.out.println("Caught Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}

Program 2: Custom Unchecked Exception Create a custom unchecked exception that extends
RuntimeException and use it in a program.

public class CustomUncheckedException extends RuntimeException {


public CustomUncheckedException(String message) {
super(message);
}
}

public class CustomUncheckedExample {


public static void checkNumber(int number) {
if (number < 0) {
throw new CustomUncheckedException("Negative number not allowed");
}
}

public static void main(String[] args) {


try {
checkNumber(-10); // This will throw CustomUncheckedException
} catch (CustomUncheckedException e) {
System.out.println("Caught CustomUncheckedException: " + e.getMessage());
}
}
}

Program 3: Using Unchecked Exceptions for Validation Write a program that demonstrates validation of input
using unchecked exceptions.
public class InputValidationExample {
public static void validateInput(int value) {
if (value < 1 || value > 100) {
throw new IllegalArgumentException("Input must be between 1 and 100");
}
}

public static void main(String[] args) {


try {
validateInput(150); // This will throw IllegalArgumentException
} catch (IllegalArgumentException e) {
System.out.println("Caught IllegalArgumentException: " + e.getMessage());
}
}
}

Do It Yourself

1. Write a program that handles NullPointerException and demonstrates how to avoid this exception.
2. Create a program that demonstrates ArrayIndexOutOfBoundsException and discuss how to avoid it.
3. Define a custom unchecked exception and write a program to throw and catch this custom exception.
4. Develop a program that performs division and handles ArithmeticException for division by zero.
5. Write a program that validates method arguments and throws IllegalArgumentException for invalid
inputs.

Quiz

1. Which class is the direct superclass of all unchecked exceptions in Java?


A) Exception
B) RuntimeException
C) Throwable
D) Error

Answer: B) RuntimeException

2. What type of exception is ArrayIndexOutOfBoundsException?


A) Checked Exception
B) Unchecked Exception
C) Error
D) RuntimeException

Answer: B) Unchecked Exception

3. What will be the output of the following code?

public class Example {


public static void main(String[] args) {
try {
int[] arr = new int[2];
arr[3] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getClass().getSimpleName());
}
}
}

A) Exception caught: ArrayIndexOutOfBoundsException


B) Exception caught: IndexOutOfBoundsException
C) No output
D) Exception caught: ArrayIndexOutOfBoundsException, IndexOutOfBoundsException

Answer: A) Exception caught: ArrayIndexOutOfBoundsException

4. How can you avoid a NullPointerException?


A) By checking for null before using an object
B) By catching the exception using a try-catch block
C) By using a custom exception
D) By setting a default value

Answer: A) By checking for null before using an object

5. What will be the output of the following code?


public class Test {
public static void main(String[] args) {
int number = 0;
int result = 1 / number; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception: " + e.getClass().getSimpleName());
}
}

A) Exception: ArithmeticException
B) Exception: Exception
C) No output
D) Exception: RuntimeException

Answer: A) Exception: ArithmeticException

8. Checked Exceptions

Checked Exceptions
Checked exceptions are exceptions that are checked at compile-time. These exceptions require explicit
handling through try-catch blocks or by declaring them using the throws keyword in the method signature.
They are used to handle exceptional conditions that a program should anticipate and recover from.
Introduction to Checked Exceptions
Definition
Checked exceptions are exceptions that are checked by the Java compiler at compile time. Unlike unchecked
exceptions, the compiler ensures that these exceptions are either caught or declared to be thrown. They
typically represent conditions that a program might want to handle, such as I/O errors or invalid data.
Hierarchy
• java.lang.Object
• java.lang.Throwable
• java.lang.Exception
• java.io.IOException
• java.sql.SQLException
• java.lang.ClassNotFoundException
• and more...
Common Checked Exceptions
• IOException: Signals that an I/O operation failed or was interrupted.
• SQLException: Signals that a database access error or other errors related to SQL operations occurred.
• ClassNotFoundException: Indicates that a requested class was not found.

Syntax and Examples


Example 1: Handling IOException
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionExample {


public static void main(String[] args) {
try {
FileReader file = new FileReader("nonexistentfile.txt"); // This line will throw IOException
file.close();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}

Explanation: IOException is thrown when trying to open a file that does not exist. The exception is caught and
handled in the catch block.
Example 2: Handling SQLException
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLExceptionExample {


public static void main(String[] args) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password"); // This line may throw SQLException
conn.close();
} catch (SQLException e) {
System.out.println("Caught SQLException: " + e.getMessage());
}
}
}

Explanation: SQLException is thrown when a database connection fails. The exception is handled in the catch
block.
Example 3: Declaring and Handling ClassNotFoundException
public class ClassNotFoundExceptionExample {
public static void loadClass() throws ClassNotFoundException {
Class.forName("com.example.NonExistentClass"); // This line will throw ClassNotFoundException
}

public static void main(String[] args) {


try {
loadClass();
} catch (ClassNotFoundException e) {
System.out.println("Caught ClassNotFoundException: " + e.getMessage());
}
}
}

Explanation: ClassNotFoundException is thrown when trying to load a class that does not exist. The method
loadClass() declares that it throws this exception, which is handled in the main method.
Example 4: Custom Checked Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomCheckedExceptionExample {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older");
}
}

public static void main(String[] args) {


try {
validateAge(16); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Caught InvalidAgeException: " + e.getMessage());
}
}
}

Explanation: A custom checked exception InvalidAgeException is created and thrown if an invalid age is
provided. This exception is declared to be thrown and handled in the main method.

Practice Programs
Program 1: Handle Multiple Checked Exceptions Write a Java program that handles multiple checked
exceptions (IOException, SQLException) in a single try-catch block.

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MultipleCheckedExceptions {


public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
file.close();

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",


"username", "password");
conn.close();
} catch (IOException | SQLException e) {
System.out.println("Caught Exception: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}

Program 2: Exception Propagation Write a program that demonstrates exception propagation through
methods.

public class ExceptionPropagation {


public static void methodA() throws ClassNotFoundException {
Class.forName("com.example.NonExistentClass"); // This will throw ClassNotFoundException
}

public static void methodB() throws ClassNotFoundException {


methodA(); // Exception is propagated from methodA to methodB
}

public static void main(String[] args) {


try {
methodB();
} catch (ClassNotFoundException e) {
System.out.println("Caught ClassNotFoundException: " + e.getMessage());
}
}
}

Program 3: Creating and Throwing a Custom Exception Write a program that creates and throws a custom
checked exception based on certain conditions.

class AgeNotValidException extends Exception {


public AgeNotValidException(String message) {
super(message);
}
}

public class ValidateAge {


public static void checkAge(int age) throws AgeNotValidException {
if (age < 18) {
throw new AgeNotValidException("Age is not valid for this operation");
}
}

public static void main(String[] args) {


try {
checkAge(15); // This will throw AgeNotValidException
} catch (AgeNotValidException e) {
System.out.println("Caught AgeNotValidException: " + e.getMessage());
}
}
}

Do It Yourself

1. Write a program that reads from a file and handles IOException. Ensure the file is closed properly in case
of an exception.
2. Create a program that connects to a database and handles SQLException for potential connection failures.
3. Define a custom checked exception, throw it from a method, and handle it in the main method.
4. Write a program demonstrating how exceptions propagate through method calls.
5. Write a program that handles multiple checked exceptions (IOException, ClassNotFoundException) in
separate try-catch blocks.

Quiz

1. Which of the following is a checked exception?

A) NullPointerException
B) ArrayIndexOutOfBoundsException
C) IOException
D) ArithmeticException

Answer: C) IOException

2. What must a method do if it declares that it throws a checked exception?


A) Catch the exception
B) Declare it again in the method signature
C) Propagate it to the calling method
D) Handle it with a try-catch block

Answer: C) Propagate it to the calling method

3. What is the output of the following code if the file does not exist?

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

public class Test {


public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
file.close();
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
A) No output
B) Exception: file.txt (The system cannot find the file specified)
C) Exception: IOException
D) Exception: FileNotFoundException

Answer: B) Exception: file.txt (The system cannot find the file specified)

4. Which keyword is used to declare that a method can throw a checked exception?
A) throws
B) throws
C) throw
D) catch

Answer: A) throws

5. What is the purpose of declaring a checked exception in a method signature?


A) To handle the exception within the method
B) To inform the compiler that the method may throw this exception
C) To automatically handle the exception
D) To log the exception

Answer: B) To inform the compiler that the method may throw this exception

Java I/O API


The Java I/O (Input/Output) API provides a set of classes and interfaces for reading and writing data to files,
handling input from users, and performing various data manipulation tasks. The I/O API is fundamental for
handling data in Java applications.

Introduction to Java I/O API


Definition
The Java I/O API is a set of classes and interfaces that allow Java programs to perform input and output
operations. It includes classes for reading from and writing to files, handling input from the console, and
working with streams.
Key Packages
• java.io: Contains classes for input and output operations, including file handling and stream manipulation.
• java.nio: Provides the New I/O (NIO) package, which includes advanced I/O capabilities such as buffers
and channels.
• java.nio.file: Contains the NIO.2 file I/O API for more flexible file operations.

Core Classes and Interfaces


1. File Handling
File Class
The File class represents a file or directory path in the filesystem.

Syntax:

import java.io.File;

public class FileExample {


public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}

Explanation: Creates a File object and checks if the file exists.


FileReader and FileWriter
• FileReader: Used for reading character files.
• FileWriter: Used for writing character files.

Syntax:

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

public class FileReaderWriterExample {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, World!");
writer.close();

FileReader reader = new FileReader("example.txt");


int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Writes "Hello, World!" to a file and then reads it.


2.Input/Output Streams
InputStream and OutputStream
• InputStream: Abstract class for reading byte streams.
• OutputStream: Abstract class for writing byte streams.

Syntax:

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

public class ByteStreamExample {


public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("bytefile.txt");
fos.write(65); // Writes the byte value 65 (which is 'A')
fos.close();

FileInputStream fis = new FileInputStream("bytefile.txt");


int b = fis.read();
System.out.println("Read byte: " + b);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Demonstrates writing and reading bytes using FileOutputStream and FileInputStream.
BufferedReader and BufferedWriter
• BufferedReader: Reads text from a character-based input stream efficiently.
• BufferedWriter: Writes text to a character-based output stream efficiently.

Syntax:

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

public class BufferedReaderWriterExample {


public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("bufferedfile.txt"));
writer.write("Hello Buffered World!");
writer.close();

BufferedReader reader = new BufferedReader(new FileReader("bufferedfile.txt"));


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Uses BufferedWriter to write and BufferedReader to read text efficiently.


3. Serialization
Serializable Interface
The Serializable interface is used to serialize objects into a byte stream.

Syntax:

import java.io.*;

class Person implements Serializable {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}

public class SerializationExample {


public static void main(String[] args) {
try {
Person person = new Person("John Doe", 30);

// Serialize
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();

// Deserialize
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();

System.out.println("Deserialized Person: " + deserializedPerson);


} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Explanation: Demonstrates serializing and deserializing an object.

Practice Programs
Program 1: File Copy Program

Write a program that copies content from one file to another.

import java.io.*;

public class FileCopyExample {


public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("destination.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program 2: Read File Line by Line

Write a program to read a file line by line and print each line.

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

public class LineByLineReader {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program 3: Object Serialization

Create a class with multiple fields, serialize an object of that class, and then deserialize it to verify that the
object’s data is correctly preserved.

import java.io.*;

class Student implements Serializable {


private String name;
private int rollNumber;

public Student(String name, int rollNumber) {


this.name = name;
this.rollNumber = rollNumber;
}

@Override
public String toString() {
return "Student{name='" + name + "', rollNumber=" + rollNumber + "}";
}
}

public class StudentSerialization {


public static void main(String[] args) {
try {
Student student = new Student("Alice", 12345);

// Serialize
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student);
oos.close();

// Deserialize
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student deserializedStudent = (Student) ois.readObject();
ois.close();

System.out.println("Deserialized Student: " + deserializedStudent);


} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Do It Yourself

1. Write a program that reads integers from a file, calculates their sum, and writes the result to another file.
2. Create a program that lists all files and directories in a specified directory.
3. Write a class with multiple fields, serialize an object of that class, and then deserialize it to verify that the
object’s data is correctly preserved.
4. Write a program that uses BufferedReader and BufferedWriter to copy text from one file to another.
5. Write a program that handles IOException and FileNotFoundException while performing file operations.
Quiz

1. Which class is used to create a new file or access an existing file in Java I/O?

• A) FileReader
• B) FileWriter
• C) File
• D) BufferedReader

Answer: C) File

2. What does the read() method of FileInputStream return?

• A) The file content as a string


• B) The number of bytes read
• C) The next byte of data or -1 if the end of the stream is reached
• D) An array of bytes

Answer: C) The next byte of data or -1 if the end of the stream is reached

3. Which of the following exceptions is thrown when a file does not exist?

• A) FileNotFoundException
• B) IOException
• C) EOFException
• D) ClassNotFoundException

Answer: A) FileNotFoundException

4. Which interface must be implemented for a class to be serializable?

• A) Serializable
• B) Externalizable
• C) Readable
• D) Writable

Answer: A) Serializable

5. What is the purpose of BufferedReader in Java I/O?

• A) To read bytes of data


• B) To read text data efficiently from a character-based input stream
• C) To write text data efficiently to a character-based output stream
• D) To serialize objects

Answer: B) To read text data efficiently from a character-based input stream

2. Standard I/O streams

Standard I/O Streams


Java provides a set of standard I/O (Input/Output) streams for interacting with the console and files. These
streams handle basic input and output operations, such as reading user input from the console or writing
output to the console.

Introduction to Standard I/O Streams


Java’s standard I/O streams are part of the java.io package and include three primary streams:
• System.in: Input stream for reading data from the console.
• System.out: Output stream for writing data to the console.
• System.err: Error output stream for writing error messages to the console.

These streams are available by default and are commonly used for basic input and output operations in Java.

Standard I/O Streams Overview


1. System.in
• System.in: An instance of InputStream used to read input from the console.

Syntax:

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class SystemInExample {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name:");
try {
String name = reader.readLine();
System.out.println("Hello, " + name + "!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Reads input from the console and displays a greeting.


2. System.out
• System.out: An instance of PrintStream used to write output to the console.

Syntax:
public class SystemOutExample {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.print("Welcome ");
System.out.print("to Java I/O.");
}
}

Explanation: Demonstrates various ways to print messages to the console.


3. System.err
• System.err: An instance of PrintStream used to write error messages to the console.

Syntax:

public class SystemErrExample {


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

Explanation: Prints an error message to the console.

Practice Programs
Program 1: Read and Echo User Input

Write a program that reads a line of text from the console and echoes it back to the user.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class EchoInput {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a line of text:");
try {
String input = reader.readLine();
System.out.println("You entered: " + input);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program 2: Simple Calculator

Create a program that reads two integers from the console and prints their sum.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class SimpleCalculator {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first number:");
try {
int num1 = Integer.parseInt(reader.readLine());
System.out.println("Enter second number:");
int num2 = Integer.parseInt(reader.readLine());
System.out.println("Sum: " + (num1 + num2));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program 3: Error Handling Example

Write a program that demonstrates the use of System.err by printing an error message if a division by zero is
attempted.

public class ErrorHandlingExample {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator;
} catch (ArithmeticException e) {
System.err.println("Error: Division by zero is not allowed.");
}
}
}

Do It Yourself

1. Write a program that reads a user's age and prints a message indicating whether the user is eligible to
vote (18 or older).
2. Write a program that reads two floating-point numbers from the console and prints their sum formatted
to two decimal places.
3. Modify the "Simple Calculator" program to handle potential input errors (e.g., non-numeric input) and
display appropriate error messages using System.err.
4. Write a program that reads three strings from the console and concatenates them into a single string,
which is then printed.
5. Write a program that logs messages to both the standard output and the error output streams to simulate
logging of normal operations and error events.

Quiz

1. What is the type of System.out in Java?


A) PrintStream
B) InputStream
C) PrintWriter
D) BufferedReader

Answer: A) PrintStream
2. Which class is used to read data from the console in Java?
A) PrintStream
B) FileReader
C) BufferedReader
D) FileWriter

Answer: C) BufferedReader

3. Which method is used to print a message followed by a newline in Java?


A) System.out.print()
B) System.out.println()
C) System.out.write()
D) System.out.flush()

Answer: B) System.out.println()

4. What does System.err typically used for?


A) Reading input
B) Writing error messages
C) Writing regular output
D) Formatting output

Answer: B) Writing error messages

5. Which of the following methods reads a line of text from the console?
A) read()
B) readLine()
C) next()
D) nextLine()

Answer: B) readLine()

3. Streams Types

Streams Based on Data


In Java, streams provide a powerful mechanism for handling input and output operations. Streams can be
categorized into two types based on the kind of data they handle:

Byte Streams: Handle byte data.


1. Character Streams: Handle character data.

This guide covers both types of streams, their classes, and provides examples and practice exercises to help
engineering students understand and use them effectively.
1. Byte Streams
Byte streams are used for handling raw binary data. They are suitable for reading and writing data such as
image files, audio files, and other binary files.
1.1 Byte Input Streams
Description: Byte input streams read byte data from various input sources.

Superclass: InputStream (abstract class)

Common Byte Input Streams:


• FileInputStream
• ByteArrayInputStream
• ObjectInputStream
Example 1: Reading Data from a File

import java.io.*;

class ReadHello {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("hello.txt");
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation: This code opens a file named hello.txt and reads its content byte by byte. It converts each byte
into a character and prints it until the end of the file.

Example 2: Reading Data Using BufferedInputStream

import java.io.*;

public class BufferedReadExample {


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

Explanation: Uses BufferedInputStream to improve efficiency by buffering the input data.

1.2 Byte Output Streams


Description: Byte output streams write byte data to various output destinations.

Superclass: OutputStream (abstract class)

Common Byte Output Streams:

• FileOutputStream
• ByteArrayOutputStream
• ObjectOutputStream

Example 1: Writing Data to a File

import java.io.*;

public class WriteExample {


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

Explanation: This code writes the string "Hello, World!" to a file named output.txt.

Example 2: Writing Data Using PrintStream

import java.io.*;

public class PrintStreamExample {


public static void main(String[] args) {
try {
PrintStream ps = new PrintStream(new File("printStreamExample.txt"));
ps.println("Hello, this is PrintStream!");
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Uses PrintStream to write formatted text to a file.

2. Character Streams
Character streams are designed for handling data as characters. They are more convenient for reading and
writing textual data.
2.1 Character Input Streams
Description: Character input streams read character data from various input sources.

Superclass: Reader (abstract class)

Common Character Input Streams:


FileReader

BufferedReader

CharArrayReader
Example 1: Reading Characters from a File

import java.io.*;

public class CharacterReadExample {


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

Explanation: Reads and prints characters from example.txt using FileReader.

Example 2: Reading Lines Using BufferedReader

import java.io.*;

public class BufferedReaderExample {


public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Uses BufferedReader to read text line by line.

2.2 Character Output Streams


Description: Character output streams write character data to various output destinations.

Superclass: Writer (abstract class)

Common Character Output Streams:


FileWriter

BufferedWriter

PrintWriter
Example 1: Writing Characters to a File

import java.io.*;

public class CharacterWriteExample {


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

Explanation: Writes "Hello, World!" to a file using FileWriter.

Example 2: Writing Formatted Text Using PrintWriter

import java.io.*;

public class PrintWriterExample {


public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter(new FileWriter("printWriterExample.txt"));
pw.println("Hello, this is PrintWriter!");
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation: Uses PrintWriter to write formatted text to a file.

Do It Yourself

1. Write a program that reads a binary file and prints its contents as characters. Explain the output.
2. Create a program that reads a list of names from the console and writes them to a file using FileWriter.
Verify the content of the file.
3. Write a program that reads data from a file using BufferedInputStream and writes data to another file
using BufferedOutputStream.
4. Write a program that writes a string with different character encodings (e.g., UTF-8, UTF-16) to a file and
reads it back.
5. Use PrintStream to format and write different types of data (integers, doubles, strings) to a file. Read the
file and print its contents.

Quiz

1. Which class is the superclass of all byte input streams?


A) Reader
B) OutputStream
C) InputStream
D) Writer

Answer: C) InputStream

2. What is the default buffer size for BufferedReader in Java?


A) 8 KB
B) 4 KB
C) 16 KB
D) 32 KB

Answer: B) 8 KB

3. Which method of PrintWriter is used to write a string to a file?


A) write()
B) print()
C) println()
D) append()

Answer: C) println()

4. Which class is used for reading and writing character data in Java?
A) ByteArrayOutputStream
B) FileReader
C) ObjectInputStream
D) DataOutputStream

Answer: B) FileReader

5. Which of the following is a character output stream?


A) FileOutputStream
B) ByteArrayOutputStream
C) PrintWriter
D) ObjectOutputStream

Answer: C) PrintWriter

4. Scanner class

Scanner Class in Java


The Scanner class in Java is a versatile tool used for reading input from various sources such as the keyboard,
files, or strings. It belongs to the java.util package and provides a way to parse primitive types and strings using
regular expressions.
1. Overview of the Scanner Class
Description: The Scanner class is used for parsing input data from different sources. It provides methods to
read data of various types, such as integers, floating-point numbers, and strings.

Package: java.util

Common Use Cases:


• Reading input from the keyboard.
• Parsing data from files.
• Tokenizing strings.

2. Syntax
Basic Syntax:

import java.util.Scanner;

Scanner scanner = new Scanner(source);

• source: Can be System.in for keyboard input, File object for file input, or String for string input.

Common Methods:
• next(): Returns the next token as a string.
• nextInt(): Parses and returns the next token as an integer.
• nextDouble(): Parses and returns the next token as a double.
• nextLine(): Returns the rest of the current line as a string.
• hasNext(): Checks if there is another token.
• hasNextInt(): Checks if the next token is an integer.

3. Examples
3.1 Reading Input from the Keyboard
Example: Reading a string and an integer from the keyboard.
import java.util.Scanner;

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.println("Name: " + name);


System.out.println("Age: " + age);

scanner.close();
}
}

Explanation: This program prompts the user to enter their name and age. It then reads the input and prints it
to the console.

3.2 Reading from a File


Example: Reading lines from a file using Scanner.

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

public class FileScannerExample {


public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}

scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}

Explanation: This program reads and prints each line from a file named example.txt.
3.3 Parsing Data
Example: Parsing different types of data from a string.
import java.util.Scanner;

public class ParsingExample {


public static void main(String[] args) {
String data = "42 3.14 Hello";
Scanner scanner = new Scanner(data);

int number = scanner.nextInt();


double decimal = scanner.nextDouble();
String text = scanner.next();

System.out.println("Integer: " + number);


System.out.println("Double: " + decimal);
System.out.println("String: " + text);

scanner.close();
}
}

Explanation: This program demonstrates parsing an integer, a double, and a string from a single input string.

Do It Yourself

1. Write a Java program that reads the following from the console using Scanner: a string, an integer, and a
double. Print each value on a new line.
2. Create a text file with some sample data. Write a program that uses Scanner to read the file and print the
contents to the console.
3. Write a Java program that takes a single line of input containing a date in the format YYYY-MM-DD and
prints each component (year, month, day) separately.
4. Modify the program from Question 1 to handle the InputMismatchException if the user enters incorrect
data types.
5. Write a Java program that reads a line of text from the console and counts the number of words in the
line.

Quiz

1. Which method of the Scanner class is used to read a line of text?


A) next()
B) nextLine()
C) read()
D) getLine()

Answer: B) nextLine()

2. What exception is thrown if the Scanner attempts to read data of the wrong type?
A) IOException
B) FileNotFoundException
C) InputMismatchException
D) NumberFormatException
Answer: C) InputMismatchException

3. Which method would you use to read a double value from the input?
A) readDouble()
B) nextDouble()
C) getDouble()
D) parseDouble()

Answer: B) nextDouble()

How do you read integers from a string using Scanner?


A) scanner.nextInt()
B) scanner.readInt()
C) scanner.parseInt()
D) scanner.getInt()

Answer: A) scanner.nextInt()

5. Which class must be imported to use Scanner?

A) java.util.Scanner
B) java.io.Scanner
C) java.util.Input
D) java.io.Input

Answer: A) java.util.Scanner

5. Files in Java

Files in Java
The java.io package in Java provides a robust set of classes for file manipulation and handling. Working with
files involves creating, reading, writing, and deleting files. Java also includes the java.nio.file package which
provides additional functionalities for file operations.

1. Overview of File Handling in Java


Description: File handling in Java involves using classes from the java.io and java.nio.file packages to perform
operations on files. This includes creating files, writing data to files, reading data from files, and deleting files.

Common Classes:

• File
• FileInputStream
• FileOutputStream
• BufferedReader
• BufferedWriter
• PrintWriter
• Files (from java.nio.file package)
• Paths (from java.nio.file package)

2. Basic File Operations


2.1 Creating a File
Syntax:

import java.io.File;
import java.io.IOException;

public class CreateFileExample {


public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Explanation: This code creates a new file named example.txt in the project directory. If the file already exists,
it notifies the user.
2.2 Writing to a File
Syntax:

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

public class WriteToFileExample {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, world!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Explanation: This code writes the text "Hello, world!" to example.txt.


2.3 Reading from a File
Syntax:

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadFromFileExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Explanation: This code reads each line from example.txt and prints it to the console.

2.4 Deleting a File

Syntax:

import java.io.File;

public class DeleteFileExample {


public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

Explanation: This code deletes example.txt from the file system.

3. Using java.nio.file for File Operations


3.1 Creating and Writing to a File
Syntax:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class NIOWriteExample {


public static void main(String[] args) {
String content = "Hello, NIO!";
try {
Files.write(Paths.get("example_nio.txt"), content.getBytes());
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Explanation: This code uses Files.write to create and write to a file example_nio.txt.
3.2 Reading from a File
Syntax:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class NIOReadExample {


public static void main(String[] args) {
try {
List<String> lines = Files.readAllLines(Paths.get("example_nio.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation: This code reads all lines from example_nio.txt and prints them.
3.3 Deleting a File
Syntax:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class NIODeleteExample {


public static void main(String[] args) {
try {
Files.delete(Paths.get("example_nio.txt"));
System.out.println("Deleted the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation: This code deletes example_nio.txt using the Files.delete method.

Do It Yourself

1. Write a program that creates a file, writes several lines of text to it, reads the file, and prints its content.
2. Write a Java program that copies the contents of a source file to a destination file.
3. Create a program that reads a file and outputs the number of lines, words, and characters in the file.
4. Write a program that attempts to delete a file and handles the case where the file does not exist.
5. File Append: Develop a program that appends new content to an existing file without overwriting the
existing content.

Quiz

1. Which class in Java is used to create, delete, and perform other file operations?
A) File
B) FileInputStream
C) FileOutputStream
D) BufferedReader

Answer: A) File
2. Which method in the Files class is used to write data to a file?
A) write()
B) create()
C) writeAllLines()
D) append()

Answer: C) writeAllLines()

3. Which method is used to read the contents of a file into a list of strings using Files?
A) read()
B) readLines()
C) readAllLines()
D) getLines()

Answer: C) readAllLines()

4. Which class is used for buffered file output?

A) FileOutputStream
B) FileWriter
C) BufferedWriter
D) PrintWriter

Answer: C) BufferedWriter

5. Which method of the File class is used to delete a file?


A) remove()
B) delete()
C) erase()
D) removeFile()

Answer: B) delete()

You might also like