Java Unit-5 Final
Java Unit-5 Final
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:
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
Page 3 of 25
JAVA PROGRAMMING – UNIT V
}
It will display,
Division by Zero
y=1
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
It will display,
Array Index Error
y=2
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
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 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
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
Page 9 of 25
JAVA PROGRAMMING – UNIT V
start( ) stop( )
start( )
paint( )
destroy( )
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
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.
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.
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.
Page 11 of 25
JAVA PROGRAMMING – UNIT V
<HEAD>
Title Tag Head Section
</HEAD>
<BODY>
Applet Tag Body Section
</BODY>
</HTML>
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>
<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>
Page 13 of 25
JAVA PROGRAMMING – UNIT V
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
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.
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
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.
Input Stream Classes Output Stream Classes Reader Classes Writer Classes
Page 16 of 25
JAVA PROGRAMMING – UNIT V
Object
InputStream
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FilterInputStream
BufferedInputStream PushbackInputStream
DataInputStream
DataInput
Page 17 of 25
JAVA PROGRAMMING – UNIT V
Object
OutputStream
ObjectOutputStream
FileOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
Page 18 of 25
JAVA PROGRAMMING – UNIT V
Object
Reader
BufferedReader StringReader
CharArrayReader PipeReader
InputStreamReader FilterReader
FileReader PushbackReader
Page 19 of 25
JAVA PROGRAMMING – UNIT V
Object
Writer
BufferedWriter PrintWriter
CharArrayWriter StringWriter
PipeWriter
FilterWriter
OutputStreamWriter
File Writer
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
1. Direct Approach:
For example,
FileInputStream fis;
try
{
fis=new FileInputStream(“test.dat”);
}
catch(IOException e)
{
................
................
}
fis “test.dat”
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)
{
................
................
}
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
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
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
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);
}
}
}
Page 24 of 25
JAVA PROGRAMMING – UNIT V
Page 25 of 25