0% found this document useful (0 votes)
2 views36 pages

Java Exception Handling Explained

This document provides an overview of exception handling and multithreading in Java. It explains the types of exceptions, exception handling techniques using keywords like try, catch, throw, throws, and finally, as well as user-defined exceptions. Additionally, it covers the creation and lifecycle of threads, including methods to create threads and their various states during execution.

Uploaded by

gchennaiah54
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)
2 views36 pages

Java Exception Handling Explained

This document provides an overview of exception handling and multithreading in Java. It explains the types of exceptions, exception handling techniques using keywords like try, catch, throw, throws, and finally, as well as user-defined exceptions. Additionally, it covers the creation and lifecycle of threads, including methods to create threads and their various states during execution.

Uploaded by

gchennaiah54
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

Unit-III

1. Exception:
• Exception is a problem that arises at the time of program execution.
• When an exception occurs, it disrupts the program execution flow.
• When an exception occurs, the program execution gets terminated, and the system
generates an error. We use the exception handling mechanism to avoid abnormal
termination of program execution.

Reasons for Exception Occurrence


Exceptions can arise due to a number of situations. For example,
✓ Trying to access the 11th element of an array when the array contains only 10
elements (ArrayIndexOutOfBoundsException)
✓ Division by zero (ArithmeticException)
✓ Accessing a file which is not present (FileNotFoundException)
✓ Failure of I/O operations (IOException)
✓ Illegal usage of null (NullPointerException)

1.1 Types of Exception


In java, exceptions have categorized into two types, and they are as follows.
Checked Exception - An exception that is checked by the compiler at the time of compilation
is called a checked exception.
Unchecked Exception - An exception that cannot be caught by the compiler but occurs at
the time of program execution is called an unchecked exception.

1
Java programming language has the following class hierarchy to support the exception handling
mechanism.

1.2 EXCEPTION HANDLING TECHNIQUES


In java, the exception handling mechanism uses five keywords namely
try, catch, finally, throw, and throws .

1.2.1 try…catch
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 occurence of an
exception.
The keyword catch is used to define a block of code that handles the exception occurred in
the respective try block..

2
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
cannot use try without at least one catch, and catch alone can be used (catch without try is not
allowed).
Syntax
try
{
...
code to be tested
...
}
catch (ExceptionType object)
{
...
code for handling the exception
...
}

Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 0;
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
catch(ArithmeticException ae)
{
[Link]("Value of divisor can not be ZERO");
}
}
}

when an exception occurs in the try block the execution control transferred to the catch
block and the catch block handles it.

3
1.2.2 Multiple catch clauses
In java programming language, a try block may have one or more number of catch blocks. That
means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae)
{
[Link](" Value of divisor can not be ZERO.");
}

catch(ArrayIndexOutOfBoundsException aie)
{
[Link]("ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e)
{
[Link](" Unknown exception has occured.");
}
}
}

4
1.2.3 throw Keyword
The throw keyword is used to explicitly throw an exception.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only one exception can be thrown. The throw keyword must followed
by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
throw new ThrowableInstance;

Example:

class Test
{
static void check(int age)
{
if(age<18)
throw new ArithmeticException("Not Elgible to Vote");
else
[Link]("Elgible to Vote");
}

public static void main(String args[])


{
check(20);
[Link]("Rest of the Code");
}
}

1.2.4 throws Keyword


The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically, we
use throws keyword followed by method declaration.

throws keyword allows throw an exception from a method. If there is chance of raise any checked
exception, compulsory we have to handle otherwise compile time error we will get.
5
In two ways we can handle this type of exceptions

1. Using try -catch


2. Using throws keyword

throws keyword Syntax:

returntype functionname(args) throws Exceptiontype


{
……
……
}
Example:

import [Link].*;
class throwsException
{
public static void main(String args[]) throws FileNotFoundException
{
FileReader fr=new FileReader(" [Link]");
}
}

throws keyword will not handle the error, it’s convinced the compiler and avoids the
abnormal termination of a program.

1.2.5 finally keyword


The finally keyword used to define a block that must be executed irrespective of exception
occurrence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.

6
Syntax 1:
try
{
...
}
finally
{
....
}

