0% found this document useful (0 votes)
6 views

Java Unit-5 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Unit-5 Final

Uploaded by

rajfelix1969
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

JAVA PROGRAMMING – UNIT V

MANAGING ERRORS AND EXCEPTIONS:


 An error may produce an incorrect output or may terminate the
execution of the program.
 It is important to detect and manage properly all the possible error
conditions in the program.

TYPES OF ERRORS:
 Errors may broadly be classified into two categories:
 Compile-time errors
 Run-time errors
 Compile-time Errors:
 All syntax errors will be detected and displayed by the java compiler
and therefore these errors are known as compile time errors.
 The most common problems are:
 Missing semicolons
 Typing mistakes
 Missing brackets
 Misspelling of identifiers and keyboards
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments

For example,
class errorpgm
{
public static void main(String args[ ])
{
System.out.println(“Hello Java!”) // Missing ;
}
}
 Run-time Errors:
 A program may compile successfully creating the .class file but may
not run properly which is known as run-time errors.
 The most common problems are:
 Dividing an integer by zero
 Accessing an element ie., out of bounds of an array
 Using negative size for an array
 Convert string into integer
 Passing parameter in illegal form
 Accessing null object

Page 1 of 25
JAVA PROGRAMMING – UNIT V

For example,
class errorpgm
{
public static void main(String args[ ])
{
int a=10, b=5, c=5;
int x=a/(b-c); // Division by zero
System.out.println(“x = “+x);
}
}

EXCEPTIONS:
 An exception is a condition that is caused by a run-time error in the
program.
 For example, an error is dividing an integer by zero, it creates an
exception object and throws it.
 Exception handling is to catch the exception object thrown by the error
condition and then display an appropriate message for taking corrective
actions.
 Exception handling mechanism providing to detect and report an
“exceptional circumstance” so that appropriate action can be taken.
It performs the following actions:
 Find the problem (Hit the exception)
 Inform an error occurred (Throw the exception)
 Receive the error information (Catch the exception)
 Take corrective actions (Handle the exception)
 The error handling code consists two segments:
1. To detect errors and to throw exceptions.
2. To detect errors and to catch exceptions and take actions.
 Some common exceptions are:

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
FileNotFoundException Caused by an attempt to access a non-existent file.
Caused by general input/output failures, such as
IOException
inability to read from a file.
NullPointerException Caused by referencing a null object.
Caused when a conversion between strings and
NumberFormatException
number fails.
OutOfMemoryException Caused when there’s not enough memory to allocate

Page 2 of 25
JAVA PROGRAMMING – UNIT V

a new object.
SYNTAX OF EXCEPTION HANDLING CODE:
 The basic concepts of exception handling are throwing an exception
and catching it.
try Block
Statement that causes Exception object
an exception creator
Throws Exception
object

catch Block
Statement that Exception
handles an exception handler

Exception handling mechanism


 Java uses try to preface a block of code to cause an error condition and
“throw” an exception.
 catch block defines to catches the exception “thrown” by the try block and
handles it appropriately.
Syntax:
try
{
Statement; //generates an exception
}
catch (Exception-type e)
{
Statement; //processes the exception
}
For example,
class errorpgm
{
public static void main(String args[ ])
{
int a=10, b=5, c=5;
int x, y;
try
{
x=a/(b-c); // Exception here
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
y=a/(b+c);
System.out.println(“y = “+y);
}

Page 3 of 25
JAVA PROGRAMMING – UNIT V

}
It will display,
Division by Zero
y=1

Multiple CATCH Statements:


 It is possible to have more than one catch statement.

Syntax:
try
{
Statement; //generates an exception
}
catch (Exception-type-1 e)
{
Statement; //processes the exception type-1
}
catch (Exception-type-2 e)
{
Statement; //processes the exception type-2
}
.
.
catch (Exception-type-N e)
{
Statement; //processes the exception type-N
}

For example,
class errorpgm
{
public static void main(String args[ ])
{
int a[ ]={5, 10};
int b=5;
try
{
int x=a[2]/b-a[1]; // Exception here
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{

Page 4 of 25
JAVA PROGRAMMING – UNIT V

System.out.println(“Array Index Error”);


}
catch (ArrayStoreException e)
{
System.out.println(“Wrong Data Type”);
}
int y=a[1]/a[0];
System.out.println(“y = “+y);
}
}

It will display,
Array Index Error
y=2

USING finally STATEMENT:


