You are on page 1of 45

UNIT - III Exception handling, Stream based I/O (java.

io)
Exception handling - Fundamentals, Exception types, Uncaught exceptions, using try and
catch, multiple catch clauses, nested try statements, throw, throws and finally, built-in
exceptions, creating own exception subclasses.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and Writing Files, Random
access file operations, The Console class, Serialization, Enumerations, Autoboxing, Generics.

Exception handling:

An exception is an unexpected event that occurs during program execution. It affects the flow
of the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5; //exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.
Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle
errors.
Exceptions
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.
RuntimeException
A runtime exception happens due to a programming error. They are also known
as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
 Improper use of an API - IllegalArgumentException
 Null pointer access (missing the initialization of a variable) - NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException
 We can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if we had checked whether the variable
was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if we tested the array index
against the array bounds.
IOException
An IOException is also known as a checked exception. They are checked by the compiler at
the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
 Trying to open a file that doesn’t exist results in FileNotFoundException
 Trying to read past the end of a file
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keywor Description
d
Try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
Finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
Throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

without try catch blocks:

public class JavaExceptionExample {


public static void main(String args[]) {

// code that may raise exception


int data = 100 / 0;

// rest code of the program


System.out.println("rest of the code...");
}
}
Output:
E:\>javac JavaExceptionExample.java

E:\>java JavaExceptionExample
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaExceptionExample.main(JavaExceptionExample.java:5)

Methods to print the Exception information:

1. printStackTrace()– This method prints exception information in the format of Name


of the exception: description of the exception, stack trace.
Example:
int a=5,b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace(); }
Output:
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)

2. toString() – This method prints exception information in the format of Name of the
exception: description of the exception.
Example:
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}

Output:
java.lang.ArithmeticException: / by zero

3. getMessage() -This method prints only the description of the exception

try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
Output:
/ by zero

