[go: up one dir, main page]

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

OOPJ(java) Unit-IV

Unit-IV covers Packages and Java Library, Exception Handling, and Java I/O and File. It includes topics such as defining and importing packages, access control, exception handling mechanisms, and Java I/O streams. The document provides detailed explanations, examples, and syntax for various Java programming concepts and classes.
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 views47 pages

OOPJ(java) Unit-IV

Unit-IV covers Packages and Java Library, Exception Handling, and Java I/O and File. It includes topics such as defining and importing packages, access control, exception handling mechanisms, and Java I/O streams. The document provides detailed explanations, examples, and syntax for various Java programming concepts and classes.
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/ 47

Unit-IV

Packages and Java Library , Exception Handling , Java I/O and File

S.No Name of the Topic Page No Date


Chapter-I Packages and Java Library
4.1 Introduction, Defining Package, Importing Packages and Classes into Programs 2-6
4.2 Path and Class Path, Access Control 6-8
4.3 Packages in Java SE, Java.lang Package and its Classes 9-10
4.4 Class Object , Enumeration, class Math 10-14
4.5 Wrapper Classes 15
4.6 Auto-boxing and Auto-unboxing 16-17
4.7 Java util Classes and Interfaces 17-18
4.8 Formatter Class, Random Class 19-20
4.9 Time Package, Class Instant (java.time.Instant) 21-23
4.10 Formatting for Date/Time in Java 23
4.11 Temporal Adjusters Class 24-25
Chapter-II Exception Handling
4.12 Introduction, Hierarchy of Standard Exception Classes 26-27
4.13 Keywords throws and throw, try, catch, and finally Blocks 27-34
4.14 Multiple Catch Clauses 35
4.15 Class Throwable 36
4.16 Unchecked Exceptions 37-38
4.17 Checked Exceptions 38
Chapter-III Java I/O and File
4.18 Java I/O API, standard I/O streams , types 39-41
4.19 Byte streams, Character streams 41-44
4.20 Scanner class 44
4.21 Files in Java 45-47
4.1 Introduction, Defining Package, Importing Packages and Classes into Programs

a)Introduction:

 In java, a package is a container of classes, interfaces, and sub-packages.


 Package is the first statement in a program, no other coding lines placed above of it except comments.
 We may think of it as a folder in a file directory.
 We use the packages to organize project-related classes, interfaces, and sub-packages into a bundle.
Advantage of Java Package:
 Java package is used to categorize the classes and interfaces so that they can be easily maintained.
 Java package provides access protection.

b) Defining Package :

We use the package keyword to create or define a package .


Syntax : package packageName;
 The package statement must be the first statement in the program.
 The package name must be a single word (spaces not allowed).
 The package name must use Camel case notation (lower case).
Note: To compile and run the program we should follow the following format
To Compile: javac -d . directory.javafilename
The -d switch specifies the destination where to put the generated class file.
To Run: java packagename.filename

Example (code to create a user-defined package myPackage)


package myPackage;
public class DefiningPackage
{
public static void main(String[] args)
{
System.out.println(" This class belongs to myPackage ");
}
}
Compile: javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage, and
the DefiningPackage.class is saved into it.
Run : java myPackage.DefiningPackage
Note: When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.

Object Oriented Programming Through Java Page 2


c) Importing Packages and Classes into Programs:
 In java, the import keyword used to import built-in and user-defined packages.
 When a package has imported, we can refer to all the classes of that package using their name directly.
 The import statement must be after the package statement, and before any other statement.
 Using an import statement, we may import a specific class or all the classes from a package.
 Using one import statement, we may import only one package or a class.
 A program may contain any number of import statements.
access package from another package
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
1) Using packagename.*
 If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
 The import keyword is used to make the classes and interface of another package accessible to the
current package.
Example (//save by A.java )

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello

Object Oriented Programming Through Java Page 3


Example
package myPackage;
import java.util.Scanner;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
}
}
In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class
called Scanner from java.utilpackage.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example (//save by A.java )

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

package mypack; (//save by B.java )


import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello

Object Oriented Programming Through Java Page 4


Example

package myPackage;
import java.util.*;
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the
classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.
3) Using fully qualified name
 If you use fully qualified name then only declared class of this package will be accessible.
 Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example (//save by A.java )
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output: Hello

Object Oriented Programming Through Java Page 5


Note: If you import a package, subpackages will not be imported.
 Subpackage(Package inside the package is called the subpackage.)
 If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-
package.
Example :
import java.util.*;
The above import statement util is a sub-package of java package. It imports all the classes of util package only,
but not classes of java package.
4.2 Path and Class Path, Access Control
a) Path and Class Path
Path
 PATH is an environment variable that is used to find and locate binary files like “java” and “javac”
and to locate needed executables from the command line or Terminal window.
 To set the path, we’re supposed to include or mention JDK_HOME/bin directory in a PATH
environment variable.
 The PATH can not be overridden by providing command and PATH is only used by the operation
System(OS) to find binary files.
Syntax : // To set PATH in the window OS.
set PATH = %PATH%;C:\Program Files\Java\JDK1.5.10\bin
Classpath:
 Classpath is an environment variable that is used by the application ClassLoader or system to locate
and load the compiled Java bytecodes stored in the .class file.
 To set CLASSPATH. the CLASSPATH can be overridden by adding classpath in the manifest file and
by using a command like set - classpath.
 The CLASSPATH is only used by Java ClassLoaders to load class files.
Syntax : // To set CLASSPATH in window OS.
set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\JDK1.5.10\lib

S. No. PATH CLASSPATH

1. An environment variable is used by the operating An environment variable is used by the Java
system to find the executable files. compiler to find the path of classes.

2. PATH setting up an environment for the operating Classpath setting up the environment for Java.
system. OS will look in this PATH for executables. Java will use to find compiled classes.

Object Oriented Programming Through Java Page 6


Permanent java classpath setting:
 Firstly, Right Click on “This PC”.
 Click Properties.
 Click “Advanced System Settings”.
 Click “Environment Variables”.
 In the “User Variable Section”, click the “New” button.
 Enter Variable name :classpath [Don’t give space between class path] Variable
value:<directory_location>(for example in my F:\workspace\bin)
 Click OK->OK->OK.
 Close all windows, open a new command prompt, and run the java command

b) Access Control (or) Access protection in java packages

 In java, the access modifiers define the accessibility(visibility) of the class and its members.
 Java has four access modifiers, and they are default, private, protected, and public.
 The class acts as a container of data and methods. So, the access modifier decides the accessibility of