 finally statement can be used to handle an exception that is not caught by
any of the previous catch statements.
 finally block can be used to handle any exception generated within a try
block.

Syntax:
try
{
Statement; //generates an exception
}
catch (Exception-type-1 e)
{
Statement; //processes the exception type-1
}
catch (Exception-type-2 e)
{
Statement; //processes the exception type-2
}
.
.
finally
{
Statement;
}

Page 5 of 25
JAVA PROGRAMMING – UNIT V

For example,
class errorpgm
{
public static void main(String args[ ])
{
int a[ ]={5, 10};
int b=5;
try
{
int x=a[2]/b-a[1]; // Exception here
}
catch (ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index Error”);
}
catch (ArrayStoreException e)
{
System.out.println(“Wrong Data Type”);
}
finally
{
int y=a[1]/a[0];
System.out.println(“y = “+y);
}
}
}

It will display,
Array Index Error
y=2

THROWING OWN EXCEPTIONS:


 It is used to throw our own exceptions.

Syntax:
throw new throwable_subclass;

Example:
throw new ArithmeticException( );
throw new NumberFormatException( );

Page 6 of 25
JAVA PROGRAMMING – UNIT V

Sample Program:

import java.lang.Exception;
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)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage( ));
}
finally
{
System.out.println(“I am always here”);
}
}
}

It will display,
Caught my exception
Number is too small
I am always here

Page 7 of 25
JAVA PROGRAMMING – UNIT V

APPLET PROGRAMMING:
 Applets are small java programs used in Internet computing.
 Applet runs using Applet Viewer that supports Java.
 It performs arithmetic operations, display graphics, play sounds, create
animation, play games.

LOCAL AND REMOTE APPLETS:


 We can embed applets into Web pages in two ways.
1. Write our own applets.
2. Download an applet from a remote computer system.
 There are two types of Applets. They are,
1. Local Applet
2. Remote Applet
1. Local Applet:
 Applet developed and stored in local system.
 Does not require Internet connection.

Local Applet

Local Computer
2. Remote Applet:
 Applet developed by someone else and stored on remote computer
 Connected to Internet
 Uniform Resource Locator (URL) is used to locate and load a remote
applet, the applet’s address on the Web.

Internet

Local Computer Remote Computer


Remote Applet
(Client) (Server)
Page 8 of 25
JAVA PROGRAMMING – UNIT V

BUILDING APPLET CODE:


 Applet code uses the services of two classes.
1. Applet
2. Graphics
1. Applet Class:
 Applet class is contained in the java.applet package.
 It provides life and behaviour to the applet through its methods.
a. init( )
b. start( )
c. paint( )
 Java automatically calls a series of Applet class methods for starting,
running and stopping the applet code.
2. Graphics Class:
 Graphics class is contained in the java.awt package.
 The paint( ) method of the Applet class which is display the result of
the applet code on the screen.
 The output may be text, graphics, or sound.
 The paint( ) method, which requires a Graphics object as an argument,
is defined as
public void paint(Graphics g)

For example,

import java.awt.*;
import java.applet.*;
public class hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to Java”, 10,100);
}
}

It will display,
Welcome to Java

APPLET LIFE CYCLE:


The applet states include:
 Born or initialization state
 Running state
 Idle state
 Dead or destroyed state

Page 9 of 25
JAVA PROGRAMMING – UNIT V

Begin Born Initialization


(Load Applet)

start( ) stop( )

Running Idle Stopped


Display

start( )
paint( )
destroy( )

Destroyed Dead End

Exit of Browser
An Applet’s State Transition Diagram

Initialization State:
 Applet enters the initialization state when it is first loaded.
 It occurs only once in the applet’s life cycle.
 This is achieved by calling the init( ) method of Applet class.
 When the applet is born, it requires,
 Create objects needed by the applet
 Set up initial values
 Load images or fonts
 Set up colors

