[go: up one dir, main page]

0% found this document useful (0 votes)
7 views19 pages

Unit 4 Materials

Interface and Arrays in java.

Uploaded by

sunhithsirigudi
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)
7 views19 pages

Unit 4 Materials

Interface and Arrays in java.

Uploaded by

sunhithsirigudi
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/ 19

Unit – 4

Syllabus

Packages and Java Library: Introduc on, Defining Package, Impor ng


Packages and Classes into Programs, Path and Class Path, Access
Control, Packages in Java SE, Java.lang Package and its Classes, Class
Object, Enumera on, class Math, Wrapper Classes, Autoboxing and
Auto-unboxing, Java u l Classes and Interfaces, Forma er Class,
Random Class, Time Package, Class Instant (java. me.Instant),
Forma ng for Date/Time in Java, Temporal Adjusters Class, Temporal
Adjusters Class.

Excep on Handling: Introduc on, Hierarchy of Standard Excep on


Classes, Keywords throws and throw, try, catch, and finally Blocks,
Mul ple Catch Clauses, Class Throwable, Unchecked Excep ons,
Checked Excep ons.

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.

Introduction to Packages in Java SE


Definition:
A package in Java is a collection of related classes and interfaces. It organizes the Java
classes and helps avoid name conflicts, especially when using large-scale applications.

Types of Packages in Java:

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:

The java.lang package is automatically imported in all Java programs.


It contains classes for basic language features, like primitive type wrappers, math
functions, and string manipulation.

Important Classes in java.lang :


Object
String
System
Math
Wrapper Classes (e.g., Integer, Double)

Class Object in java.lang Package


Definition:
The Object class is the root of the Java class hierarchy. Every class in Java inherits directly
or indirectly from the Object class, making it the superclass of all classes.

Key Methods of the Object Class:

1. equals(Object obj) - Compares two objects for equality.


2. toString() - Returns a string representation of the object.
3. hashCode() - Returns an integer hash code for the object.
4. getClass() - Returns the runtime class of the object.
5. clone() - Creates and returns a copy of the object (requires Cloneable interface).
6. finalize() - Called by the garbage collector when an object is no longer in use.

Java.lang Package Classes and Their Uses


String Class:

Used to handle sequences of characters.


Immutable, meaning once created, the contents cannot be changed.

Example of String class:

public class StringExample {


public static void main(String[] args) {
String str = "Hello, Java!";
System.out.println("Length of string: " + str.length());
System.out.println("Character at index 1: " + str.charAt(1));
System.out.println("Substring (7 to end): " + str.substring(7));
}
}

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 .

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.

Why Wrapper Classes?

Object-Oriented Approach: Java is an object-oriented language, and sometimes


objects are required where only primitive types exist (e.g., in collections like
ArrayList ).
Utilities: Wrapper classes provide methods to perform operations on primitive values,
such as converting them to strings, parsing strings to numbers, and more.

Wrapper Classes for Primitive Data Types:

Primitive Type Wrapper Class


int Integer
byte Byte
short Short
long Long
float Float
double Double
char Character
boolean Boolean

Example:

public class WrapperExample


{
public static void main(String[] args)
{
int num = 5; // Primitive data type
Integer numObj = Integer.valueOf(num); // Boxing - converting
primitive to Integer object
System.out.println("Integer object: " + numObj);
int unboxedNum = numObj.intValue(); // Unboxing - converting
Integer object to primitive
System.out.println("Primitive int: " + unboxedNum);
}
}

2. Autoboxing and Auto-unboxing


Definition:
Autoboxing and auto-unboxing are features in Java that allow automatic conversion between
primitive types and their corresponding wrapper classes. This feature simplifies the coding
process by handling the conversions implicitly.

Autoboxing: Automatic conversion of a primitive type to its corresponding wrapper


class object.
Auto-unboxing: Automatic conversion of a wrapper class object back to its
corresponding primitive type.

Benefits of Autoboxing and Auto-unboxing:

Simplifies the code by removing the need for explicit conversions.


Reduces errors and makes code easier to read.

Examples of Autoboxing and Auto-unboxing:

public class AutoboxingExample


{
public static void main(String[] args)
{
// Autoboxing: Converting int to Integer
int num = 10;
Integer numObj = num; // Automatically converts int to Integer
System.out.println("Autoboxed Integer: " + numObj);

// Auto-unboxing: Converting Integer to int


Integer integerObj = 20;
int primitiveInt = integerObj; // Automatically converts Integer to
int
System.out.println("Auto-unboxed int: " + primitiveInt);
}
}
3. Practical Use of Autoboxing and Auto-unboxing
Autoboxing and auto-unboxing are especially useful when working with Java collections, as
collections can only store objects, not primitive types.

Example: Using Autoboxing with Collections:

import java.util.ArrayList;

public class CollectionExample


{
public static void main(String[] args)
{
// ArrayList of Integer (Wrapper class) to store int values
ArrayList<Integer> numbers = new ArrayList<>();

// Autoboxing: Adding primitive int values to ArrayList


numbers.add(5); // Converts int 5 to Integer 5
numbers.add(10); // Converts int 10 to Integer 10
numbers.add(15); // Converts int 15 to Integer 15

// Auto-unboxing: Retrieving Integer values as int


int sum = 0;
for (Integer number : numbers)
{
sum += number; // Auto-unboxes Integer to int for addition
}

System.out.println("Sum of numbers: " + sum);


}
}

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.

Exception Handling in Java (Very Important)


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.

Java I/O API


Definition:
Java's I/O (Input/Output) API allows programs to perform input and output operations like
reading from and writing to data sources (files, consoles, network sockets, etc.).

The Java I/O API is located in the java.io package and contains classes to handle various
types of I/O.

Standard I/O Streams


Java has three standard I/O streams that are created automatically for every Java
application:

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).

Example of Standard I/O Streams:

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.

Common Byte Stream Classes:

FileInputStream: Reads byte data from a file.


FileOutputStream: Writes byte data to a file.

Example of Byte Stream:

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

public class ByteStreamExample {


public static void main(String[] args) {
try {
// Writing bytes to a file
FileOutputStream fos = new FileOutputStream("output.txt");
String data = "Hello, Byte Stream!";
fos.write(data.getBytes());
fos.close();

// Reading bytes from a file


FileInputStream fis = new FileInputStream("output.txt");
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

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.

Common Character Stream Classes:

FileReader: Reads character data from a file.


FileWriter: Writes character data to a file.

Example of Character Stream:

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

public class CharacterStreamExample {


public static void main(String[] args) {
try {
// Writing characters to a file
FileWriter writer = new FileWriter("textfile.txt");
writer.write("Hello, Character Stream!");
writer.close();

// Reading characters from a file


FileReader reader = new FileReader("textfile.txt");
int content;
while ((content = reader.read()) != -1) {
System.out.print((char) content);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Scanner Class
The Scanner class (from java.util package) is commonly used to read user input in Java.
It can read data types like int , double , String , etc., and can read from different sources
like the console, files, and strings.

Common Methods in Scanner Class:

nextInt() : Reads an integer.


nextDouble() : Reads a double.
nextLine() : Reads an entire line.
next() : Reads a single word.

Example of Scanner Class for User Input:

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 + ", Age: " + age);

scanner.close();
}
}

Example of Scanner Class for Reading a File:

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("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}

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.

Common Methods in File Class:

createNewFile() : Creates a new file if it does not exist.


exists() : Checks if a file exists.
delete() : Deletes a file.
mkdir() : Creates a new directory.
listFiles() : Returns an array of files in the directory.

Example of File Handling in Java:

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

public class FileExample {


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

// Creating a new file


if (file.createNewFile())
{
System.out.println("File created: " + file.getName());
}
else
{
System.out.println("File already exists.");
}
// Checking if the file exists
if (file.exists()) {
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + "
bytes");
}

// Deleting the file


if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like