class members across the different packages.

 The public members can be accessed everywhere.


 The private members can be accessed only inside the same class.
 The protected members are accessible to every child class (same package or other packages).
 The default members are accessible within the same package but not outside the package.

Object Oriented Programming Through Java Page 7


Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println(" Inside ParentClass ");
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" c = " + c);
System.out.println(" d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}

Object Oriented Programming Through Java Page 8


4.3 Packages in Java SE, Java.lang Package and its Classes
 In java, the packages have divided into two types.
Built-in Packages
User-defined Packages
a) Built-in Packages
 The built-in packages are the packages from java API. The Java API is a library of pre-defined classes,
interfaces, and sub-packages. The built-in packages were included in the JDK.
 There are many built-in packages in java, few of them are as java, lang, io, util, awt, net, sql, etc.

User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own packages.
b) Java.lang Package and its Classes
Following is the list of important classes in java.lang.package:
Boolean − The Boolean class wraps a value of the primitive type boolean in an object. An object of type
Boolean contains a single field whose type is boolean.
Byte − The Byte class class wraps a value of primitive type byte in an object. An object of type Byte
contains a single field whose type is byte.
Character − The Character class offers a number of useful class (i.e., static) methods for manipulating
characters.
Compiler − The Compiler class is provided to support Java-to-native-code compilers and related services.
By design, it serves as a placeholder for a JIT compiler implementation.
Double − The Double class wraps a value of primitive type double in an object. An object of type Double
contains a single field whose type is double.
Enum − The Enum class is the common base class of all Java language enumeration types.
Float − The Float class wraps a value of primitive type float in an object. An object of type Float contains a
single field whose type is float.
Integer − The Integer class wraps a value of primitive type int in an object. An object of type Integer
contains a single field whose type is int.

Object Oriented Programming Through Java Page 9


Long − The Long class wraps a value of the primitive type long in an object. An object of type Long
contains a single field whose type is long.
Math − The Math class contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
Number − The Number class is an abstract class in java.lang package. It is the superclass of the classes that
represent numeric values convertible to primitive data types such as byte, short, int, long, float, and double.
Object − The Object class is the root of the class hierarchy. Every class has Object as a superclass. All
objects, including arrays, implement the methods of this class.
4.4 Class Object , Enumeration, class Math
a) Class Object : Refer Unit-III Concept no: 3.14 page no : 34-39
b) Enumeration :
 An enum is a special "class" that represents a group of constants (unchangeable variables, like final
variables).
 This concept enables the java enum to have constructors, methods, and instance variables.
 All the constants of an enum are public, static, and final.
 As they are static, we can access directly using enum name.
 The main objective of enum is to define our own data types in Java, and they are said to be enumeration
data types.
Creating enum in Java
 In java, an enum can be defined outside a class, inside a class, but not inside a method.
 To create an enum, use the enum keyword , and separate the constants with a comma.
 Note that they should be in uppercase letters:
 Access enum constants with the dot syntax
 Enum is short for "enumerations", which means "specifically listed".
 Every constant of an enum is defined as an object and enum does not allow to create an object of it.
 As an enum represents a class, it can have methods, constructors. It also gets a few extra methods from
the Enum class, and one of them is the values() method.
Enum using values() method
The enum type has a values() method, which returns an array of all enum constants.
This method is useful when you want to loop through the constants of an enum:

Example
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

Object Oriented Programming Through Java Page 10


public class EnumerationExample
{
public static void main(String[] args)
{
WeekDay day = WeekDay.FRIDAY;
System.out.println(" Today is " + day);
System.out.println("\n All WeekDays: ");
for(WeekDay d : WeekDay.values())
{
System.out.println(d);
}
}
}
Output:
Today is FRIDAY

All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Java Enum ordinal() Method

The ordinal() method of Enum class returns the ordinal of this enumeration constant.
This method is designed to be used by sophisticated enum-based data structures, like EnumSet and EnumMap.
Syntax
public final int ordinal()

Return Value
The ordinal() method returns this enumeration constant's ordinal.

Example
public class Enum_ordinalMethodExample1
{
enum Colours
{
Red,Green,Brown,Yellow;
}

Object Oriented Programming Through Java Page 11


public static void main(String[] args)
{
Colours Red = Colours.Red;
Colours Green = Colours.Green;
Colours Brown = Colours.Brown;
Colours Yellow = Colours.Yellow;
System.out.println(" Red ordinal = "+Red.ordinal());
System.out.println(" Green Ordinal = "+Green.ordinal());
System.out.println(" Brown Ordinal = "+Brown.ordinal());
System.out.println(" Yellow Ordinal = "+Yellow.ordinal());
}
}