Syntax 2:
try {
...
}
catch(Throwable e)
{
...
}
finally
{
....
}

Example:
class finallyExample
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
[Link]("Divisble by zero");
}
finally
{
[Link]("Finally Block");
}
try
{
[Link]("try Block");
}
finally
{
[Link]("Java Finally Block");

7
}
}
}

1.2.6 Rethrowing Exception


class rethrow
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
throw new NumberFormatException();
}
}
}

1.3 User-Defined Exception


The Java programming language allow us to create our own exception classes which are basically
subclasses built-in class Exception.

To create our own exception class simply create a class as a subclass of built-in Exception class.

We may create constructor in the user-defined exception class and pass a string to Exception class
constructor using super(). We can use getMessage() method to access the string.

8
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z= (float) x/ (float) y;
if(z<0.01)
{
throw new MyException(" Number is too
small");
}
}
catch(MyException e)
{
[Link]("Caught my exception");
[Link]([Link]());
}
}
}

9
Multithreading in java
2.1 Introduction
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a
multithreading program.
Each part of this program is called a thread. Every thread defines a separate path of execution
in java.
A thread is explained in different ways, and a few of them are as specified below.

A thread is a light weight process.

A thread may also be defined as follows.

A thread is a subpart of a process that can run individually.


In java, multiple threads can run at a time, which enables the java to write multitasking
programs.
The multithreading is a specialized form of multitasking. All modern operating systems support
multitasking.
There are two types of multitasking, and they are as follows.

• Process-based multitasking
• Thread-based multitasking

Difference between process-based and thread-based multitasking

Process-based multitasking Thread-based multitasking

It allows the computer to run two or It allows the computer to run two or more
more programs concurrently threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires separate address
Threads share same address space.
space for each.
Process never gain access over idle
Thread gain access over idle time of CPU.
time of CPU.
Inter process communication is Inter thread communication is not
expensive. expensive.

10
2.2 Creating threads in Java
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread.
When a java program gets executed, the main thread created automatically. All other threads
called from the main thread.

The java programming language provides two methods to create threads, and they are listed
below.

• Using Thread class (by extending Thread class)


• Using Runnable interface (by implementing Runnable interface)

2.2.1 Extending Thread class


The java contains a built-in class Thread inside the [Link] package. The Thread class contains all
the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
Step-1 (Declaring a Thread ) : - Create a class as a child of Thread class. That means, create a class that
extends Thread class.
Syntax:
class NewThread extends Thread
{
......
......
......
}
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Syntax:
public void run( )
{
......
//code segment providing the functionality of thread
.....
}
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Syntax:
newThread thread1 = new newThread();
[Link]();

11
Example 1:
class Single extends Thread
{
public void run()
{
[Link]("Sample Thread Program");
}
}
class SampleThread
{
public static void main(String args[])
{
Single s=new Single();
[Link]();
}
}

Example 2:
class SampleThread extends Thread
{
public void run()
{
[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
[Link]("i = " + i);
}
}
}
class MyThread
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}

12
2.2.2 Implementing Runnable interface
The java contains a built-in interface Runnable inside the [Link] package.
The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Syntax:
class NewThread implements Runnable
{
......
......
......
}

Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Syntax:
public void run( )
{
......
//code segment providing the functionality of thread
.....
}

Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.

Example:

class SampleThread implements Runnable


{
public void run()
{
[Link]("Thread is under Running...");

for(int i= 1; i<=10; i++)


{
[Link]("i = " + i);
}
} }
13
class ThreadTest
{
public static void main(String[] args)
{
SampleThread th = new SampleThread();
Thread obj = new Thread(th);
[Link]("Thread about to start...");
[Link]();
}
}

2.3 Thread Lifecycle / Thread States

In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases.

14
2.3.1 New:
In this state, a new thread is created but not started. This state is also known as Born state.

Syntax:
Thread obj = new Thread();

The above statement is responsible for creating a new Thread object At this state , we can do only
one of the following things with it:
• Schedule it for running using start() method
• Kill it using stop() method

2.3.2 Runnable / Ready:

The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.

When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.

[Link]();

4.3.2 Running:

Running means that the processor has given its time to the thread for its execution.