Using try and catch:

Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
JavaExceptionExample.java
Output:
E:\>javac JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){ E:\>java JavaExceptionExample
try{ java.lang.ArithmeticException: / by zero
//code that may raise exception rest of the code...
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Multiple catch clauses:

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if we have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

public class MultipleCatchBlock1 {

public static void main(String[] args) { Output:


E:\>javac MultipleCatchBlock1.java
E:\>java MultipleCatchBlock1
try { Arithmetic Exception occurs
int a[] = new int[5]; rest of the code
int b = 30 / 0;
a[5] = 10;
} 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");
}
}
Nested try statements:

In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

public class NestedTryBlock {


public static void main(String args[]) {
// outer try block
try {
// inner try block 1
try {
System.out.println("going to divide by 0");
int b = 39 / 0;
}
// catch block of inner try block 1
catch (ArithmeticException e) {
System.out.println(e);
}

// inner try block 2


try {
int a[] = new int[5];
// assigning the value out of array bounds
a[5] = 4;
}
// catch block of inner try block 2
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

System.out.println("other statement");
}
// catch block of outer try block
catch (Exception e) {
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:
E:\>javac NestedTryBlock.java
E:\>java NestedTryBlock
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..

Throw statement:

The Java throw keyword is used to throw an exception explicitly.


We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
Syntax:
throw throwableObject;
Example:
throw new ArithmeticException("/ by zero");

program:
//user defined exception
class Eligible extends Exception {
String str;

Eligible(String s) {
str = s;
}
public String toString() {
return ("user defined Exception is " + str);
}
public static void main(String[] args)throws Eligible {
int age = 15;
try {
if (age < 18) {
throw new Eligible("not eligible for vote");
} else {
System.out.println("eligible for vote");
}
} catch (Eligible e) {
Output:
System.out.println(e); E:\>javac Eligible.java
} E:\>java Eligible
finally user defined Exception is not eligible for
{ vote
System.out.println("Finally block"); Finally block
rest of code
}
System.out.println("rest of code");
}
}

throws and finally:

throws is a keyword in Java which is used in the signature of method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.

Syntax:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 …
{
// code
}
exception_list is a comma separated list of all the
exceptions which a method might throw.
Example:
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………

// code that may produce IOException


………
// code that may produce InvalidClassException
………
}
Example:

class DemoExcep implements Cloneable {


void method() {
System.out.println("simple method");
}
public static void main(String args[]) throws CloneNotSupportedException {
DemoExcep d = new DemoExcep();
DemoExcep d1 = (DemoExcep) d.clone(); Output:
System.out.println(d1); E:\>javac DemoExcep.java
d1.method(); E:\>java DemoExcep
} DemoExcep@36baf30c
} simple method

Finally block:

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

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs
or not.

Example:
public class TestFinallyBlock1{
public static void main(String args[]){

try {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

E:\>javac TestFinallyBlock.java
E:\>java TestFinallyBlock
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock.main(TestFinallyBlock.java:9)
List of checked exceptions in Java
The following table shows the list of several checked exceptions.
S.
No. Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and
the specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers
do not allow.

4 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be
instantiated because it is an interface or is an abstract class.

5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.

7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.
S.
No. Exception Class with Description

1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
S.
No. Exception Class with Description

2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The
index is either negative or greater than or equal to the size of the array.

3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type
of object into an array of objects

4 AssertionError
It is used to indicate that an assertion has failed

5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to
another.

6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal
or inappropriate argument.

7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or
has attempted to notify other threads that wait on an object's monitor, without
owning the specified monitor.

8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.

9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to
modify the state of the thread when it is illegal.

10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as
an array , vector , string , and so forth.

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

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException
S.
No. Exception Class with Description

It is thrown when we try to convert a string into a numeric value such as float or
integer, but the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is
either negative, or greater than the size of the string itself.

16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

creating own exception subclasses

Sometimes it is required to develop meaningful exceptions based on the application


requirements. We can create our own exceptions by extending Exception class in Java

class MyException extends Exception


{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
class CustomException
{
public static void main(String args[])
{
try
{
throw new MyException("Custom");
// I'm throwing user defined custom exception above
}
catch(MyException exp)
{
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
}
Output:
D:\java\jpgms\labpgms>javac CustomException.java
D:\java\jpgms\labpgms>java CustomException
Hi this is my catch block
Output String = Custom

Differences between throw and throw keywords:

Sr. Key throw Throws


No.
Definition Throw is a keyword which is Throws is a keyword used in the
used to throw an exception method signature used to declare
1 explicitly in the program an exception which might get
inside a function or inside a thrown by the function while
block of code. executing the code.
Internal Internally throw is On other hand we can declare
implementation implemented as it is allowed multiple exceptions with throws
to throw only single keyword that could get thrown by
2 exception at a time i.e we the function where throws
cannot throw multiple keyword is used.
exception with throw
keyword.
Type of With throw keyword we can On other hand with throws
exception propagate only unchecked keyword both checked and
exception i.e checked unchecked exceptions can be
3 exception cannot be declared and for the propagation
propagated using throw. checked exception must use
throws keyword followed by
specific exception class name.
Syntax Syntax wise throw keyword On other hand syntax wise throws
4 is followed by the instance keyword is followed by exception
variable. class names.
5 Declaration In order to use throw On other hand throws keyword is
Sr. Key throw Throws
No.
keyword we should know used with the method signature.
that throw keyword is used
within the method.

Stream based I/O

The Stream:
A stream is a sequence of data. Streams facilitate translating data from one place to another.
Different streams are needed to send and receive data through different sources, such as to
receive data from keyboard, we need a stream and to send data to a file, we need another
stream. Without streams it is not possible to move data in java.

Java Standard Streams


As we know, all Java programs automatically import the java.lang package. This package
defines a class called System, which encapsulates several aspects of the run-time
environment.

 System class also contains three predefined stream variables, in, out, and err. These
fields are declared as public and static within System.
 System.out refers to the standard output stream. By default, this is the console.
 System.in refers to standard input, which is the keyboard by default.
 System.err refers to the standard error stream, which also is the console by default.
 System.in is an object of type InputStream;
 System.out and System.err are objects of type PrintStream.

 Standard Input: Accessed through in which is used to read input from the keyboard.
 Standard Output: Accessed through out which is used to write output to the display
(console).
 Standard Error: Accessed through err which is used to write error output to the
display (console).
There are two brands of Stream in Java Programming Language:

1. Input Stream:
The Input Stream provides the functionality of taking the Input from a Source. The Input
Stream provides the set of Objects and pipelines together to provide us the functionality of
Input the collection in I/O File.

2. Output Stream:
The Output Stream provides the functionality of writing the data to the Destination. The
Output Stream provides the set of Objects and pipelines together to provide us the
functionality of Output to the collection in I/O File.
Fig: Flow of data in standard Input-Output streams and file streams

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.

1. Byte Stream Classes that provide support for handling I/O operations on bytes.
2. Character Stream Classes that provide support for managing I/O operations
on characters.
These two groups may further be classified based on their purpose. Figure 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.

1. Byte Stream Classes


 Java byte streams are used to perform input and output of 8-bit bytes.
 Byte streams are defined by using two class hierarchies.
 At the top there are two abstract
classes: java.io.InputStream and java.io.OutputStream.
 Each of these abstract classes has several concrete subclasses of each of these.
 The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement.
 Two of the most important are read() and write(), which, respectively, read and write
bytes of data.
 Both methods are declared as abstract inside InputStream and OutputStream.
 They are overridden by derived stream classes.
InputStream Classes
The InputStream class is used for reading the data such as a byte and array of bytes from an
input source. An input source can be a file, a string, or memory that may contain the data. It is
an abstract class that defines the programming interface for all input streams that are inherited
from it. An input stream is automatically opened when we create it. We cans explicitly close a
stream with the close() method, or let it be closed implicitly when the object is found as a
garbage.

The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown
below:

Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses. Here
are some of the commonly used methods:
 read() - reads one byte of data from the input stream
 read(byte[] array) - reads bytes from the stream and stores in the specified array
 available() - returns the number of bytes available in the input stream
 mark() - marks the position in the input stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark was set
 markSupported() - checks if the mark() and reset() method is supported in the stream
 skips() - skips and discards the specified number of bytes from the input stream
 close() - closes the input stream

OutputStream Classes
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when we create it. We can explicitly close an output stream with
the close() method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:

Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses.
Here are some of the methods:
 write() - writes the specified byte to the output stream
 write(byte[] array) - writes the bytes from the specified array to the output stream
 flush() - forces to write all data present in output stream to the destination
 close() - closes the output stream
2. Character Stream Classes
Java offers another type of streams called Character Streams, which are used to read from the
input device and write to the output device in units of 16-bit (Unicode) characters. In some
cases, character streams are more efficient than byte streams. The oldest version of Java (Java
1.0) did not include character streams and, thus, all I/O was byte-oriented. Character streams
were added by Java 1.1, and certain byte-oriented classes and methods were deprecated.
Character streams are defined by using two class hierarchies. At the top there are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character (16-bit)
streams. Java has several concrete subclasses of each of these. The abstract
classes Reader and Writer define several key methods that the other stream classes implement.
Two of the most important methods are read() and write(), which read and write characters of
data, respectively. These methods are overridden by derived stream classes.

2.1 Reader Stream Classes


The Reader class contains methods that are identical to those available in
the InputStream class, except Reader is designed to handle characters. Therefore, Reader
classes can perform all the functions implemented by the InputStream classes. The hierarchy
of Reader character stream classes is shown below:

Modifier and Method Description


Type

abstract void close() It closes the stream and releases any system resources
associated with it.
void mark(int readAheadLimit) It marks the present position in the stream.

Boolean markSupported() It tells whether this stream supports the mark() operation.

int read() It reads a single character.

int read(char[] cbuf) It reads characters into an array.

abstract int read(char[] cbuf, int off, int It reads characters into a portion of an array.
len)

int read(CharBuffer target) It attempts to read characters into the specified character
buffer.

Boolean ready() It tells whether this stream is ready to be read.

void reset() It resets the stream.

2.2 Writer Stream Classes


The Writer class contains methods that are identical to those available in
the OutputStream class, except Writer is designed to handle characters. Therefore, Writer
classes can perform all the functions implemented by the OutputStream classes. The hierarchy
of Writer character stream classes is shown below
Methods
Modifier and Method Description
Type

Writer append(char c) It appends the specified character to this writer.

Writer append(CharSequence csq) It appends the specified character sequence to this


writer

Writer append(CharSequence csq, int start, It appends a subsequence of the specified character
int end) sequence to this writer.

abstract void close() It closes the stream, flushing it first.

abstract void flush() It flushes the stream.

void write(char[] cbuf) It writes an array of characters.

abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.

void write(int c) It writes a single character.

void write(String str) It writes a string.

void write(String str, int off, int len) It writes a portion of a string.

Reading console Input:

Java provides different ways to take input and provide output on the console.

There are three ways to take input from console in Java

1. Using Java BufferedReader class


2. Through Java Scanner class
3. Using Java Console class
1. Using BufferedReader class:
Using BufferedReader class is the classical method of taking input from the console. Java has
introduced this technique since Java 1. The BufferedClass reads data line by line through the
readLine() method. This class wraps the System.in with an InputStreamReader.

We use the object of Bufferedredaer class to take input from the keyboard

To use these classes, we need to use the java.io package. Let’s see an example to understand
this method of reading input from the console.

Example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
//Taking the input data using the BufferedReader class
BufferedReader br= new BufferedReader(input);

// Reading data using readLine


System.out.println("Please enter the input:");
String name = br.readLine();

System.out.println("Please enter the integer input:");


int num=Integer.parseInt(br.readLine());
Output:
// Printing the read line E:\pgms>javac BufferedReaderDemo.java
System.out.println("You entered: "); E:\pgms>java BufferedReaderDemo
Please enter the input:
System.out.println(name); shyam
System.out.println(num); Please enter the integer input:
} 1000
} You entered:
shyam
1000
Note: The method readLine() is used to take the String input from the user. If you want to read
the other types, we can use the methods like

 Integer.parseInt(): to read int values


 Double.parseDouble(): to read double values
 Float.parseFloat(): to read float values
To read multiple values, we use the split() method.
2. Using Scanner class
It is probably the best choice of taking console input from the user. This class reads the input
from the user in the console or the command line.

The other use of Scanner class is to parse the strings and primitive types with the help of java
regular expressions.

The Scanner class is present in the java.util package. This class obtains the input from
System.in (standard input stream).

Syntax of using Scanner class:

Scanner sc = new Scanner(System.in);

Advantages
 The Scanner class provides useful methods like nextInt(), nextDouble(), nextFloat(), etc,
for parsing primitive data types.
 The Scanner class uses regular expressions and we can use these regular expressions to find
tokens.
Drawback
 The methods of Scanner class for reading values are not synchronized

Methods:
To read the values of various data types, the Scanner class provides several methods. The
following table shows these methods:
Method Description
nextBoolean() This method reads a boolean value from the user

nextByte() This method reads a byte value from the user


nextDouble() This method reads a double value from the user
nextFloat() This method reads a float value from the user
nextInt() This method reads an int value from the user

nextLine() This method reads a String value from the user

nextLong() This method reads a long value from the user

nextShort() This method reads a short value from the user


Example:

import java.util.Scanner;
public class ScannerClassDemo
{
// Java program to understand the use of Scanner in Java
public static void main(String args[]) Output:
{ E:\pgms>javac ScannerClassDemo.java
// Using Scanner for Getting Input from User E:\pgms>java ScannerClassDemo
Scanner sc = new Scanner(System.in); Enter a string
ram
System.out.println("Enter a string"); You entered string: ram
Enter a number
String string = sc.nextLine(); 1001
System.out.println("You entered string: " +string); You entered integer: 1001
Enter a float number
System.out.println("Enter a number"); 78.9076
int num = sc.nextInt(); You entered float: 78.9076
System.out.println("You entered integer: " +num);

System.out.println("Enter a float number");


float fnum = sc.nextFloat();
System.out.println("You entered float: " +fnum);
}
}
3. Using the Java Console class
The Java Console class is the third technique to take input from the user through the console.
The Console class was introduced since Java 1.5. This class is present in the java.io package.

we use the Console class, the JVM associated system console isn't available if we run the code
within an IDE such as Eclipse or IntelliJ IDEA.

There are several methods in Console class that help in reading input texts and passwords
from the console, without displaying it on the screen.
Methods of Java Console class
Method Description

String readLine() This method reads a single line of text from the console.

char[] readPassword() It is used to read a password that is visible on the console screen.

Advantages
 Reading password without displaying the characters of the password on the console.
 Reading methods of the console class are synchronized.
 We can also use the format string syntax with the Console class
Drawback
 It does not work in a non-interactive environment (such as in an IDE).
Example:

import java.io.*;
Output:
E:\pgms>javac ConsoleDemo.java
public class ConsoleDemo { E:\pgms>java ConsoleDemo
public static void main(String[] args) Enter username : satya
{ Username : satya
// Create the console object Enter password :
Password : [C@3b9a45b3
Console cnsl= System.console();

if (cnsl == null) {
System.out.println("No console available");
return;
}

// Read line
String str = cnsl.readLine("Enter username : ");

// Print username
System.out.println("Username : " + str);

// Read password into character array


char[] ch = cnsl.readPassword("Enter password : ");

// Print password
System.out.println("Password : " + ch);
}
}
Writing console output in java
In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.

 Using print() and println() methods


 Using write() method

1. Writing console output using print() and println() methods


The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.
 Both print() and println() methods are used with System.out stream.
 The print() method writes console output in the same line. This method can be used
with console output only.
 The println() method writes console output in a separete line (new line). This method
can be used with console and also with other output sources.

2. Writing console output using write() method


Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also accept escape sequences.
Output:
Example: E:\pgms>javac JavaPrintStreamWriteExample.java
E:\pgms>java JavaPrintStreamWriteExample
public class JavaPrintStreamWriteExample { vedha
public static void main(String[] args) { Successfully printed byte array to this stream.
//out is the object class PrintStream.
byte[] b= {118,101,100,104,97};
System.out.write(b,0,5);
System.out.print("\nSuccessfully printed byte array to this stream.");
}
}

File class:
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.
S.No. Constructor with Description

1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe 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 abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking
thesingle-argument File constructor on the given child pathname string.

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking
thesingle-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.

The File class in java has the following methods.


Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
Example:

// In this Java program, we accepts a file or directory name from


// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.

import java.io.File;

// Displaying file property


class fileProperty {
public static void main(String[] args)
{

// accept file name or directory name through


// command line args
String fname = args[0];

// pass the filename or directory name to File


// object
File f = new File(fname);

// apply File class methods on File object


System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:" + f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists()); Output:
E:\pgms>javac fileProperty.java
E:\pgms>java fileProperty myFile.txt
if (f.exists()) { File name :myFile.txt
System.out.println("Is writable:"+ f.canWrite()); Path: myFile.txt
System.out.println("Is readable" + f.canRead()); Absolute path:E:\pgms\myFile.txt
System.out.println("Is a directory:" + f.isDirectory()); Parent:null
System.out.println("File Size in bytes " + f.length()); Exists :true
Is writable:true
}
Is readabletrue
} Is a directory:false
} File Size in bytes 755

FileWriter Class:
Java FileWriter class of java.io package is used to write data in character form to file.
Java FileWriter class is used to write character-oriented data to a file. This class
extends OutputStreamWriter. This class provides methods to write strings directly so we don't
need to convert string to a byte array.
o FileWriter is meant for writing streams of characters. For writing streams of raw
bytes, consider using a FileOutputStream.
o FileWriter creates the output file if it is not present already.

Hierarchy of Java FileWriter Class:

FileWriter extends OutputStreamWriter and Writer classes. It implements Closeable,


Flushable, Appendable, AutoCloseable interfaces.

Constructors of FileWriter Class


Constructor Description
FileWriter(String
This constructor creates a new file. It gets the file name in a string.
file)
This constructor creates a new file. It gets the file name in the File
FileWriter(File file)
object.

Methods of FileWriter Class


All the methods supported by FileWrite Class are mentioned in the table below.

Method Description
void write(String text) This method is used to write the string into FileWriter.

void write(char c) This method is used to write the char into FileWriter.

void write(char[] c) Thi method is used to write char array into FileWriter.

void flush() This method is used to flushes the data of FileWriter.


void close() This method is used to close the FileWriter.
Example:
import java.io.FileWriter;

public class FileWriterDemo {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {
// Creates a FileWriter
FileWriter output = new FileWriter("output.txt");

// Writes the string to the file


output.write(data);
System.out.println("Data written to the file is successfully...");

// Closes the writer Output:


output.close(); E:\pgms> javac FileWriterDemo.java
} E:\pgms>java FileWriterDemo
catch (Exception e) { Data written to the file is successfully...
e.getStackTrace();
}
}
}

FileReader class:
The FileReader class of the java.io package can be used to read data (in characters) from files.
It extends the InputSreamReader class.

Create a FileReader
In order to create a file reader, we must import the java.io.FileReader package first. Once we
import the package, here is how we can create the file reader.
1. Using the name of the file
FileReader input = new FileReader(String name);
Here, we have created a file reader that will be linked to the file specified by the name.
2. Using an object of the file
FileReader input = new FileReader(File fileObj);
Here, we have created a file reader that will be linked to the file specified by the object of the
file.
Methods of FileReader
The FileReader class provides implementations for different methods present in
the Reader class.
read() Method
 read() - reads a single character from the reader
 read(char[] array) - reads the characters from the reader and stores in the specified array
 read(char[] array, int start, int length) - reads the number of characters equal to length from
the reader and stores in the specified array starting from the position start

For example:
we have a file named input.txt with the following content.
This is a line of text inside the file.
Let's try to read the file using FileReader.

import java.io.FileReader;

class Main {
public static void main(String[] args) {

// Creates an array of character


char[] array = new char[100];

try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");

// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array); Output
Data in the file:
This is a line of text inside the file.
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

In the above example, we have created a file reader named input. The file reader is linked with
the file input.txt.
FileInputStream input = new FileInputStream("input.txt");
To read data from the file, we have used the read() method.
Note: The file input.txt should be present in the current working directory.

RandomAccessFile:

This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number
of byte has been read than EOFException is thrown. It is a type of IOException.

Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and


file, String mode) optionally to write to, the file specified by the File
argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.

Access Modes
Using the RandomAccessFile, a file may created in th 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.
Method:

Modifier Method Method


and Type

void close() It closes this random access file stream and releases any system
resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.


void seek(long It sets the file-pointer offset, measured from the beginning of this
pos) file, at which the next read or write occurs.
void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

Example:
import java.io.RandomAccessFile;
import java.io.*;
class RaFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile rf=null;
try{
rf=new RandomAccessFile("output.txt","rw");

rf.seek(34);
Output:
rf.writeUTF("Hyderabad"); E:\>javac RaFile.java
rf.seek(10); E:\>java RaFile
int b; file to display capital
while((b=rf.read())!= -1) Hyderabad,,amaravathi
{
System.out.print((char)b);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(rf != null)
{
rf.close();
}
}
}
}

Java Enum:
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, we should always represent
them in UPPERCASE letters.

You can use an Enum type when we need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.

The following characteristics make enum a ‘special’ class:

 enum constants cannot be overridden


 enum doesn’t support the creation of objects
 enum can’t extend other classes because it is internally extends fromEnum class
 enum can implement interfaces like classes.
Example:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest {
Day day;

public EnumTest(Day day) {


this.day = day;
}

public void tellItLikeItIs() {


switch (day) {
case MONDAY:
case TUESDAY: Output:
case WEDNESDAY: E:\>javac EnumTest.java
case THURSDAY:
E:\>java EnumTest
case FRIDAY:
WEEK DAYS
System.out.println("WEEK DAYS"); Weekends are best.
break;

case SATURDAY: case SUNDAY:


System.out.println("Weekends are best.");
break;

default:
System.out.println(" WORNG WEEK NAME");
break;
}
}

public static void main(String[] args) {


EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();

}
}
Serialization:
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.

The byte stream created is platform independent. So, the object serialized on one platform
can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.

public final void writeObject(Object obj)throws IOException


The ObjectInputStream class contains readObject() method for deserializing an object.

public final Object readObject()throws IOException,ClassNotFoundException


Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.

// Java code for serialization and deserialization


// of a Java object
import java.io.*;
class Student implements java.io.Serializable
{
public int a;
public String b;

// Default constructor
public Student(int a, String b)
{
this.a = a;
this.b = b;
}
}
class Test
{
public static void main(String[] args)
{
Student object = new Student(1001, "ram");
String filename = "file.ser";

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object


out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Student object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Student)in.readObject();

in.close();
file.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
Output:
}
E:\>java Test
catch(IOException ex) Object has been serialized
{ Object has been deserialized
System.out.println("IOException is caught"); a = 1001
} b = ram

catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}

}
}

Autoboxing and Unboxing:


The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java
programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:

 No need of conversion between primitives and Wrappers manually so less coding is


required.
Primitive Type Wrapper Class
boolean Boolean
Byte Byte
Char Character
float Float
int Integer
Long Long
short Short
Double Double

Example:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Output:
Integer a2=new Integer(a);//Boxing
Integer a3=5; //Boxing 50 5

System.out.println(a2+" "+a3);
}
}

Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing. Let's see the example of unboxing:

class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a); 50
}}
Generics in Java:

Generics means parameterized types. The idea is to allow type (Integer, String, … etc.,
and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types.

Note: Generics does not work with primitive types (int, float, char, etc).

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

3) Compile-Time Checking: It is checked at compile time so problem will not occur at


runtime. The good programming strategy says it is far better to handle the problem at compile
time than runtime.
Java Generics Class
We can create a class that can be used with any type of data. Such a class is known as
Generics Class.

Example: Create a Generics Class


class Main {
public static void main(String[] args) {

// initialize generic class


// with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());

// initialize generic class


// with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}
// create a generics class
class GenericsClass<T> {
// variable of T type
private T data;

public GenericsClass(T data) {


this.data = data;
}

// method that return T type variable


public T getData() {
return this.data;
}
}
Output:
E:\>javac GenericsDemo.java

E:\>java GenericsDemo
Generic Class returns: 5
Generic Class returns: Java Programming
Java StringBuffer Class:

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Modifier and Method Description


Type
public append(String s) It is used to append the specified string with this
synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.
public insert(int offset, String It is used to insert the specified string with this
synchronized s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int startIndex, It is used to replace the string from specified
synchronized int endIndex, String str) startIndex and endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified
synchronized endIndex) startIndex and endIndex.
StringBuffer
public reverse() is used to reverse the string.
synchronized
StringBuffer
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int It is used to ensure the capacity at least equal to
minimumCapacity) the given minimum.
public char charAt(int index) It is used to return the character at the specified
position.
public int length() It is used to return the length of the string i.e.
total number of characters.
public String substring(int It is used to return the substring from the
beginIndex) specified beginIndex.
public String substring(int It is used to return the substring from the
beginIndex, int specified beginIndex and endIndex.
endIndex)

Example:
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hellojava

StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH

StringBuilder class:
StringBuilder class has been added in JDK1.5 which has same features like StringBuffer class.
StringBuilder class objects are also mutable as the stringBuffer Objects.
Difference:
StringBuffer is class is synchronized and StringBuilder is not.

You might also like