Output:
Red ordinal = 0
Green Ordinal = 1
Brown Ordinal = 2
Yellow Ordinal = 3

c) class Math
Java Math Methods

The java.lang.Math class contains various methods for performing basic numeric operations such as the
logarithm, cube root, and trigonometric functions etc. The various java math methods are as follows:

Method Description

Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.


Math.sqrt() It is used to return the square root of a number.

Math.cbrt() It is used to return the cube root of a number.

Math.pow() It returns the value of first argument raised to the power to second argument.

Object Oriented Programming Through Java Page 12


Trigonometric Math Methods

Method Description

Math.sin() It is used to return the trigonometric Sine value of a Given double value.

Math.cos() It is used to return the trigonometric Cosine value of a Given double value.

Math.tan() It is used to return the trigonometric Tangent value of a Given double value.

Math.asin() It is used to return the trigonometric Arc Sine value of a Given double value

Math.acos() It is used to return the trigonometric Arc Cosine value of a Given double value.

Math.atan() It is used to return the trigonometric Arc Tangent value of a Given double value.
Example:
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;

System.out.println("Maximum number of x and y is: " +Math.max(x, y));


System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));

System.out.println("Logarithm of x is: " + Math.log(x));


System.out.println("Logarithm of y is: " + Math.log(y));

System.out.println("log10 of x is: " + Math.log10(x));


System.out.println("log10 of y is: " + Math.log10(y));

}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java JavaMathExample1
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624

Object Oriented Programming Through Java Page 13


Example 2:

public class JavaMathExample2


{
public static void main(String[] args)
{
double a = 30;

double b = Math.toRadians(a); // converting values to radian

System.out.println("Sine value of a is: " +Math.sin(a));

System.out.println("Cosine value of a is: " +Math.cos(a));

System.out.println("Tangent value of a is: " +Math.tan(a));

System.out.println("Sine value of a is: " +Math.asin(a));

System.out.println("Cosine value of a is: " +Math.acos(a));

System.out.println("Tangent value of a is: " +Math.atan(a));

System.out.println("Sine value of a is: " +Math.sinh(a));

System.out.println("Cosine value of a is: " +Math.cosh(a));

System.out.println("Tangent value of a is: " +Math.tanh(a));


}
}

Output:

D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java JavaMathExample2

Sine value of a is: -0.9880316240928618


Cosine value of a is: 0.15425144988758405
Tangent value of a is: -6.405331196646276
Sine value of a is: NaN
Cosine value of a is: NaN
Tangent value of a is: 1.5374753309166493
Sine value of a is: 5.343237290762231E12
Cosine value of a is: 5.343237290762231E12
Tangent value of a is: 1.0

Object Oriented Programming Through Java Page 14


4.5 Wrapper Classes
 A Wrapper class in Java is a class whose object wraps or contains primitive data types.
 When we create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types.
 In other words, we can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
There are certain needs for using the Wrapper class in Java:
 They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
 Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
 An object is needed to support synchronization in multithreading.
Advantages of Wrapper Classes
 Collections allowed only object data.
 On object data we can call multiple methods compareTo(), equals(), toString()
 Cloning process only objects
 Object data allowed null values.
 Serialization can allow only object data.
Primitive Data Types and their Corresponding Wrapper Class

Primitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

Object Oriented Programming Through Java Page 15


4.6 Auto-boxing and Auto-unboxing
 All the primitive data types have defined using the class concept, these classes known as wrapper
classes.
 In java, every primitive type has its corresponding wrapper class. (refer page 15)
 All the wrapper classes in Java were defined in the java.lang package.
The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and
reverses of it.
Autoboxing in Java
 In java, the process of converting a primitive type value into its corresponding wrapper class object is
called autoboxing or simply boxing.
 For example, converting an int value to an Integer class object.
 The compiler automatically performs the autoboxing when a primitive type value has assigned to an
object of the corresponding wrapper class.
 We can also perform autoboxing manually using the method valueOf( ), which is provided by every