When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.

4.3.3 Not Runnable:


A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.

A thread which is in any of these three states can be assumed to be in ‘not runnable’ state.
These three states are WAITING, TIMED_WAITING, and BLOCKED.

Waiting : In this state, a thread is waiting indefinitely for another thread to perform a particular
action (i.e., notify). Threads can move into this state either by calling the methods
[Link]() (without time out) or [Link]() (without time out).

Timed_Waiting : In this state, the thread is waiting for another thread to perform an action
(notify) up to a specified waiting time. A thread can get into this state by calling
either of these methods: [Link](), [Link](), and
[Link]()
(all these methods should be called with time out specified).
15
Blocked : In this state, a resource cannot be accessed because it is being used by another
thread.A thread can get into this state by calling [Link]() method.

4.3.4 Terminated
A thread in the Running state may move into the dead state due to either its
execution completed or the stop( ) method called. The dead state is also known as the
terminated state.

The Thread class contains the following methods.

Return
Method Description
Value

run( ) Defines actual task of the thread. void

It moves thre thread from Ready state to Running


start( ) void
state by calling run( ) method.

setName(String) Assigns a name to the thread. void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

Returns the reference of the thread that currently in


currentThread( ) void
running state.

moves the thread to blocked state till the specified


sleep( long ) void
number of milliseconds.

isAlive( ) Tests if the thread is alive. Boolean

Tells to the scheduler that the current thread is willing


yield( ) void
to yield its current use of a processor.

join( ) Waits for the thread to end. void

16
Example :

class Sample extends Thread


{
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedException ie)
{

}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]("Id = "+[Link]());
[Link]("Name of the Thread s1 = "+[Link]());
[Link]("Thread One");
[Link]("Name of the Thread after Changing =
"+[Link]());
[Link]("Priority of Thread s1 = "+[Link]());
[Link]("Priority of Thread s2 = "+[Link]());
[Link](6);
[Link]("After Changing Priority of Thread s1 =
"+[Link]());
[Link]();
}
}

17
Example Program on Join Method :
class Sample extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedException ie)
{

}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]();
try
{
[Link]("Thread1 Running");
[Link]();
[Link]("Thread1 Ends");
}
catch(InterruptedException e)
{

}
[Link]("Thread2 Running");
[Link]();
}
}

18
2.4 Thread Priority
In a java programming language, every thread has a property called priority.
Most of the scheduling algorithms use the thread priority to schedule the execution sequence.
In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority,
and priority 10 is considered as the highest priority.
The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.

• MAX_PRIORITY - It has the value 10 and indicates highest priority.


• NORM_PRIORITY - It has the value 5 and indicates normal priority.
• MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔 The default priority of any thread is 5 (i.e. NORM_PRIORITY).

19
2.5 SYNCHRONIZATION
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.

The synchronization is the process of allowing only one thread to access a shared resource at
a time.

Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.

• Synchronized method
• Synchronized block

2.5.1 Synchronized method


When a method created using a synchronized keyword, it allows only one object to access it at
a time.
When an object calls a synchronized method, it put a lock on that method so that other objects
or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.

In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.

20
Syntax for Synchronized Method:
synchronized Methodname()
{
……..
// method Body
}
Example :-

class Display
{
synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n+"*"+i+"="+i*n);
}
}
}
class Mythread extends Thread
{
Display d;
int num;
Mythread(Display d, int num)
{
this.d=d;
[Link]=num;
}
public void run()
{
[Link](num);
}
}

class ThreadSync
{
public static void main(String
args[])
{
Display d=new Display();
Mythread m1=new Mythread(d,5);
Mythread m2=new Mythread(d,10);
[Link]();
[Link]();
}
}
21
2.5.2 Synchronized Block / Statements
The synchronized block is used when we want to synchronize only a specific sequence of lines
in a method.
For example, let's consider a method with 20 lines of code where we want to synchronize only
a sequence of 5 lines code, we use the synchronized block.
Syntax:

public void anyBlock()


{
synchronized (this)
{
......
//statement for the body of block
......
}
}