public void init( )


{
............
............ (Action)
............
}

Running State:

Page 10 of 25
JAVA PROGRAMMING – UNIT V

 Applet enters the running state when the system calls the start( ) method
of Applet class.
 It occurs automatically after the applet is initialized.
 The start( ) method may be called more than once.
 Starting can also occur if the applet is already in “stopped”(idle) state.

public void start( )


{
............
............ (Action)
............
}

Idle or Stopped State:


 An applet becomes idle when it is stopped from running.
 We use stop( ) method to terminate the process.

public void stop( )


{
............
............ (Action)
............
}

Dead State:
 An applet is said to be dead when it is removed from memory.
 We use destroy( ) method to quit the browser.
 Destroying state occurs only once in the applet’s life cycle.

public void destroy( )


{
............
............ (Action)
............
}

Display State:
 The display state used to perform some output operations on the
screen.
 It happens immediately after the applet enters into the running state.
 The paint( ) method is to be displayed anything on the screen.

public void paint(Graphics g)


{
..............

Page 11 of 25
JAVA PROGRAMMING – UNIT V

.............. (Display Statements)


..............
}
DESIGNING A WEB PAGE:
 Java applets are programs that reside on Web pages.
 A Web page is made up of text and HTML tags that can be interpreted by
a Web Browser or an applet viewer.
 A Web page is also known as HTML page or HTML document.
 Web pages are stored using a file extension .html which is referred to as
HTML files.
 A Web page is marked by <HTML> and </HTML> tag.
 It is divided into three sections:
1. Comment section
2. Head section
3. Body section
<HTML>
<!
...................... Comment Section
......................
>

<HEAD>
Title Tag Head Section
</HEAD>

<BODY>
Applet Tag Body Section
</BODY>
</HTML>

A Web page Template

1. Comment section:
 This section contains comments about the web page.
 A comment line has <! and > tag.
 Web browsers will ignore the text enclosed between them.
2. Head section:
 The head section contains a title for the Web page.
 It is defined <HEAD> and </HEAD> tag.
For example,
<HEAD>
<TITLE> WELCOME </TITLE>

Page 12 of 25
JAVA PROGRAMMING – UNIT V

</HEAD>
 The text enclosed in the tags <TITLE> and </TITLE> will appear in
the title bar of the Web browser when it displays the page.
Body section:
 After the head section comes the body section.
 It contains the entire information about the web page and its
behaviour.
For example,
<BODY>
<CENTER>
<H1> Welcome to the world of Applets </H1>
</CENTER>
<BR>
<APPLET ..............>
</APPLET>
</BODY>

It will display the message,


Welcome to the world of Applets

ADDING APPLET TO HTML FILE:


We can put together the various components of the Web page and create a
file known as HTML file.
 <APPLET> tag supplies the name of the applet to be loaded.
 It tells the browser how much space the applet requires.

<HTML>
<HEAD>
<TITLE> WELCOME </TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> Welcome to the world of Applets </H1>
</CENTER>
<BR>
<APPLET CODE=test.class WIDTH=400 HEIGHT=200>
</APPLET>
</BODY>
</HTML>

RUNNING THE APPLET:


 The HTML file containing the applet, we must have the following files:
 test.java
 test.class
 test.html

Page 13 of 25
JAVA PROGRAMMING – UNIT V

 To run an applet, we require one of the following tools:


1. Java-enabled Web browser
2. Java appletviewer
1. Java-enabled Web browser:
 It is used to see the entire web page containing the applet.
2. Java appletviewer:
 We use the appletviewer tool, we will only see the applet output.
 It is a part of Java Development Kit(JDK).
For example,
appletviewer test.html

HTML Tags:
HTML supports a large number of tags that can be used to control the style
and format of the display of Web pages.

Tag Function
<HTML>.........</HTML> Begins and end of the HTML file.
<HEAD>.........</HEAD> Contains <TITLE> tag.
<TITLE>.........</TITLE> Title bar of the browser.
Contains main text of web page and also
<BODY>.........</BODY>
<APPLET> tag is declared.