wrapper class.
Example - Autoboxing
import java.lang.*;
public class AutoBoxingExample
{
public static void main(String[] args)
{
int num = 100; // Auto boxing : primitive to Wrapper
Integer i = num;
Integer j = Integer.valueOf(num);
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Output:
D:\SASI\sasijava>javac AutoBoxingExample.java
D:\SASI\sasijava>java AutoBoxingExample
num = 100, i = 100, j = 100
Auto un-boxing in Java
 In java, the process of converting an object of a wrapper class type to a primitive type value is called
auto un-boxing or simply unboxing.
 For example, converting an Integer object to an int value.
 The compiler automatically performs the auto un-boxing when a wrapper class object has assigned to a
primitive type.
 We can also perform auto un-boxing manually using the method intValue( ), which is provided by
Integer wrapper class. Similarly every wrapper class has a method for auto un-boxing.

Object Oriented Programming Through Java Page 16


Example - Auto unboxing
import java.lang.*;
public class AutoUnboxingExample
{
public static void main(String[] args)
{
Integer num = 200; // Auto un-boxing : Wrapper to primitive
int i = num;
int j = num.intValue();
System.out.println("num = " + num + ", i = " + i + ", j = " + j);
}
}
Output:
D:\SASI\sasijava>javac AutoUnboxingExample.java
D:\SASI\sasijava>java AutoUnboxingExample
num = 200, i = 200, j = 200
4.7 Java util Classes and Interfaces
Contains the collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes .
Interface Summary

Interface Description

Collection<E> The root interface in the collection hierarchy.

Comparator<T> A comparison function, which imposes a total ordering on some collection of objects.

Deque<E> A linear collection that supports element insertion and removal at both ends.

Enumeration<E> An object that implements the Enumeration interface generates a series of elements, one at a
time.
EventListener A tagging interface that all event listener interfaces must extend.

Formattable The Formattable interface must be implemented by any class that needs to perform custom
formatting using the 's' conversion specifier of Formatter.
Iterator<E> An iterator over a collection.

List<E> An ordered collection (also known as a sequence).

ListIterator<E> An iterator for lists that allows the programmer to traverse the list in either direction, modify
the list during iteration, and obtain the iterator's current position in the list.
Map<K,V> An object that maps keys to values.

Object Oriented Programming Through Java Page 17


Class Summary

Class Description

AbstractCollection<E> This class provides a skeletal implementation of the Collection interface,


to minimize the effort required to implement this interface.

AbstractList<E> This class provides a skeletal implementation of the List interface to minimize the effort
required to implement this interface backed by a "random access" data store (such as an
array).
AbstractMap<K,V> This class provides a skeletal implementation of the Map interface, to
minimize the effort required to implement this interface.

AbstractMap.SimpleEntry<K,V> An Entry maintaining a key and a value.

AbstractMap.SimpleImmutableEntry<K,V> An Entry maintaining an immutable key and value.

AbstractQueue<E> This class provides skeletal implementations of some Queue operations.

AbstractSequentialList<E> This class provides a skeletal implementation of the List interface to


minimize the effort required to implement this interface backed by a
"sequential access" data store (such as a linked list).
AbstractSet<E> This class provides a skeletal implementation of the Set interface to
minimize the effort required to implement this interface.

ArrayDeque<E> Resizable-array implementation of the Deque interface.

ArrayList<E> Resizable-array implementation of the List interface.

Arrays This class contains various methods for manipulating arrays (such as
sorting and searching).

Calendar The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such
as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the
calendar fields, such as getting the date of the next week.

Collections This class consists exclusively of static methods that operate on or return
collections.

Currency Represents a currency.

Date The class Date represents a specific instant in time, with millisecond
precision.

Scanner A simple text scanner which can parse primitive types and strings using
regular expressions.

Stack<E> The Stack class represents a last-in-first-out (LIFO) stack of objects.

Timer A facility for threads to schedule tasks for future execution in a


background thread.

Vector<E> The Vector class implements a growable array of objects.

Object Oriented Programming Through Java Page 18


4.8 Formatter Class, Random Class
Formatter Class:
 The Formatter is a built-in class in java used for layout justification and alignment, common formats
for numeric, string, and date/time data, and locale-specific output in java programming.
 The Formatter class is defined as final class inside the java.util package.
 The Formatter class implements Cloneable and Flushable interface.
 The Formatter class in java has the following constructors.
Example:
import java.util.Formatter;
public class FomatterExample
{
public static void main(String args[]) throws Exception
{
int num[] = {10, 21, 13, 4, 15, 6, 27, 8, 19};

Formatter fmt = new Formatter();

fmt.format("%15s %15s %15s\n", "Number", "Square", "Cube");

for (int n : num)


{
fmt.format("%14s %14s %17s\n", n, (n*n), (n*n*n));
}
System.out.println(fmt);
}
}
Output:
D:\ACEM\II AI DS>javac FomatterExample.java
D:\ACEM\II AI DS>java FomatterExample
Number Square Cube
10 100 1000
21 441 9261
13 169 2197
4 16 64
15 225 3375
6 36 216
27 729 19683
8 64 512
19 361 6859

Object Oriented Programming Through Java Page 19


Random Class
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java
programming. The Random class is available inside the java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
 The Random class is a part of java.util package.
 The Random class provides several methods to generate random numbers of type integer, double, long,
float etc.
 The Random class is thread-safe.
 Random number generation algorithm works on the seed value. If not provided, seed value is created
from system nano time.
Example:
import java.util.Random;
public class JavaRandomExample
{
public static void main(String[] args)
{
Random random = new Random();

//return the next pseudorandom integer value


System.out.println("Random Integer value : "+random.nextInt());

// setting seed

long seed =20;


random.setSeed(seed);

//value after setting seed


System.out.println("Seed value : "+random.nextInt());
//return the next pseudorandom long value

Long val = random.nextLong();


System.out.println("Random Long value : "+val);
}

}
Output:
D:\ACEM\II AI DS>javac JavaRandomExample.java
D:\ACEM\II AI DS>java JavaRandomExample
Random Integer value : -1652727993
Seed value : -1150867590
Random Long value : -7322354119883315205

Object Oriented Programming Through Java Page 20


4.9 Time Package, Class Instant (java.time.Instant)
The java.time, java.util, java.sql and java.text packages contains classes for representing date and time.

Class Summary

Class Description

Clock A clock providing access to the current instant, date and time using a time-zone.

Duration A time-based amount of time, such as '34.5 seconds'.

Instant An instantaneous point on the time-line.

LocalDate A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.

LocalDateTime A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalTime A time without a time-zone in the ISO-8601 calendar system, such as 10:15:30.

MonthDay A month-day in the ISO-8601 calendar system, such as --12-03.

Year A year in the ISO-8601 calendar system, such as 2007.

YearMonth A year-month in the ISO-8601 calendar system, such as 2007-12.

ZoneId A time-zone ID, such as Europe/Paris.

Example:

import java.time.LocalDate;
public class LocalDateExample1
{
public static void main(String[] args)
{
LocalDate date = LocalDate.now();

LocalDate yesterday = date.minusDays(1);


LocalDate tomorrow = yesterday.plusDays(2);

System.out.println("Today date: "+date);


System.out.println("Yesterday date: "+yesterday);
System.out.println("Tomorrow date: "+tomorrow);
}
}
Output:
Today date: 2017-01-13
Yesterday date: 2017-01-12
Tomorrow date: 2017-01-14

Object Oriented Programming Through Java Page 21


Example:
import java.time.YearMonth;
public class YearMonthExample1
{
public static void main(String[] args)
{
YearMonth ym = YearMonth.now();
System.out.println(ym);
}
}

Output:
2017-01

Class Instant (java.time.Instant)


In Java language, the Instant Class is used to represent the specific time instant on the current timeline.
The time object return by this class is expressed in seconds from mid night of 1st January 1970, which is also
called as epoch.
Methods in Class Instant:

Method Description

isAfter(Instant otherInstant) This method checks if this instant is after the specified instant.

isBefore(Instant otherInstant) This method checks if this instant is before the specified instant.

minus(long amountToSubtract, This method returns a copy of this instant with the specified amount
TemporalUnit unit) subtracted.

now() This method obtains the current instant from the system clock.

until(Temporal endExclusive, This method calculates the amount of time until another instant in terms
TemporalUnit unit) of the specified unit.
Example:
import java.time.*;
public class InstantExample
{
public static void main(String[] args)
{
Instant cur = Instant.now();
System.out.println("Current Instant is " + cur);

Object Oriented Programming Through Java Page 22


Instant diff = cur.minus(Duration.ofDays(70)); // Using minus() to find instant value after subtraction

System.out.println("Instant after subtraction : "+ diff); // Using plus()to find instant value after addition

Instant sum = cur.plus(Duration.ofDays(10));


System.out.println("Instant after addition : "+ sum);
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java InstantExample
Current Instant is 2024-09-12T11:18:57.349649300Z
Instant after subtraction : 2024-07-04T11:18:57.349649300Z
Instant after addition : 2024-09-22T11:18:57.349649300Z
4.10 Formatting for Date/Time in Java
Class DateTimeFormatter
 java.time.format.DateTimeFormatter
 public final class DateTimeFormatter extends Object
 This class provides the main application entry point for printing and parsing and provides common
implementations of DateTimeFormatter:
Using predefined constants, such as ISO_LOCAL_DATE
Using pattern letters, such as uuuu-MMM-dd
Using localized styles, such as long or medium
Program:

import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.util.Formatter;
import java.text.Format;
class TimeFormats
{
public static void main(String args[])
{
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
System.out.println(parsedDate );
}
}
Output: D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TimeFormats
2024-09-20
Object Oriented Programming Through Java Page 23
4.11 Temporal Adjusters Class
 TemporalAdjusters Class in Java provides Adjusters, which are a key tool for modifying temporal
objects.
Examples include an adjuster that sets the date like “Second Saturday of the Month” or “Next
Tuesday”, or one that sets the date to the last day of the month.
TemporalAdjuster can be used in two ways.
 The first is by invoking the method on the interface directly. The second is by using
Temporal.with(TemporalAdjuster):
 The following two ways of using TemporalAdjuster are equivalent, but it is recommended to use the
second approach, as it is cleaner and readable
temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);

Methods
Method Description

This method is used to return the day-of-week in month adjuster,


dayOfWeekInMonth(int ordinal,
which returns a new date object within the same month with the
DayOfWeek dayOfWeek)
ordinal day-of-week.

This method is used to return the “first day of month” adjuster,


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

This method is used to return the “first day of next month” adjuster,
firstDayOfNextMonth()
which returns a new date set to the first day of the next month.

This method is used to return the “first day of next year” adjuster,
firstDayOfNextYear()
which returns a new date set to the first day of the next year.

This method is used to return the “first day of year” adjuster, which
firstDayOfYear()
returns a new date set to the first day of the current year.

This method is used to return the first in month adjuster, which


firstInMonth(DayOfWeek dayOfWeek) returns a new date in the same month with the first matching day-of-
week.

This method is used to return the “last day of month” adjuster, which
lastDayOfMonth()
returns a new date set to the last day of the current month.

This method is used to return the “last day of year” adjuster, which
lastDayOfYear()
returns a new date set to the last day of the current year.

Object Oriented Programming Through Java Page 24


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

public class TemporalAdjusterExample


{

public static void main(String args[])


{
TemporalAdjusterExample obj = new TemporalAdjusterExample();
obj.testAdjusters();
}

public void testAdjusters()


{

LocalDate date1 = LocalDate.now();


System.out.println("Today's date is: " + date1); // to get the current date

// to get the next monday


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

// to get the second saturday of next month


LocalDate firstInYear = LocalDate.of(date1.getYear(), date1.getMonth(), 1);

}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TemporalAdjusterExample
Today's date is: 2024-09-22
Next Monday is on : 2024-09-23

Object Oriented Programming Through Java Page 25


Chapter-II Exception Handling
4.12 Introduction, Hierarchy of Standard Exception Classes
 An exception is a problem or an abnormal condition that arises during the program execution (at run
time).
 In other words an exception is a run time error.
 When an Exception occurs the normal flow of the program is interrupts the flow and the program
terminates abnormally, therefore these exceptions are to be handled.
An exception can occur for many different reasons, including the following:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Errors
No matter how good a program we write it may cause the following types of errors.
1. Syntax Errors or 2. Logical Errors or 3. Runtime Errors
Syntax Errors:
It is an error which occurs when the rules of language are violated .
If we are not following the rules, those cause the error. It can be easily detected and corrected by compilers.
Eg: Statement missing semicolon; , Missing/expected „ }‟ , Un-defined symbol varname etc.
Logical Error:
It is an error caused due to manual mistake in the logical expressions. These errors cannot be detected by the
compiler.
Eg. Current_balance = old_balance*cash_deposit
Runtime Error:
It is an Error, which occurs after executing the program at runtime.
Eg. Divide by zero.
File not found
No disc in the drive etc.
3 Built-in Exceptions (checked & Unchecked exceptions) (or) Hierarchy of Standard Exception Classes
 Exception that are already available in Java libraries are referred to as built-in exception.
 These exceptions are able to define the error situation so that we can understand the reason of getting
this error. It can be categorized into two broad categories, i.e., checked exceptions and unchecked
 All the built-in exception classes in Java were defined a package java.lang.

Object Oriented Programming Through Java Page 26


The hierarchy of Java Exception classes
The Exception class is used for exception conditions that the application may need to handle.
Examples of exceptions include IllegalArgumentException, ClassNotFoundException and NullPointerException
The Error class is used to indicate a more serious problem in the architecture and should not be handled in the
application code.
Examples of errors include InternalError, OutOfMemoryError and AssertionError.
Exceptions are further subdivided into checked (compile-time) and unchecked (run-time) exceptions.
All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses of Exception
besides RuntimeException are checked exceptions.
4.13 Keywords throws and throw, try, catch, and finally Blocks
try-catch block
 In java, the try and catch, both are the keywords used for exception handling.
 The keyword try is used to define a block of code that will be tests the occurrence of an exception.
 The keyword catch is used to define a block of code that handles the exception occurred in the
respective try block.
 Both try and catch are used as a pair. Every try block must have one or more catch blocks.
Syntax
try
{
code to be tested
}
catch(ExceptionType object)
{
code for handling the exception
}

Object Oriented Programming Through Java Page 27


Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1 (TryCatchExample1.java)
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of the
code statement is not printed).
There might be 100 lines of code after the exception. If the exception is not handled, all the code below the
exception won't be executed.
Solution by exception handling ( the above problem by a java try-catch block)
Example 2 (TryCatchExample2.java)
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data = 50/0; //may throw exception
}
catch(ArithmeticException e) //handling the exception
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code

Object Oriented Programming Through Java Page 28


throw , throws and finally keywords
Java throw keyword
 The Java throw keyword is used to throw an exception explicitly.
 We specify the exception object which is to be thrown. The Exception has some message with it that
provides the error description. These exceptions may be related to user inputs, server, etc.
 We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to
throw a custom(user defined) exception.
 We can also define our own set of conditions and throw an exception explicitly using throw keyword.
syntax
throw new exception_class("error message");
Example
throw new IOException("sorry device error");
Example 1: Throwing Unchecked Exception
public class TestThrow1
{
public static void validate(int age) //function to check if person is eligible to vote or not
{
if(age<18)
{
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[])
{
validate(13); //calling the function
System.out.println("rest of the code...");
}
}
Output:
D:\sasi>javac TestThrow1.java
D:\sasi>java TestThrow1
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.

Object Oriented Programming Through Java Page 29


Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws
clause.
If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.
Java throws keyword
 The Java throws keyword is used to declare an exception.
 Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code before
it being used.
Syntax:
return_type method_name() throws exception_class_name
{
//method code
}
Advantage of Java throws keyword
 Now Checked Exception can be propagated (forwarded in call stack).
 It provides information to the caller of the method about the exception.
Java throws Example

import java.io.IOException;
class Testthrows1
{
void m() throws IOException
{
throw new IOException("device error"); //checked exception
}
void n() throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}

Object Oriented Programming Through Java Page 30


public static void main(String args[])
{
Testthrows1 obj = new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rules:
If we are calling a method that declares an exception, we must either caught or declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.
Difference between throw and throws in Java

S.no Differences Throw Throws

1. Definition throw keyword is used throw an Java throws keyword is used in the method
exception explicitly from inside the signature.
function .

2. Type of Using throw keyword, we can only Using throws keyword, we can declare both
exception propagate unchecked exception i.e., the checked and unchecked exceptions. However,
checked exception cannot be propagated the throws keyword can be used to propagate
using throw only. checked exceptions only.

3. Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.

4. Declaration throw is used within the method. throws is used with the method signature.

Java throw and throws Example (TestThrowAndThrows.java)


public class TestThrowAndThrows
{
// defining a user-defined method which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println(" Inside the method() ");
throw new ArithmeticException(" throwing ArithmeticException ");
}

Object Oriented Programming Through Java Page 31


public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
Output:
D:\sasi>javac TestThrowAndThrows.java
D:\sasi>java TestThrowAndThrows
Inside the method()
caught in main() method

Java finally block


Java finally block is a block used to execute important code such as closing the connection, etc.
Flowchart of finally block

Note:
If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
 finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.

 The important statements to be printed can be placed in the finally block.

Uses:
Case 1: When an exception does not occur
Case 2: When an exception occurs but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block

Object Oriented Programming Through Java Page 32


Case 1: When an exception does not occur (TestFinallyBlock.java)
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\sasi>javac TestFinallyBlock.java
D:\sasi>java TestFinallyBlock
5
finally block is always executed
rest of the code...
Case 2: When an exception occurs but not handled by the catch block

The code throws an exception however the catch block cannot handle it.
Even though, the finally block is executed after the try block and then the program terminates abnormally.

TestFinallyBlock1.java
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}

Object Oriented Programming Through Java Page 33


finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero

Case 3: When an exception occurs and is handled by the catch block

Example where the Java code throws an exception and the catch block handles the exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(" Exception handled ");
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
Exception handled
finally block is always executed
rest of the code...
Note:
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if the program exits ( by calling System.exit())

Object Oriented Programming Through Java Page 34


4.14 Multi-catch block
 A try block can be followed by one or more catch blocks.
 Each catch block must contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.
Points to remember
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException
must come before catch for Exception.
Flowchart of Multi-catch Block

Example 1 MultipleCatchBlock1.java
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output: Arithmetic Exception occurs
rest of the code

Object Oriented Programming Through Java Page 35


4.15 Throwable class
 The Throwable class is the super class of every error and exception in the Java language.
 Only objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or
may be thrown by the Java throw statement..
Example:
import java.io.IOException;
class Testthrows2
{
public static void main(String args[])
{
try
{
int a = 10/0;
}
catch(Throwable t)
{
System.out.println(t.toString()); //This method returns a short description of current throwable.
System.out.println(t.getMessage()); //Returns the detail message string of current throwable.
t.printStackTrace(); //Prints the current throwable and its backtrace to the standard error stream.
}
}
}
Output:
D:\ACEM\II AI DS>java Testthrows2
java.lang.ArithmeticException: / by zero
/ by zero
java.lang.ArithmeticException: / by zero
at Testthrows2.main(Testthrows2.java:8)

Object Oriented Programming Through Java Page 36


4.16 & 4.17 Types of Exception in Java (or) Checked & Unchecked Exceptions (uncaught Exceptions)
Bugs or errors that we don't want and restrict our program's normal execution of code are referred to
as exceptions.
Exceptions can be categorized into two ways:
1. Built-in Exceptions
 Checked Exception