Example:
class Test
{
public void show()
{
synchronized(this)
{
for(int i=0;i<5;i++)
{
[Link](i);
}
}
for(int i=20;i<25;i++)
{

[Link](i);
}
}
}
class MyThread extends Thread
{
Test T;
MyThread(Test T)
{
this.T=T;
}
public void run()
{
22
[Link]();
}
}
class SyncMethod
{
public static void main(String args[])
{
Test obj=new Test();
MyThread t1=new MyThread(obj);
MyThead t2=new MyThread(obj);
[Link]();
[Link]();
}
}

23
3. Input/Output
3.1 Introduction

The two most important parts of a computer are input and output. Input/output classes form
the core of any programming language.
The [Link] package provides separate classes for reading and writing data (byte and
character data). The java I/O facility is based on streams.
The Stream is defined in the [Link] package.

Stream is a continuous flow of data. Java provides two types of streams, and they are as follows.

• Byte Stream
• Character Stream

Byte stream classes deal with reading and writing of bytes to files, socket, etc.
Character stream classes deal with reading and writing characters to files, socket, etc.
The [Link] package contains two top level byte stream abstract classes :
[Link] (for reading bytes) and [Link] (for writing
bytes).

The [Link] package also contains two other level character stream abstract classes:
[Link] (for reading characters) and [Link] (for writing characters).

24
The

3.2 [Link] CLASS


The File is a built-in class in Java. In java, the File class has been defined in the [Link] 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.


Method Description
String getName() It returns the name of the file or directory that
referenced by the current File object.
String getParent() It returns the pathname of the pathname's parent, or null
if the pathname does not name a parent directory.
String getPath() It returns the path of current File.
File getParentFile() It returns the path of the current file's parent; or null
if it does not exist.
String It returns the current file or directory path from the
getAbsolutePath() root.
boolean isAbsolute() It returns true if the current file is absolute, false
otherwise.
boolean isDirectory() It returns true, if the current file is a directory;
otherwise returns false.
boolean isFile() It returns true, if the current file is a file; otherwise
returns false.
boolean exists() It returns true if the current file or directory exist;
otherwise returns false.
boolean canRead() It returns true if and only if the file specified exists
and can be read by the application; false otherwise.
boolean canWrite() It returns true if and only if the file specified exists
and the application is allowed to write to the file; false
otherwise.
25
long length() It returns the length of the current file.
long lastModified() It returns the time that specifies the file was last
modified.

boolean It returns true if the named file does not exist and was
createNewFile() successfully created; false if the named file already
exists.

boolean delete() It deletes the file or directory. And returns true if and
only if the file or directory is successfully deleted;
false otherwise.

Example Program:

import [Link].*;
class FileDemo
{
public static void main(String args[])
{
File f = new File("D:\\[Link]");
[Link]("Existance : " + [Link]());
[Link]("Read mode : " + [Link]());
[Link]("Write mode : " + [Link]());
[Link]("Executable File : " + [Link]());
[Link]("Name of the file : " + [Link]());
[Link]("Parent name : " + [Link]());
[Link]("path of the File : " + [Link]());
[Link]("Hidden File : " + [Link]());
[Link]("Length of the File : " + [Link]());
[Link]("Last Modified : " + [Link]());
[Link]("It is a File : " + [Link]());
}
}

26
3.3 File Reading & Writing in Java
In java, there 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)

5.3.1 File Handling using Byte Stream


FileInputStream (inherits InputStream) class is used for reading a file .
FileOutputStream (inherits OutputStream) class is used for writing to a file .

The InputStream class has defined as an abstract class, and it has the following methods

Method Description
int available() It returns the number of bytes that can be read
from the input stream.
int read() It reads the next byte from the input stream.
int read(byte[] b) It Reads up to [Link] bytes of data from this
input stream into the byte array b.
int read(byte b[], Reads m bytes into b starting from nth byte
int n, int m)
void close() It closes the input stream and also frees any
resources connected with this input stream.
long skip(long n) Skips over n bytes from the input stream

27
The OutputStream class has defined as an abstract class, and it has the following methods.

