Beruflich Dokumente
Kultur Dokumente
PREPARED BY
S.NARMADHA M.E., (AP/CSE)
VERIFIED BY
HOD
PRINCIPAL
CORRESPONDENT
UNIT V
EXCEPTION HANDLING
EXCEPTION HANDLING
PART-A
1. What is an interface? [A/M2015] [M/J2012] [or] Define the term interface. Write the
general form of Interface. [M/J2014] [or] How interface is used in java? Give an
example. [N/D2014] [or] What is meant by Interface in Java? [M/J2013][N/D2013]
2. Write short note on throw().[A/M2015]
3. What is an exception in java? [N/D2014]
4. When will you use Multi-threaded programming? [M/J2013] [N/D2013]
5. What is Package? [M/J2012] [or] Define a package in Java. How it is created?
[N/D2012]
6. Write the syntax for concatenating two strings. [N/D2012]
7. What is meant by stringBuffer? [A/M2011]
8. What is the difference between throw and throws clause?
9. List the various Thread Methods.
10. What are checked and unchecked Exceptions?
11. What is multithreading? [M/J2016]
12. Distinguish between interface and class. [M/J2016]
PART-B
1. Illustrate the use of try-catch clauses by sample statements of rare type run time
error. (16m) [A/M2015] [N/D2011][N/D2013]
2. What is multi threading? Write a multi threaded program in java and explain. (16m)
[A/M2015]
[or]
Discuss with examples for creating multiple threads. (16m) [M/J2014] [or] What is a
Thread? What are the different states of Thread? Explain the creation of Thread with an
example program. (16m) [N/D2014] [N/D2012] [or] What is thread? Explain the life
cycle of a thread with neat diagram and discuss the important methods in the thread
class that are commonly used in application. (8m) [M/J2012] [N/D2011]
3. With suitable examples, explain packages in detail. (16m) [M/J2014] [or] Explain
about Packages in Java with an example program. List built in Java API packages.
(16m) [N/D2014] (16m) [M/J2013] [N/D2012][N/D2013]
4. Discuss about Strings with programming examples. (16m) [M/J2013]
5. Explain the various forms of interface implementations. (8m) [M/J2012] [N/D2011]
[N/D2012]
6. How do you define an interface? Why do the members of interface are static and
final? [M/J2016] [7m]
7. Write a java program to implement nested packages.
8. Distinguish between arrays and strings .[M/J2016] [3m]
9. Explain the method available in the String Bufferf class.[M/J2016] [5m]
10. Explain the use of command line arguments with an example. [M/J2016] [8m]
NOTES
UNIT V
EXCEPTION HANDLING
PART A
1. What is an interface? [A/M2015] [M/J2012] [or] Define the term interface. Write
the general form of Interface. [M/J2014] [or] How interface is used in java? Give
an example. [N/D2014] [or] What is meant by Interface in Java? [M/J2013]
[N/D2013]
An interface is a reference type in Java, it is similar to class, it is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface. The interface keyword is used to declare an interface. There
are mainly three reasons to use interface. They are given below.
Example:
5
Syntax:
return_type method_name() throws exception_class_name
{
//method code
}
3. What is an exception in java? [N/D2014]
An exception (or exceptional event) is a problem that arises during the execution
of a program. When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not recommended,
therefore these exceptions are to be handled.
4. When will you use Multi-threaded programming? [M/J2013] [N/D2013]
Java is amulti threaded programming language which means we can develop
multi threaded program using Java. A multi threaded program contains two or more
parts that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.
java.io - classes for input , output functions are bundled in this package
Example:
public class Test{
Output:
suspend()
resume ()
wait()
notify()
notifyAll()
join()
isAlive()
15. What are the various types of i/o streams available in java
1
Buffered stream
Streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects. Some streams simply pass on data; others
manipulate and transform the data in useful ways.
A program uses an output stream to write data to a destination, one item at time.
PART - B
1. Illustrate the use of try-catch clauses by sample statements of rare type run
time error. (16m) [A/M2015] [N/D2011][N/D2013]
Sometimes exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner. The three categories
of exceptions,
Checked exceptions: A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file is
to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Java Exceptions
The mechanism suggests incorporation of a separate error handling code
mat performs the following tasks:
1. Find the problem [Hit the exception},
2. Inform that an error has occurred {Throw the exception)
10
Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException
:3
Out of the block
11
Example:
try
try
{
//Protected code
}catch(ExceptionType1 e1)
{
x = (byte) file.read();
}catch(IOException i)
//Catch block
}catch(ExceptionType2 e2)
i.printStackTrace();
return -1;
//Catch block
}catch(FileNotFoundException
}catch(ExceptionType3 e3)
valid!
{
//Catch block
f)
//Not
f.printStackTrace();
return -1;
}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list.
If the data type of the exception thrown matches ExceptionType1, it gets caught
there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current
method stops execution and the exception is thrown down to the previous method on
the call stack.
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a method's
signature.
12
You can throw an exception, either a newly instantiated one or an exception that you
just caught, by using the throw keyword. Try to understand the different in throws and
throw keywords.
The following method declares that it
throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount)
throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
import java.io.*;
public class className
{
public void withdraw(double amount)
throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element
three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException
e){
System.out.println("Exception thrown :"
13
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
+ e);
}
finally{
a[0] = 6;
System.out.println("First element value:
" +a[0]);
System.out.println("The finally
statement is executed");
}
}
}
Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException
:3
First element value: 6
are
considered
to
be
checked
14
exceptions.
The
following
Program 2:
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new
CheckingAccount(101);
System.out.println("Depositing
$500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing
$100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing
15
$600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you
are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
InsufficientFundsException
{
if(amount <= balance)
{
balance = amount;
}
else
{
double needs = amount - balance;
throw new
InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The above BankDemo program 2 demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
Compile all the above three files and run BankDemo, this would produce following
result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
2. What is multi threading? Write a multi threaded program in java and explain.
(16m)[A/M2015]
16
[or]
Discuss with examples for creating multiple threads. (16m) [M/J2014] [or] What is
a Thread? What are the different states of Thread? Explain the creation of Thread
with an example program. (16m) [N/D2014] [N/D2012] [or] What is thread?
Explain the life cycle of a thread with neat diagram and discuss the important
methods in the thread class that are commonly used in application. (8m)
[M/J2012] [N/D2011]
A thread is an independent path of execution within a program. Many threads can
run concurrently within a program. Every thread in Java is created and controlled by
the java.lang.Thread class. A Java program can have many threads, and these threads
can run concurrently, either asynchronously or synchronously.
Java is a multi threaded programming language which means we can develop
multi threaded program using Java. A multi threaded program contains two or more
parts that can run concurrently and each part can handle different task at the same time
making optimal use of the available resources specially when your computer has
multiple CPUs.
Multi threading enables you to write in a way where multiple activities can
proceed concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. Following diagram shows complete life cycle of a
thread.
New: A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
17
Waiting: Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task.A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
Timed waiting: A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads.
18
Creating threads
Java's creators have graciously designed two ways of creating threads:
implementing an interface and extending a class.
Step 2:
At second step you will instantiate a Thread object using the following constructor:
Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.
Step 3:
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
19
Example:
Output:
thread is running...
Step 2:
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Output:
20
thread is running...
Thread Methods:
Following is the list of important methods available in the Thread class.
21
22
The previous methods are invoked on a particular Thread object. The following methods
in the Thread class are static. Invoking one of the static methods performs the operation
on the currently running thread.
24
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package
There are three ways to access the package from outside the package.
1) import package.*;
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}
}
//save by B.java
Output:
Hello
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
25
2) import package.classname;
If you import package.classname then only declared class of this package
will be accessible.
//save by A.java
Output:
package pack;
Hello
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
3) fully qualified name
If you use fully qualified name then only declared class of this package
will be accessible. Now there is no need to import. But you need to use
fully qualified name every time when you are accessing the class or
interface.
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
26
//save by A.java
Output:
package pack;
Hello
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Creating a Package
To create a package, you choose a name for the package and put a
package statement with that name at the top of every source file that
contains the types (classes, interfaces, enumerations, and annotation
types) that you want to include in the package.
//in the Circle.java file
package graphics;
public class Circle extends Graphic
implements Draggable {
...
}
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic
implements Draggable {
27
...
}
helloString
hello.
new
String(helloArray);
System.out.println( helloString );
}
}
28
String Length:
The length() method, returns the number of characters contained in the string object.
Below given program is an example of length() , method String class.
Example:
Output:
String Length is : 17
29
Example:
Output:
String Methods:
Here is the list of methods supported by String class:
Method
char charAt(int index)
int compareTo(Object o)
Description
Returns the character at the specified index.
Compares this String to another Object.
Compares two strings lexicographically.
Compares two strings lexicographically,
ignoring case differences.
Concatenates the specified string to the end of
this string.
Returns true if and only if this String represents
the same sequence of characters as the
specified StringBuffer.
Tests if this string ends with the specified
suffix.
Returns a hash code for this string.
Returns the index within this string of the last
occurrence of the specified character.
Returns the length of this string.
Returns a new string resulting from replacing
all occurrences of oldChar in this string with
newChar.
Tests if this string starts with the specified
prefix.
30
An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
31
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example
to declare an interface:
Example:
Below given is an example of an interface:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
32
}
Interfaces have the following properties:
An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
Example:
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class does not
perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the extends portion of
the declaration.
Output
Example
Mammal eats
Mammal travels
33
When overriding methods defined in interfaces there are several rules to be followed:
The signature of the interface method and the same return type or subtype
should be maintained when overriding the methods.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can
extend another class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can
extend another class. The extends keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
35
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class
that implements Hockey needs to implement all six methods. Similarly, a class that
implements Football needs to define the three methods from Football and the two
methods from Sports.
6. How do you define an interface? Why do the members of interface are static
and final? [M/J2016] [7m]
Interfaces form a contract between the class and the outside world, and this contract is
enforced at build time by the compiler. If your class claims to implement an interface, all
methods defined by that interface must appear in its source code before the class will
successfully compile.
All fields declared within an interface are implicity public, static, and final. Why?
Any implementations can change value of fields if they are not defined as final.
Then they would become a part of the implementation.An interface is a pure
specification without any implementation.
If they are static, then they belong to the interface, and not the object, nor the
run-time type of the object.
An interface provide a way for the client to interact with the object. If variables
were not public, the clients would not have access to them.
In general, a field declaration may include the following modifiers: public, protected,
private, final, static, transient, volatile. But only public, final, and static are permitted for
interface's variable.
Every field declaration in the body of an interface is implicitly public, static, and final. It is
permitted to redundantly specify any or all of these modifiers for such fields. Every field
in the body of an interface must have an initialization expression, which need not be a
constant expression. The variable initializer is evaluated and the assignment performed
exactly once, when the interface is initialized.
36
37
It contains some particular sequence of characters, but the length and content of
the sequence can be changed through certain method calls.
Class declaration
Following is the declaration for java.lang.StringBuffer class:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
Class constructors
S.N
.
1
S.N
.
1
StringBuffer()
This constructs a string buffer with no characters in it and an initial capacity of
16 characters.
2
StringBuffer(CharSequence seq)
This constructs a string buffer that contains the same characters as the
specified CharSequence.
3
StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified initial
capacity.
4
StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified string.
Class methods
StringBuffer append(boolean b)
This method appends the string representation of the boolean argument to the
38
5
6
10
11
12
13
14
15
16
17
sequence
StringBuffer append(char c)
This method appends the string representation of the char argument to this
sequence.
StringBuffer append(char[] str)
This method appends the string representation of the char array argument to
this sequence.
StringBuffer append(char[] str, int offset, int len)
This method appends the string representation of a subarray of the char array
argument to this sequence.
StringBuffer append(CharSequence s)
This method appends the specified CharSequence to this sequence.
StringBuffer append(CharSequence s, int start, int end)
This method appends a subsequence of the specified CharSequence to this
sequence.
StringBuffer append(double d)
This method appends the string representation of the double argument to this
sequence.
StringBuffer append(float f)
This method appends the string representation of the float argument to this
sequence.
StringBuffer append(int i)
This method appends the string representation of the int argument to this
sequence.
StringBuffer append(long lng)
This method appends the string representation of the long argument to this
sequence.
StringBuffer append(Object obj)
This method appends the string representation of the Object argument.
StringBuffer append(String str)
This method appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb)
This method appends the specified StringBuffer to this sequence.
StringBuffer appendCodePoint(int codePoint)
This method appends the string representation of the codePoint argument to
this sequence.
int capacity()
This method returns the current capacity.
char charAt(int index)
This method returns the char value in this sequence at the specified index.
int codePointAt(int index)
This method returns the character (Unicode code point) at the specified index
39
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
10. Explain the use of command line arguments with an example. [M/J2016] [8m]
The java command-line argument is an argument i.e. passed at the time of
running the java program.
The arguments passed from the console can be received in the java program
and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Your first argument is: sono
42