 Unchecked Exception

2. User-Defined Exceptions

Difference Between Checked and Unchecked Exception(uncaught Exception)

S. Checked Exception Unchecked Exception


No

1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time too. exceptions. These exceptions are not checked and
handled at compile time.

2. These exceptions are direct subclasses of They are the direct subclasses of the
Exception RuntimeException class.

3. Common checked exceptions include Common unchecked exceptions include


IOException, DataAccessException, ArithmeticException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.

4. These exceptions are propagated using the throws These are automatically propagated.
keyword

5. It is required to provide the try-catch and try- In the case of unchecked exception it is not
finally block to handle the checked exception. mandatory.

Object Oriented Programming Through Java Page 37


Unchecked Exceptions:

S. Example
No. Exception Class with Description

1 ArithmeticException int a = 30, b = 0;


It handles the arithmetic exceptions like dividion by zero int c = a/b;

2 ArrayIndexOutOfBoundsException int a[] = new int[5];


It handles the situations like an array has been accessed with an illegal a[6] = 9;
index like ( index is either negative or greater than or equal to the size of
the array).

3 ArrayStoreException Double[] a = new Double[2];


It handles the situations like when an attempt has been made to store the
wrong type of object into an array of objects a[0] = new Integer(4);

4 ClassCastException Object o = new Object();


It handles the situation when we try to improperly cast a class from one String s = (String)o;
type to another.

5 IndexOutOfBoundsException int ar[] = { 1, 2, 3, 4, 5 };


It is thrown when attempting to access an invalid index within a System.out.println(ar[9]);
collection, such as an array, vector , string , and so forth.

6 NegativeArraySizeException int ar[] = new int[-9];


It is thrown if an applet tries to create an array with negative size.

7 NullPointerException String s =null;


it is thrown when program attempts to use an object reference that has s.length();
the null value.

8 NumberFormatException String s = "aditya ";


It is thrown when we try to convert a string into a numeric value such as Integer i =
float or integer, but the format of the input string is not appropriate or Integer.parseInt(s);
illegal.

9 StringIndexOutOfBounds String s = "aditya ";


It is thrown by the methods of the String class, in order to indicate that s.charAt[8];
an index is either negative, or greater than the size of the string itself.

Checked Exceptions:
ClassNotFoundException
IOException
SQLException
InterruptedException
FileNotFoundException

Object Oriented Programming Through Java Page 38


Chapter-III Java I/O and File
 In java, the IO operations are performed using the concept of streams.
 Generally, a stream means a continuous flow of data.
 In java, a stream is a logical container of data that allows us to read from and write to it.
 The stream-based IO operations are faster than normal IO operations.
 The Stream is defined in the java.io package.
4.18 Java I/O API
 The Java Input/Output (I/O) is a part of java.io package.
 This package contains a relatively large number of classes that support input and output operations.
 These classes may be categorized into groups based on the data type on which they operate.
 Byte Stream Classes that provide support for handling I/O operations on bytes.
 Character Stream Classes that provide support for managing I/O operations on characters.
 These two groups may further be classified based on their purpose.
 Diagram 3 below shows how stream classes are grouped based on their functions.
 Byte stream and Character stream classes contain specialized input and output stream classes to deal
with input and output operations independently on various types of streams.

standard I/O streams


To understand the functionality of java streams, look at the following picture.

Object Oriented Programming Through Java Page 39


