0% found this document useful (0 votes)
11 views10 pages

Unit 4

Hi
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)
11 views10 pages

Unit 4

Hi
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/ 10

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.

Math Package in Java


The java.lang.Math package in Java provides a variety of mathematical operations and
constants. . It has methods to perform common mathematical functions such as power,
square root, trigonometric functions, rounding, and random number generation.

Below are some commonly used methods in the Math class, grouped by functionality:

1. Basic Mathematical Functions


Math.abs(int a) , Math.abs(double a) : Returns the absolute value of the argument.
Math.max(int a, int b) , Math.min(int a, int b) : Returns the maximum or
minimum of two values.
Math.pow(double a, double b) : Returns the value of a raised to the power of b .

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.

4. Exponential and Logarithmic Functions


Math.exp(double a) : Returns Euler's number e raised to the power of a .
Math.log(double a) : Returns the natural logarithm (base e ) of a .
Math.log10(double a) : Returns the base-10 logarithm of a .

5. Random Number Generation


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.

6. Square Root and Cube Root


Math.sqrt(double a) : Returns the square root of a .
Math.cbrt(double a) : Returns the cube root of a .

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:

public class MathExample


{
public static void main(String[] args)
{
double number = -25.5;

System.out.println("Absolute Value: " + Math.abs(number));


System.out.println("Square Root: " + Math.sqrt(25));
System.out.println("Power: " + Math.pow(5, 2));
System.out.println("Maximum of 10 and 20: " + Math.max(10, 20));
System.out.println("Rounding up (ceil): " + Math.ceil(5.2));
System.out.println("Rounding down (floor): " + Math.floor(5.8));
System.out.println("Random Number: " + Math.random());
System.out.println("PI constant: " + Math.PI);
}
}
In this code:

Math.abs(number) returns the absolute value of number .


Math.sqrt(25) returns the square root of 25.
Math.pow(5, 2) computes 5 raised to the power of 2.
Math.random() generates a random number between 0.0 and 1.

Random Class in Java


The Random class in Java (located in the java.util package) is used to generate random
numbers of different types, including integers, floats, and more. Unlike Math.random() ,
which generates only double values between 0.0 and 1.0, Random provides greater flexibility
with methods for generating various types of random values.

Importing the Random Class

import java.util.Random;

Creating an Instance of Random

Random random = new Random();

Commonly Used Methods in the Random Class


1. Generating Integer Values
nextInt() : Returns a random integer (positive, negative, or zero).
nextInt(int bound) : Returns a random integer between 0 (inclusive) and the
specified bound (exclusive).

int randomInt = random.nextInt(); // Any random int value


int boundedInt = random.nextInt(50); // Random int between 0 and
49

2. Generating Float Values


nextFloat() : Returns a random float between 0.0 (inclusive) and 1.0
(exclusive).
float randomFloat = random.nextFloat(); // Random float between 0.0
and 1.0

3. Generating Double Values


nextDouble() : Returns a random double between 0.0 (inclusive) and 1.0
(exclusive).

double randomDouble = random.nextDouble(); // Random double between 0.0


and 1.0

4. Generating Long Values


nextLong() : Returns a random long value.

long randomLong = random.nextLong(); // Any random long value

5. Generating Boolean Values


nextBoolean() : Returns a random boolean value ( true or false ).

boolean randomBoolean = random.nextBoolean(); // Random boolean (true


or false)

Example Program
Here's a sample program that demonstrates generating different types of random values
using the Random class:

import java.util.Random;

public class RandomExample


{
public static void main(String[] args)
{
Random random = new Random();

int randomInt = random.nextInt(); // Random integer


int boundedInt = random.nextInt(100); // Random integer
between 0 and 99
float randomFloat = random.nextFloat(); // Random float
between 0.0 and 1.0
double randomDouble = random.nextDouble(); // Random double
between 0.0 and 1.0
boolean randomBoolean = random.nextBoolean(); // Random boolean
(true or false)
System.out.println("Random Integer: " + randomInt);
System.out.println("Random Integer (0-99): " + boundedInt);
System.out.println("Random Float (0.0-1.0): " + randomFloat);
System.out.println("Random Double (0.0-1.0): " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
}

Sample Output

Random Integer: 123456789


Random Integer (0-99): 57
Random Float (0.0-1.0): 0.3249
Random Double (0.0-1.0): 0.8726
Random Boolean: true

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 .

Exception Handling in Java


Exception Handling in Java is a mechanism that allows a program to deal with unexpected
situations (exceptions) during execution, ensuring the program can either recover gracefully
or provide meaningful error information instead of crashing abruptly.

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:

1. try: Used to wrap code that might throw an exception.


2. catch: Used to handle the exception type specified by the programmer.
3. finally: A block that always executes after try and catch , regardless of whether an
exception occurred. Often used for resource cleanup.
4. throw: Used to explicitly throw an exception.
5. throws: Used in method signatures to indicate the method may throw certain
exceptions.

Basic Structure of Exception Handling

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
}

Example of Exception Handling


The following example demonstrates basic exception handling where a program attempts to
divide a number by zero:

public class ExceptionExample


{
public static void main(String[] args)
{
try
{
int result = 10 / 0; // This will throw an ArithmeticException
}

catch (Exception e)
{
System.out.println("Cannot divide by zero!");
System.out.println(e);
}
finally
{
System.out.println("Execution complete.");
}
}
}

Output:

Cannot divide by zero!


Execution complete.

Multiple Catch Blocks


You can have multiple catch blocks to handle different types of exceptions separately.

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.");
}

throw and throws


throw: Used to explicitly throw an exception.

public class Test


{
public void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Not eligible for voting");
}
}
}

throws: Declares the exceptions a method might throw, used in the method signature.

public void readFile() throws IOException {


FileReader file = new FileReader("file.txt");
}

Exception Handling Best Practices


1. Catch the most specific exception first.
2. Avoid using Exception as a catch-all, which can mask errors.
3. Use finally to release resources.
4. Use custom exception classes for specific business logic errors.
5. Avoid empty catch blocks, as they can hide critical issues.

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.

File Handling in Java


File Handling in Java is a crucial concept that allows programs to create, read, update, and
delete files on the file system. Java provides several classes and methods to perform file
operations, making it easy to manage data storage and retrieval in text or binary files.

Why File Handling?


File handling is essential when you want to:

Save data persistently (e.g., user information, application logs, or configurations).


Read and process data from external files.
Share data between different programs.

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

public class SimpleFileRead


{
public static void main(String[] args)
{
try
{
FileReader reader = new FileReader("Mine.txt"); // Open
Mine.txt
int character;

// Read and display each character until end of file


while ((character = reader.read()) != -1)
{
System.out.print((char) character);
}

reader.close(); // Close the file


}
catch (IOException e)
{
System.out.println("Error reading file: " + e.getMessage());
}
}
}

You might also like