Unit 4
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.
Below are some commonly used methods in the Math class, grouped by functionality:
2. Rounding Functions
Math.round(float a) , Math.round(double a) : Rounds the argument to the nearest
integer (returns an int or long ).
Math.ceil(double a) : Returns the smallest integer that is greater than or equal to a
(rounds up).
Math.floor(double a) : Returns the largest integer that is less than or equal to a
(rounds down).
3. Trigonometric Functions
Math.sin(double a) , Math.cos(double a) , Math.tan(double a) : Returns the
trigonometric sine, cosine, and tangent of an angle (in radians).
Math.toRadians(double degrees) : Converts degrees to radians.
Math.toDegrees(double radians) : Converts radians to degrees.
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:
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 .
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 ).
Exception Handling Keywords
Java provides four keywords to handle exceptions:
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.
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.
import java.io.FileReader;
import java.io.IOException;