 The stream-based IO operations are performed using two separate streams input stream and output
stream.
 The input stream is used for input operations, and the output stream is used for output operations.
 The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the console.
 System.out: standard output stream for console output operations.
 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive data types,
localized characters, and objects.
Types of Streams:
Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream:
These streams are used to read data that must be taken as an input from a source array or file or any
peripheral device.
For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream:
These streams are used to write data as outputs into an array or file or any output peripheral device.
For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc

Object Oriented Programming Through Java Page 40


 Depending on the types of file, Streams can be divided into two primary classes which can be further
divided into other classes as can be seen through the diagram below followed by the explanations.

Byte streams, Character streams


4.19 Byte Stream in java
 In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.
 In Java 1.0 version all IO operations were byte oriented, there was no other stream (character stream).
 The java byte stream is defined by two abstract classes, InputStream and OutputStream.
 The InputStream class used for byte stream based input operations, and the OutputStream class used for
byte stream based output operations.
 The InputStream and OutputStream classes have several concrete classes to perform various IO
operations based on the byte stream.
The following picture shows the classes used for byte stream operations.

Object Oriented Programming Through Java Page 41


InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.

OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 void write(int n)
It writes byte(contained in an int) to the output stream.
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.

Character Stream in java


 In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream.
 The unicode set is basically a type of character set where each character corresponds to a specific
numeric value within the given character set, and every programming language has a character set.
 The character stream is a 16 bits carrier. The character stream allows us to transmit 16 bits of data.
 The character stream was introduced in Java 1.1 version. The character stream
 The java character stream is defined by two abstract classes, Reader and Writer.
 The Reader class used for character stream based input operations, and the Writer class used for
character stream based output operations.
 The Reader and Writer classes have several concrete classes to perform various IO operations based on
the character stream.

Object Oriented Programming Through Java Page 42


The following picture shows the classes used for character stream operations.

Reader class

The Reader class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 int read()
It reads the next character from the input stream.
2 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed ('\n')
a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
3 boolean ready()
It tells whether the stream is ready to be read.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.

S.No. Method with Description


1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
2 void write(char[] cbuf)

Object Oriented Programming Through Java Page 43


S.No. Method with Description
It writes a whole array(cbuf) to the output stream.
3 void write(int c)
It writes single character.
4 void write(String str)
It writes a string.
5 void write(String str, int off, int len)
It writes a portion of a string.
6 Writer append(char c)
It appends the specified character to the writer.
7 void close()
It closes the output stream and also frees any resources connected with this output stream.

4.20 Java Scanner Class