Method Description
void write(int n) It writes byte(contained in an int) to the
output stream.
void write(byte[] It writes a whole byte array(b) to the output
b) stream.
void write(byte[] Writes m bytes from array b starting from nth
b, int n, int m) byte
void flush() It flushes the output steam by forcing out
buffered bytes to be written out.
void close() It closes the output stream and also frees any
resources connected with this output stream.

Example program on FileInput and FileOutput Stream class


import [Link].*;
class FileIOStreamEx
{
public static void main(String args[])throws IOException
{
FileOutputStream fout=new FileOutputStream("[Link]");
String s="Welcome to Java io";
//Convert string into byte array
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
FileInputStream fin= new FileInputStream("[Link]");
[Link]("Available bytes in the file: " +[Link]());
[Link](b);
//Convert byte array into string
String data = new String(b);
[Link](data);
[Link]();
}
}

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

• FileReader - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the character stream. 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. This class has
implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.

Example Program on Filehandling using CharacterStream


import [Link].*;
class FilewriterDemo
{
public static void main(String args[])throws IOException
{
FileWriter fw=new FileWriter("[Link]");
FileReader fr=new FileReader("[Link]");
[Link](65);
[Link]("\n");
[Link]("Java Programming");
char ch[]={'a','b','c'};
[Link]("\n");
[Link](ch);
[Link]();
int i=[Link]();
while(i!=-1)
{
[Link]((char)i);
i=[Link]();
}
[Link]();
} }

29
3.4 Scanner Class
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the [Link] package.
Hence to use the Scanner class in your program, you need to import this package as follows.

import [Link].*
OR

import [Link];

The Scanner class provides the easiest way to read input in a Java program.
The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter
is whitespace.
Syntax :-
Scanner scannerObject = new Scanner([Link]);

The Scanner class in java has the following methods.

Method Description
void close() Closes this scanner.
Returns true if this scanner has another
boolean hasNext()
token else false.
Returns true if the next token matches
boolean hasNext(Pattern p)
the specified pattern (p).
Returns true if the next token matches
boolean hasNext(String p)
the pattern in the specified string (p).
Returns true if the next token in this
boolean hasNextBoolean() input can be interpreted as a Boolean
value
Returns true if the next token in this
boolean hasNextByte() input can be interpreted as a byte
value.
Returns true if the next token in this
boolean hasNextDouble() input can be interpreted as a double
value.
Returns true if the next token in this
boolean hasNextFloat()
input can be interpreted as a fl oat.
Returns true if the next token in this
boolean hasNextInt()
input can be interpreted as an int.
Returns true if there is another line
boolean hasNextLine()
in the input.

30
Returns true if the next token in this
boolean hasNextLong() scanner’s input can be interpreted as a
long
Returns true if the next token in this
boolean hasNextShort() scanner’s input can be interpreted as a
short.
Returns the next complete token from
String next()
this scanner.
String next(Pattern Returns the next token if it matches the
pattern) specified pattern.
Scans the next token of the input into
boolean nextBoolean()
a boolean value and returns that value.
Returns the next token of the input as
byte nextByte()
a byte.
Returns the next token of the input as
double nextdouble()
a double.
Returns the next token of the input as
float nextFlot()
a float.
Returns the next token of the input as
short nextInt()
an int
Advances this scanner past the current
short nextLine()
line and returns the input as a string
Returns the next token of the input as
short nextLong()
a long.
Returns the next token of the input as
short nextShort()
a short
Sets the delimiting pattern for scan to
Scanner useDelimiter
pattern constructed from the specified
(String pattern)
string.

Example:-
import [Link].*;
class ScannerInput
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a String");
String str=[Link]();
[Link]("Enter Integer number");
int num=[Link]();
[Link]("Enter Float number");
float real=[Link]();
[Link]("\n------------------------------------------");
[Link]("Entered String is "+ str);

31
[Link]("Entered Integer Number is "+ num);
[Link]("Entered Float Number is "+ real);
}
}

3.5 BufferedOutputStream Class


BufferedOutputStream class is used to buffer the output and enhance the performance.

3.6 BufferedInputStream Class


