Unit 4 Materials
Unit 4 Materials
Syllabus
Java I/O and File: Java I/O API, standard I/O streams, types, Byte
streams, Character streams, Scanner class, Files in Java
Unit 4
Packages in Java:
A package in Java is a mechanism for organizing classes, interfaces, and sub-packages
into namespaces, similar to folders in a file system. Packages help to prevent naming
conflicts, provide access control, and make it easier to manage large software projects by
grouping related classes together.
Types of Packages:
1. Built-in Packages: Provided by Java, such as java.util , java.io , java.lang , etc.
2. User-defined Packages: Created by users to group their own classes.
1. Built-in Packages – These are standard libraries provided by Java, like java.lang ,
java.util , java.io , etc.
2. User-defined Packages – These are created by the user to group related classes and
interfaces.
Java.lang Package
The java.lang package is one of Java's core packages. It contains fundamental classes
that are essential to the Java programming language.
Key Features:
Below are some commonly used methods in the Math class, grouped by functionality:
2. Rounding Functions
3. Trigonometric Functions
Math.random() : Returns a random double value between 0.0 (inclusive) and 1.0
(exclusive). You can scale this to get random numbers within a specific range.
7. Constants
Math.PI : The value of π (approximately 3.14159).
Math.E : The base of the natural logarithm, Euler’s number (approximately 2.71828).
Example Usage:
Here's a program demonstrating some common methods from the Math package:
In this code:
import java.util.Random;
Example Program
Here's a sample program that demonstrates generating different types of random values
using the Random class:
import java.util.Random;
Sample Output
Notes
Using Boundaries: With nextInt(bound) , you can specify the upper limit to control
the range.
Non-zero Floats and Doubles: Since nextFloat() and nextDouble() only generate
values between 0.0 and 1.0 , you can scale them by multiplying by a constant to get a
larger range.
The Random class is ideal when you need more control over random number generation,
especially for generating different types of random values like int , float , or boolean .
1. Wrapper Classes
Definition:
Wrapper classes in Java are used to convert primitive data types (like int , char , double )
into objects. Each primitive type has a corresponding wrapper class in the java.lang
package.
Example:
import java.util.ArrayList;
Explanation:
Autoboxing occurs when adding primitive int values to an ArrayList of Integer .
Java automatically converts each int to Integer .
Auto-unboxing occurs when retrieving elements from the list, converting Integer
values back to int for calculations.
Types of Exceptions
1. Checked Exceptions: Exceptions that are checked at compile-time (e.g.,
IOException , SQLException ).
2. Unchecked Exceptions: Exceptions that occur at runtime, which the compiler doesn’t
require you to handle (e.g., ArithmeticException , NullPointerException ).
try
{
// Code that might throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
finally
{
// Code that will run regardless of whether an exception was thrown or
not
}
catch (Exception e)
{
System.out.println("Cannot divide by zero!");
System.out.println(e);
}
finally
{
System.out.println("Execution complete.");
}
}
}
Output:
try
{
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds!");
}
catch (ArithmeticException e)
{
System.out.println("Cannot divide by zero!");
}
Nested try-catch
Java allows nested try-catch blocks, where an inner try-catch handles an exception
separate from the outer block.
try
{
try
{
int num = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch: " + e.getMessage());
}
int arr[] = new int[2];
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Outer catch: Array index out of bounds!");
}
finally Block
The finally block always executes, even if an exception is not thrown. It’s commonly used
for resource cleanup, like closing files or database connections.
try {
int data = 10 / 2;
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("Finally block executed.");
}
throws: Declares the exceptions a method might throw, used in the method signature.
public void readFile() throws IOException {
FileReader file = new FileReader("file.txt");
}
Summary
Exception handling ensures a program can deal with errors smoothly, maintaining stability
and reliability. With the try , catch , finally , throw , and throws constructs, Java
provides a structured way to handle runtime errors, making code robust and easier to debug.
The Java I/O API is located in the java.io package and contains classes to handle various
types of I/O.
1. System.in – Standard input stream (by default, reads input from the keyboard).
2. System.out – Standard output stream (by default, outputs data to the console).
3. System.err – Standard error stream (by default, outputs error data to the console).
import java.io.*;
public class StandardIOExample {
public static void main(String[] args) {
System.out.println("This is a standard output message.");
System.err.println("This is a standard error message.");
}
}
Types of Streams
Java provides two types of streams to handle different types of data:
A. Byte Streams
Definition: Byte streams handle binary data and are used for handling input and output
of raw bytes (e.g., image, video files).
Classes:
InputStream – Abstract class for reading byte data.
OutputStream – Abstract class for writing byte data.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
B. Character Streams
Definition: Character streams handle character data and are used for handling text
files (e.g., reading/writing strings).
Classes:
Reader – Abstract class for reading character data.
Writer – Abstract class for writing character data.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
scanner.close();
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Files in Java
The File class in java.io package represents a file or directory path in Java. It provides
methods to create, delete, and manipulate files and directories.
import java.io.File;
import java.io.IOException;