<H1>...............</H1>
<H1> creates the largest font header, while
......
<H6> creates the smallest one.
<H6>...............</H6>
<CENTER>....</CENTER> Text displayed in the center of the page.
<APPLET ......> Declares the applet details as its attributes.
<B>..................<B> Text displayed in bold type.
<BR> Line break tag. Skip a line.
<P> Para tag.
<IMG ..............> Declare an image to display.
<A ...................></A> Anchor tag used to add hyperlinks.
<FONT......> ..........</FONT> To change the colour and size of the text
<! ....................> To add comments

Page 14 of 25
JAVA PROGRAMMING – UNIT V

MANAGING INPUT/OUTPUT FILES IN JAVA


We have used variables and arrays for storing data inside the program. It
leads the following problems:

 The data is lost when a variable goes out of scope, or the program is
terminated. The storage is temporary.
 It is difficult to handle large volume of data.

To overcome these problems by storing data on secondary storages such


as floppy disk or hard disk.

 The data is stored in these devices using the concept of file is called
Persistent Data.
 A File is a collection of related records placed in a particular area on the
disk.
 Records mean collection of data.
 Storing and managing data using files is known as File Processing which
includes creating files, updating files and manipulation of data.
 The process of reading and writing objects is known as Serialization.

0 1 1 0 Bytes

J O H N Field (4 Characters)

Record (3 Fields)

JOHN E19CA9201 78
File (3 Records)
JOHN E19CA9201 78

HEMA E19CA9231 45
Mark Field
RAVI E19CA9247 91

Roll No. Field


Name Field
Data Representation in Java Files

Page 15 of 25
JAVA PROGRAMMING – UNIT V

STREAM CLASSES:
Java.io Package contains large number of stream classes for processing all
types of data.

These classes are categorised into two groups based on data types.

1. Byte stream classes


 It supports for handling Input/Output operations on bytes.
2. Character stream classes
 It supports for managing Input/Output operations on characters.

Java Stream Classes

Byte Stream Classes Character Stream Classes

Input Stream Classes Output Stream Classes Reader Classes Writer Classes

Memory File Pipe Memory File Pipe

Classification of Java Stream Classes

1. BYTE STREAM CLASSES:


 It is used to provide for creating and manipulating streams and files
for reading and writing bytes.
 Streams are unidirectional. It can transmit bytes in only one direction.
 There are two kinds of byte stream classes.
i. Input Stream Classes
ii. Output Stream Classes

Page 16 of 25
JAVA PROGRAMMING – UNIT V

i. Input Stream Classes:


 It is used to read 8-bit bytes
 It has the following methods:
a. read( )
 Read a byte from input stream.
b. available( )
 Gives the number of bytes available in the input stream.
c. reset( )
 Goes back to the beginning of the stream.
d. close( )
 Closes the input stream.

Object

InputStream

FileInputStream SequenceInputStream

PipeInputStream ObjectInputStream

ByteArrayInputStream StringBufferInputStream

FilterInputStream

BufferedInputStream PushbackInputStream

DataInputStream

DataInput

Page 17 of 25
JAVA PROGRAMMING – UNIT V

Hierarchy of Input Stream Classes

ii. Output Stream Classes:


 It can be used for performing the output operations.
 It has the following methods:
a. write( )
 Writes a bytes to output stream.
b. close( )
 Close the output stream.
c. flush( )
 Flushes the output stream.

Object

OutputStream

ObjectOutputStream
FileOutputStream

PipedOutputStream ByteArrayOutputStream

FilterOutputStream

BufferedOutputStream PushbackOutputStream

DataOutputStream

DataOutput

Hierarchy of Output Stream Classes

Page 18 of 25
JAVA PROGRAMMING – UNIT V

2. CHARACTER STREAM CLASSES:


 It can be used to read and write 16-bit Unicode characters.
 There are two kinds of character stream classes.
i. Reader Stream Classes
ii. Writer Stream Classes
i. Reader Stream Classes:
 It is designed to read character from files.
 Reader class is base for all other classes.