BufferedInputStream class s used for buffering the input and it supports operations to re-read
the files. It extends the functionality of FileInputStream.
BufferedInputStream class is used to provide buffering to InputStream. Instead of reading
one byte at a time, it can read a large block of data. It improves reading performance.
Methods Description
int available() Returns the number of bytes that can be read from
this input stream without blocking
Void close() Closes this input stream and releases all the
resources.
Void mark(int Similar to mark the methods of InputStream.
readlimit)
boolean markSupported() Tests if this input stream supports the mark and
reset methods.
int read() Similar to read of InputStream class.
int read(byte b[],int Reads bytes from the inputStream into the byte
off, int len) array starting at offset off and returns
the number of bytes read. Len specifi es the
maximum number of bytes to read.
void reset() Similar to reset method of InputStream class.
Long skip(long n) Similar to skip method of InputStream class.

32
Example Program on Buffered Output and Input class :

import [Link].*;
class BufferedIOExample
{
public static void main(String args[])throws IOException
{
FileOutputStream fout=new FileOutputStream("[Link]");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Bufferedoutput Concept";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]();
FileInputStream fin=new FileInputStream("[Link]");
BufferedInputStream bis=new BufferedInputStream(fin);
int size=[Link]();
for(int i=0;i<size;i++)
{
[Link](i);
[Link](i);
[Link]((char)[Link]());
[Link]();
}
[Link]();
[Link]();
}
}

33
3.7 Randomly Accessing A File
In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be accessed
randomly. The RandomAccessFile class has several methods used to move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.

Access Modes
Using the RandomAccessFile, a file may created in the following modes.

• r - Creates the file with read mode; Calling write methods will result in an IOException.
• rw - Creates the file with read and write mode.
• rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
• rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.

Methods Description
void close () Closes this random access fi le stream.
long getFilePointer() Returns the current offset in this fi le.
long length () Returns the length of the fi le.
int read () Reads a byte of data from this fi le.
int read (byte [] b) Reads up to [Link] bytes of data from this fi le into an array
of bytes.
int read(byte[] b, int off, int Reads up to len bytes of data from this fi le into an array of
len) bytes starting at offset off in the byte array.
final boolean readBoolean() Reads a boolean from this fi le.
byte readByte() Reads a signed eight-bit value from this fi le.
final char readChar() Reads a character from this fi le.
final double readDouble() Reads a double from this fi le.
final float readFloat() Reads a float from this fi le.
final int readlnt () Reads a signed 32-bit integer from this fi le.
final String readLine() Reads the next line of the text from this fi le.
final long readLong() Reads a signed 64-bit integer from this fi le.
final short readShort() Reads a signed 16-bit number from this fi le.
void seek(long pos) Sets the fi le-pointer, measured from the beginning of this
file, at which the next read or write operation occurs.

void setLength (long Sets the length of this fi le.


newLength)
int skipBytes(int n) Skips n bytes of input discarding skipped bytes.
final void write (byte [] b) Writes [Link] bytes from the specified byte array to this fi
le, starting at the current fi le pointer.

34
final void write(int b) Writes the specified byte to this fi le.
final void Writes a boolean to the file as a one-byte value.
writeBoolean(boolean v)
final void writeByte(int v) Writes a byte to the fi le as a one-byte value.
final void writeBytes(String s) Writes the string to the fi le as a sequence of bytes.
final void writeChar(int v) Writes char to the fi le as a two-byte value, high byte first.
final void writeChars(String s) Writes string to the fi le as a sequence of characters
final void writelnt(int v) Writes an int to the file as four bytes, high byte first.
final void writeLong(long v) Writes a long to the file as eight bytes, high byte first.
final void writeShort(int v) Writes a short to the file as two bytes, high byte first.

Example Program :
import [Link].*;
class RandomFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile fr=new RandomAccessFile("[Link]","rw");
String s="Welcome to Random Access file";
[Link]([Link]());
[Link](8);
int i=[Link]();
while(i!=-1)
{
[Link]((char)i);
i=[Link]();
}
}
}

35
Unit-III Questions
1. Explain Exception Handling in detail.
2. Explain thread in detail./ Mutithreading
3. Thread life cycle
4. Exception and Exception handling Techniques
5. Explain about user defined exception
6. Thread priorities
7. [Link] package / streams
8. Scanner class and Randomaccessfile
9. Synchronization

36

You might also like