 Scanner class belongs to java.util package.
 Java Scanner class allows the user to take input from the console(screen).
 It is used to read the input of primitive types like int, double, long, short, float, and byte.
Syntax
Scanner scan = new Scanner(System.in);
 The above statement creates a constructor of the Scanner class having System.in as an argument.
 It means it is going to read from the standard input stream of the program.
 The java.util package should be import while using Scanner class.
Methods of Java Scanner Class

Method Description

int nextInt() It is used to scan the next token of the input as an integer.

float nextFloat() It is used to scan the next token of the input as a float.

double nextDouble() It is used to scan the next token of the input as a double.

byte nextByte() It is used to scan the next token of the input as a byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() It is used to scan the next token of the input into a boolean value.

long nextLong() It is used to scan the next token of the input as a long.

short nextShort() It is used to scan the next token of the input as a Short.

Object Oriented Programming Through Java Page 44


4.21 File class in Java
 The File is a built-in class in Java.
 In java, the File class has been defined in the java.io package.
 The File class represents a reference to a file or directory.
 The File class has various methods to perform operations like creating a file or directory, reading from a
file, updating file content, and deleting a file or directory.
The File class in java has the following constructors.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the given pathname string into an abstract pathname. If the
given string is the empty string, then the result is the empty abstract pathname.
2 File(String parent, String child)
It Creates a new File instance from a parent abstract pathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking the single-argument File constructor on the
given child pathname string.
3 File(File parent, String child)
It creates a new File instance from a parent abstract pathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking the single-argument File constructor on the
given child pathname string.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.

4.21 File Reading & Writing in Java


In java, there are multiple ways to read data from a file and to write data to a file.
The most commonly used ways are as follows.
Using Byte Stream (FileInputStream and FileOutputStream)
Using Character Stream (FileReader and FileWriter)
File Handling using Byte Stream
In java, we can use a byte stream to handle files. The byte stream has the following built-in classes to
perform various operations on a file.
 FileInputStream - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the byte stream. The FileInputStream class provides a method read() to read data
from a file byte by byte.
 FileOutputStream - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the byte stream. The FileOutputStream class provides a method write() to write
data to a file byte by byte.
Example program that reads data from a file and writes the same to another file using FileInoutStream and
FileOutputStream classes.

Object Oriented Programming Through Java Page 45


Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileReadingTest
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("D:\\ACEM\\II AI DS\\Input-File.txt");
out = new FileOutputStream("D:\\ACEM\\II AI DS\\Output-File.txt");
int c;

while ((c = in.read()) != -1)


{
out.write(c);
}
System.out.println(" Reading and Writing has been success ");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Output:
D:\ACEM\II AI DS>javac FileReadingTest.java
D:\ACEM\II AI DS>java FileReadingTest
Reading and Writing has been success
Note: The above program will read data from one file and writes data to another file by creating new file

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream has the following built-in classes to
perform various operations on a file.

Object Oriented Programming Through Java Page 46


 FileReader - It is a built-in class in java that allows reading data from a file.
The FileReader class provides a method read() to read data from a file character by character.
 FileWriter - It is a built-in class in java that allows writing data to a file.
The FileWriter class provides a method write() to write data to a file character by character.
Example that reads data from a file and writes the same to another file using FIleReader and FileWriter classes.
Example

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadingTest1
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try
{
in = new FileReader("D:\\ACEM\\II AI DS\\Input-File1.txt");
out = new FileWriter("D:\\ACEM\\II AI DS\\Output-File1.txt");
int c;

while ((c = in.read()) != -1)


{
out.write(c);
}
System.out.println("Reading and Writing has been success ");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Output: D:\ACEM\II AI DS>javac FileReadingTest1.java
D:\ACEM\II AI DS>java FileReadingTest1
Reading and Writing has been success

Object Oriented Programming Through Java Page 47

You might also like