Object

Reader

BufferedReader StringReader

CharArrayReader PipeReader

InputStreamReader FilterReader

FileReader PushbackReader

Hierarchy of Reader Stream Classes

Page 19 of 25
JAVA PROGRAMMING – UNIT V

ii. Writer Stream Classes:


 It is designed to perform all output operations on files.
 Writer Stream classes are designed to write characters.

Object

Writer

BufferedWriter PrintWriter

CharArrayWriter StringWriter

PipeWriter
FilterWriter
OutputStreamWriter

File Writer

Hierarchy of Writer Stream Classes

CREATION OF FILES:
 If we want to create and use disk file, we need the details of the file.
 Suitable name for the file.
 Data type to be stored.
 Purpose (Reading, Writing or Updating).
 Method of crating the file.
 A filename is a unique string of character. It helps to identify the file on
the disk.
 Filename may contain two parts.
1. Primary name
2. File extension

Page 20 of 25
JAVA PROGRAMMING – UNIT V

For example, student.txt test.doc shop.xls


 A file stream can be defined using the class.
i. Reader/Input Stream
 Used for reading data
ii. Writer/Output Stream
 Used for writing data

Source or Characters Bytes


Destination Read Write Read Write
Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream
File FileReader FileWriter FileInputStream FileOutputStream
Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream
 The common stream classes used for various input/output operations are:

 There are two ways to initialize file stream objects.


1. Directly (Provides filename)
2. Indirectly (Give file object that has already assigned a filename)

1. Direct Approach:
For example,
FileInputStream fis;
try
{
fis=new FileInputStream(“test.dat”);
}
catch(IOException e)
{
................
................
}

fis “test.dat”

Stream Object Filename

Page 21 of 25
JAVA PROGRAMMING – UNIT V

2. Indirect Approach:
For example,
File inFile;
inFile = new File(“test.dat”);
FileInputStream fis;
try
{
fis=new FileInputStream(inFile);
}
catch(IOException e)
{
................
................
}

The code includes five tasks:

 Select a filename
 Declare a file object
 Give the selected name to the file object declared
 Declare a file stream object
 Connect the file to the file stream object

fis inFile “test.dat”

Stream Object File Object Filename

READING/WRITING CHARACTERS:
The two subclasses used for handling characters in files are FileReader
and FileWriter.

ins stream
Input.dat
read( )
inFile
Program

Output.dat
write( )
outFile outs stream

Page 22 of 25
JAVA PROGRAMMING – UNIT V

For example, Copying characters from one file into another.

import java.io.*;
class copychar
{
public static void main(String args[ ])
{
File infile = new File(“input.dat”);
File outfile = new File(“output.dat”);
FileReader ins = null;
FileWriter outs = null;
try
{
ins = new FileReader(infile);
outs = new FileWriter(outfile);
int ch;
while ((ch = ins.read( )) != -1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
Finally
{
try
{
ins.close( );
outs.close( );
}
catch (IOException e)
{
}
}
}
}

READING/WRITING BYTES:
FileInputStream and FileOutputStream classes used for handling bytes.

For example,

Page 23 of 25
JAVA PROGRAMMING – UNIT V

(i) Writing bytes to a file.

import java.io.*;
class writebyte
{
public static void main(String args[ ])
{
byte cities[ ] = {‘D’, ‘E’, ‘L’, ‘H’, ‘I’, ’\n’, ’L’, ‘O’, ‘N’, ‘D’, ‘O’, ‘N’};
FileOutputStream outs = null;
try
{
outs = new FileOutputStream(“city.txt”);
outs.write(cities);
outs.close( );
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
}
}

(ii) Reading bytes from a file.


import java.io.*;
class readbyte
{
public static void main(String args[ ])
{
FileInputStream ins = null;
int b;
try
{
ins = new FileInputStream(args[0]);
while ((b = ins.read( )) != -1)
{
System.out.println((char)b);
}
ins.close( );
}
catch (IOException e)
{
System.out.println(e);
}
}

Page 24 of 25
JAVA PROGRAMMING – UNIT V

Page 25 of 25

You might also like