Sunteți pe pagina 1din 17

Question Paper

Object Oriented Programming and Java (MC221): July 2005


Section A : Basic Concepts (30 Marks)

1.

Answer all questions.


Each question carries one mark.

Maximum time for answering Section A is 30 Minutes.

Encapsulation
Abstraction
Object persistence.

The use of consistent coding conventions


The organization of components interacting to achieve a coherent, common behavior
The use of inheritance to achieve polymorphic behavior
The organization of components interacting not to achieve a coherent common behavior
The use of data hiding to achieve polymorphic behavior.

(b) Interface
(d) Inheritance

This is an

< Answer >

(e) Aggregation.

Which of the following does not belong: If a class inherits from some other class, it should

< Answer >

Make use of the parent class's capabilities


Over-ride or add the minimum to accomplish the derived class' purpose
Over-ride all the methods of its parent class
Make sure the result "IS-A-KIND-OF" its base class
Make sure the result contains its base class.

Object oriented inheritance models the


(a)
(b)
(c)
(d)
(e)

7.

< Answer >

In object oriented programming new classes can be defined by extending existing classes.
example of:

(a)
(b)
(c)
(d)
(e)
6.

< Answer >

An object is what classes instantiated are from


An object is an instance of a class
An object is a variable
An object is a reference to an attribute
An object is not an instance of a class.

(a) Encapsulation
(c) Composition
5.

< Answer >

(b) Polymorphism
(d) Inheritance

In object oriented programming, composition relates to


(a)
(b)
(c)
(d)
(e)

4.

Which statement is true regarding an object?


(a)
(b)
(c)
(d)
(e)

3.

This section consists of questions with serial number 1 - 30.

A process that involves recognizing and focusing on the important characteristics of a situation or object
is known as:
(a)
(c)
(e)

2.

< Answer >

"is a kind of" relationship


"has a" relationship
"want to be" relationship
inheritance does not describe any kind of relationship between classes
contains of relationship.

The wrapping up of data and functions into a single unit is called

< Answer >

(a) Encapsulation
(c) Data Hiding
8.

(b) Abstraction
(d) Polymorphism

(e) Message passing.


< Answer >

Polymorphism
(a) Is not supported by Java
(b) Refers to the ability of two or more objects belonging to different classes to respond to exactly the
same message in different class-specific ways
(c) Simplifies code maintenance
(d) Not simplifies code manintenance
(e) Refers to the ability of two or more objects belonging to different classes to respond to exactly the
same message in different class specific ways and simplifies code maintenance.

9.

In object oriented programming new classes can be defined by extending existing classes.
example of:
(a) Encapsulation
(d) Inheritance

(b) Interface
(e) Aggregation.

This is an

(c) Composition

10. Given a class named student, which of the following is a valid constructor declaration for the class?
(a) Student (student s) { }
(c) Private final student ( ) { }
(e) Static void student(){ }.

< Answer >

< Answer >

(b) Student student ( ) { }


(d) Void student ( ) { }
< Answer >

11. What is garbage collection in the context of Java?


(a) The operating system periodically deletes all of the java files available on the system.
(b) Any package imported in a program and not used is automatically deleted.
(c) When all references to an object are gone, the memory used by the object is automatically
reclaimed.
(d) The JVM checks the output of any Java program and deletes anything that doesn't make sense.
(e) When all references to an object are gone the memory used by the object is not reclaimed.

< Answer >

12. The concept of multiple inheritance is implemented in Java by


I.
Extending two or more classes.
II. Extending one class and implementing one or more interfaces.
III. Implementing two or more interfaces.
(a) Only (II)
(d) Only (I)

(b) (I) and (II)


(e) Only (III).

< Answer >

13. In Java, declaring a class abstract is useful


(a)
(b)
(c)
(d)
(e)

(c) (II) and (III)

To prevent developers from further extending the class


When it doesn't make sense to have objects of that class
When default implementations of some methods are not desirable
To force developers to extend the class not to use its capabilities
When it makes sense to have objects of that class.

14. What is the error in the following class definitions?


Abstract class xy
{
abstract sum (int x, int y) {
}
(a) Class header is not defined properly.
(b) Constructor is not defined.
(c) Method is not defined properly
(d) Method is defined properly
(e) No error.

< Answer >

< Answer >

15. Which of these field declarations are legal within the body of an interface?
(a) Private final static int answer = 42
(c) final static answer =42
(e) No error.

(b) public static int answer=42


(d) int answer
< Answer >

16. A package is a collection of


(a) Classes
(d) Classes and interfaces

(b) Interfaces
(c) Editing tools
(e) Editing tools and interfaces.

17. A method within a class is only accessible by classes that are defined within the same package as the
class of the method. Which one of the following is used to enforce such restriction?
(a)
(b)
(c)
(d)
(e)

< Answer >

Declare the method with the keyword public


Declare the method with the keyword private
Declare the method with the keyword protected
Do not declare the method with any accessibility modifiers
Declare the method with the keyword public and private.
< Answer >

18. Basic Java language functions are stored in which of the following java package?
(a) java.lang

(b) java.io

(c) java.net

(d) java.util

(e) java.awt.
< Answer >

19. Which of the following is a member of the java.lang package?


(a) List

(b) Queue

(c) Math

(d) Stack

(e) Process.
< Answer >

20. Which of the following has a method names flush( )?


(a) Input stream
(c) Reader stream
(e) Input output stream.

(b) Output Stream


(d) Input reader stream
< Answer >

21. What is the fundamental unit of information of writer streams?


(a) Characters
(c) Files

(b) Bytes
(d) Records

(e) Information.
< Answer >

22. File class is included in which package?


(a) java.io package (b) java.lang package
(c) java.awt package (d) java.net.package
(e) java.util.package.

< Answer >

23. Given the code


String s1 = yes ;
String s2 = yes ;
String s3 = new String ( s1);
Which of the following would equate to true?
(a) s1 == s2

(b) s1 = s2

(c) s3 == s1

(d) s3=s1

< Answer >

24. URL stands for


(a) Universal reader locator
(c) Uniform resource loader
(e) Uniform reader locator.

(b) Universal reform loader


(d) Uniform resource locator

25. What is the sequence of major events in the life of an applet?


(a) init, start, stop, destroy
(c) init, start , destroy, stop
(e) destroy, start, init, stop.

(e) s1!=s2.

(b) start, init , stop , destroy


(d) init, start, destroy

< Answer >

< Answer >

26. Which of the following is true in regard to applet execution?


(a)

Applets loaded from the same computer where they are executing have the same restrictions as
applets loaded from the network.
(b) Applets loaded and executing locally have none of the restrictions faced by applets that get loaded
from the network.
(c) Applets loaded and executing locally have some restrictions faced by applets that get loaded from
the network.
(d) Applets cant react to user input and change dynamically
(e) Applets can be run independently.
< Answer >

27. What is the return type of the method getID() defined in AWTEvent class
(a) Int

(b) long

(c) Object

(d) Component

(e) float.
< Answer >

28. Which of the following events will cause a thread to die?


(a)
(b)
(c)
(d)
(e)

The method sleep( ) is called


The method wait( ) is called
Execution of the start( ) method ends
Execution of the run( ) method ends
Execution of the run() method is called.
< Answer >

29. What will be the result of the expression 13 & 25?


(a) 38

(b) 25

(c) 9

(d) 12

(e) 21.

30. Which of the following statements are true regarding the finalize( ) method?
(a) The finalize ( ) method must be declared with protected accessibility
(b) The compiler will fail to compile the code that explicitly tries to call the finalize( ) method
(c) The body of the finalize ( ) method can only access other objects that are eligible for garbage
collection
(d) The finalize ( ) method can be overloaded
(e) The finalize() method cant be overloaded.

END OF SECTION A

< Answer >

Section B : Problems (50 Marks)


This section consists of questions with serial number 1 5.
Answer all questions.
Marks are indicated against each question.
Detailed workings should form part of your answer.
Do not spend more than 110 - 120 minutes on Section B.
1.

a.

Why is Java known as platform-neutral language? Explain the importance of JVM in Java.

b.

What do you mean by dynamic initialization of a variable? Give an example.


(5 + 5 = 10 marks) < Answer >

2.

a.

What are objects? How are they created from a class?

b.

What is a constructor? What are its special properties?


(5 + 5 = 10 marks) < Answer >

3.

a.

What is meant by method overriding? What is the difference between methods overloading from method
overriding.

b.

Distinguish between static and dynamic polymorphism.

a.
b.
i.
ii.

Define Applet and give the syntax of the applet tag in an HTML file.
Write a short note on the following:
IP Address.
URL.

(5 + 5 = 10 marks) < Answer >


4.

(2 + 8 = 10 marks) < Answer >


5.

a.

What is JDBC? How do you connect to the Database?

b.

Give the sequence of steps to invoke a SQL query using JDBC.


(5 + 5 = 10 marks) < Answer >

END OF SECTION B

Section C : Applied Theory (20 Marks)


This section consists of questions with serial number 6.
Do not spend more than 25 -30 minutes on section C.

6.

a.

Given below are two files :


File Employee.java
package purchase;
public class Employee
{
protected double age = 35;

}
import purchase.Employee;
public class Company
{
public static void main (String args[ ] )
{
Employee e= new Employee ( );
System.out.println ( Age = + e.age );
}
}
Will the file Company.java compile? Explain the reason briefly.
b.

Consider the following class file :


import java.awt.*;
import java.io.*;
package studentbase;
class Test
{
void display ( )

{
System.out.println (Results);
}
}
Will it compile? Give reason for the answer.
c.

How will the following program lay out its buttons.


import java.awt.*;
public class MyClass
{
Public static void main(String args[])
{
String [] labels = {"A","B","C","D","E","F"};
Window win = new Frame ();
win.setLayout(new GridLayout(1,0,2,3));
for(int i=0;i < labels.length;i++)
win.add(new Button(labels[i]));

win.pack ();
win.setVisible (true);

}
}
d.

Is it possible to have multiple catch blocks? Give reason and Illustrate with an example.
(6 + 2 + 2 + 10 = 20 marks) < Answer >
END OF SECTION C
END OF QUESTION PAPER

Suggested Answers

Object Oriented Programming and Java (MC221): July


2005
Section A : Basic Concepts
1.

Answer : (c)
Reason : The insulation of data from direct access by the program is called as
the data abstraction.Data abstraction also called as data hiding, is the
mechanism where by the code and the data it manipulates are
wrapped into a single unit.

< TOP >

2.

Answer : (b)
Reason : An object is an instance of a class. Objects are created from class
definitions that implement abstractions.

< TOP >

3.

Answer : (b)
Reason : Composition is about an object that is made up of other objects,
referred as "containment. Composition implies that the life cycles
are more strongly linked, that means Whole is responsible for the
life time of Part.

< TOP >

4.

Answer : (d)
Reason : Inheritance is a mechanism that enables one class to inherit all of the
behaviour (methods ) and attributes (instance variables) of another
class. A class that inherits from another class is called a subclass and
the class that gives the inheritance is called a superclass.

< TOP >

5.

Answer : (c)
Reason : In a class hierarchy, when a method in a subclass has the same
method signature as that of the superclass, then the method in the
subclass is said to override the method in superclass. When an
overridden method exists in the subclass, the subclass objects always
refer its own. The subclass overridden method hides ( or blocks )
that of the superclass method.

< TOP >

6.

Answer : (a)
Reason : As it models generalization relationship it takes is a kind of

< TOP >

keyword.
7.

Answer : (a)
Reason : Data encapsulation is the method of wrapping up of data and
functions into a single unit.

< TOP >

8.

Answer : (e)
Reason : As Polymorphism refers to the ability of two or more objects
belonging to different classes to respond to exactly the same
message in different class-specific ways. It also simplifies code
manintenance.

< TOP >

9.

Answer : (d)
Reason : As inheritance is nothing but extending existing classes whereas the
others are for different purpose.

< TOP >

10. Answer : (a)


Reason : A constructor cannot specify any return type, not even void. A
constructor cannot be final, static or abstract.

< TOP >

11.

< TOP >

Answer : (c)
Reason : As the remaining all contradict the functionality of JVM.

12. Answer : (c)


Reason : The remaning are not opt solutions for the concept of multiple
inheritance.

< TOP >

13. Answer : (b)


Reason : As other Choices are contradicting the meaning of Abstract Class .

< TOP >

14. Answer : (c)


Reason : method is not defined properly.

< TOP >

15. Answer : (b)


Reason : The remaining are all illegal.

< TOP >

16. Answer : (d)


Reason : Editing tools are not the part of packages.So d is the correct Answer.

< TOP >

17. Answer : (d)


Reason : The desired accessibility is package accessibility, which is the
default accessibility for members that have no accessibility modifier.
Package is not an accessibility modifier.

< TOP >

18. Answer : (a)


Reason : The basic language functions are stored in a package inside of the
java package called java.lang.

< TOP >

19. Answer : (b)


Reason : Math is a member of the java.lang package whereas the remaining
are not.

< TOP >

20. Answer : (b)


Reason : Output stream has the method flush ( ) that flushes the output
stream.

< TOP >

21. Answer : (a)


Reason : Writer streams uses characters as their fundamental unit of
information.

< TOP >

22. Answer : (a)


Reason : File class is included in inputoutput

< TOP >

23. Answer : (a)


Reason : == is a comparision operator whereas = is an assignment operator.

< TOP >

24. Answer : (d)


Reason : The abbreviation of URL uniform resource locator.

< TOP >

25. Answer : (a)


Reason : The remaining all are incorrect because the sequence of major
events are wrong.

< TOP >

26. Answer : (b)


Reason : The remaining Choices are contradicting the properties of applets.

< TOP >

27. Answer : (a)


Reason : Int is the return type of the method getID() in AWTEvent Class.

< TOP >

28. Answer : (d)


Reason : A thread dies when the execution of the run( ) method ends. The call
to the start method is asynchronous, that is, it returns immediately,
and it enables the thread for running. Calling the sleep( ) or wait( )
methods will only block the thread temporarily.

< TOP >

29. Answer : (c)


Reason : 11001&1101==9;

< TOP >

30. Answer : (d)


Reason : The finalize( ) method like any method can be called explicitly if it
is accessible. Intended purpose of the method is to be called by the
garbage collector in order to clean up before an object is destroyed.
Overloading the finalize ( ) method is allowed, but only the method
with the original signature will be called by the garbage collector.

< TOP >

Section B : Problems
1.

a.

Java is known as platform-neutral language as it is not tied to any particular hardware or operating system.
Java programs can be executed any where on any system. They can be moved from one computer system to
another, anywhere and anytime. Changes and upgrades in operating systems, processors and system
resources will not force any changes in the programs.
The Java Virtual Machine is the engine that actually executes a Java program. When a Java program is run,
the instructions are not executed directly by the hardware of the local system, instead an interpreter or
"virtual processor" walks through the instructions step by step and carries out the action the instruction
represents. Java compiler produces and intermediate code known as bytecode .

The machine specific code is generated by the Java interpreter by acting as an intermediary between the byte
code and the real machine as shown below :

b.

Dynamic initialization is the method of initializing the variables dynamically at runtime using any
expression valid at the time the variable is declared .
For example, here is a short program that computes the area of a circle given the radius of it :
// Dynamic initialization
Class DynInit {
Public static void main (String args { } ) {
double r = 5.0;
double p=3.14
// a is dynamically initialized
double a = pi * (r * r )
System.out.println (Area is , + a );
}
}
Here, three local variables are used- r, p, a are declared. The first two r, p, a re initialized by constants.
However, a is initialized dynamically to the area of the circle. Initialization expression may use any element
valid at the time of the initialization, including calls to methods, other variables, or literals.
< TOP >

2.
a.

An object is a specific instance of a class. An object in java is essentially a block of memory that contains
space to store all the instance variables.
The process of creating objects from a class is called instantiation. The object is created using the class and is
a concrete instance of the abstraction that the class represents. An object must be created before it can be
used in a program. In Java objects are manipulated through object references. The process of creating objects
involves the following steps:
1.
2.

Declaration of a variable to store the object reference.


This involves declaring a reference variable of the appropriate class to store the reference to the object.
Creating an object.
This involves using the new operator in conjunction with a call to a constructor, to create an instance of
the class.
Eg : Creating an object of type Circle
Circle C1;
// declare
C1 = new Circle( );
// instantiate

assigns

b.

This first statement declares a variable to hold the object reference and the second one actually
the object reference to the variable.

A constructor is a method, which is invoked when an object of a class is created. It has no return type in java.
Its name must be same as the name of class. It can accept parameter. Here we look at how they function in
java.
Class student
{
int age;
string name;
student( ) //constructor
{
age=0;
name="kiran";
}

In java the overloading of constructors is possible. An overloading means using same name of constructor
with different parameters. An example is given.
Class student
{
int age;
string name;
student() //constructor
{
age=0;
name="kiran";
}
student(int n, string s) // constructor overloading
{
age=n;
name=s;
}
Properties:
Constructors enable an object to initialize itself when created.
Constructors have the same name as that of the class.
They do not specify a return type, not even void.
They return the instance of the class itself
< TOP >

3.
a.

In a class hierarchy , when a method in a subclass has the same method signature as that of the superclass,
then the method in the subclass is said to override the method in superclass. When an overridden method
exists in the subclass, the subclass object always refer its own. The subclass overridden method hides ( or
blocks ) that of the superclass method.
Example :
Class X
{
int i,j;
X ( int a , int b)
{
i = a;
j = b;
}
void show( )
{
System.out.println ( i and j : + i + + j );
}
}
Class Y extends X

{
int k;
Y ( int a , int b , int c )
{
super ( a, b );
k = c;
}
void show ( )
{
System.out.println ( k : + k );
}
}

Class Overridedemo
{
public static void main (String args [ ] )
{
Y subob = new Y ( 1,2,3 );
subob. Show ( );
}
}
Output :

k:3

When show( ) is invoked on an object of type Y, the version of the show( ) defined in Y is used. That is, the
version show ( ) inside Y overrides the version declared in X.
b.

Static polymorphism : In static polymorphism, which method is to be called is decided at compile time only.
Method overloading is an example of static polymorphism. In Method overloading the same method name is used
many times in the same class, but with different parameters. Depending on the parameters passed, it is decided at
compile as which method is to be called. Parameters are the deciding factor (not return type) for the compiler to
decide which method is to be called actually at run-time. In static polymorphism, decision is take at compile-time
(contrast with dynamic polymorphism).
Dynamic polymorphism (also called dynamic method dispatch) is the mechanism by which a call to an overridden
function is resolved at run-time ( not at compile time). Dynamic method dispatch is the method by which Java
implements run-time polymorphism.
When an overridden method is called through a superclass reference, Java
determines which version of that method is to be executed based upon the type of the object being referred at the time the
call occurs.
Thus this determination is made at run time. When different type of objects are referred to , different
versions of an overridden method will be called. It is the type of object being referred to (not the type of reference
variable) that determines which version of an overridden method will be executed. Therefore, if a superclass
contains a method that is overridden by a subclass, then , when different types of objects are referred to through a
superclass reference variable, different versions of the methods are executed.
< TOP >

4.

a.

Java applets are compiled Java programs that are stored on a Web server. A Java applet is a special kind of
program because it can't run on its own. It needs a Web browser to give it a home. When your Web browser
encounters a reference to a Java applet in a Web page, it sends a request to the server that gave it the Web
page to send along the compiled code for the applet as well.

The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. An applet
viewer will execute each APPLET tag that it finds in a separate window, while web browsers like Netscape
Navigator, Internet Explorer, and Hot Java will allow many applets on a single page.
The syntax for the standard APPLET tag is shown here. The bracketed items are optional.
< APPLET
[ CODE BASE = Codebase URL ]
CODE = appletFile
[ ALT = alternateText]
[ Name = applet Instance Name ]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment ]
[VSPACE = pixels ] [ HSPACE = pixels ]
>
[ <PARAM NAME = Attribute Name VALUE = Attribute Value > ]
[ <PARAM NAME = Attribute Name2 VALUE = Attribute Value > ]

[ HTML Displayed in the absence of Java ]


< / APPLET .
b.

a.
net.

An IP address (Internet Protocol Address) is a number that uniquely identifies each computer on the
All internet address consists of 32-bit values (called Ipv4 Internet Protocol, version 4).Latest
addressing scheme, called IPv 6 (Internet Protocol, version 6) uses a 128-bit value to represent an
address. It supports larger address space.
For example, 1.160.10.240 could be an IP address.

b.
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a
resource on
the Internet. The following is an example of a URL which addresses the Java Web
site hosted by
Sun Microsystems:

A URL has two main components:


Protocol identifier
Resource name
The protocol identifier and the resource name are separated by a colon and two forward slashes. The
protocol identifier indicates the name of the protocol to be used to fetch the resource. The example
uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext
documents. HTTP is just one of many different protocols used to access different types of resources
on the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name
depends entirely on the protocol used, but for many protocols, including HTTP, the resource name
contains one or more of the components listed in the following table:
Host Name: The name of the machine on which the resource lives.
Filename: The pathname to the file on the machine.
Port Number : The port number to which to connect (typically optional).

Reference : A reference to a named anchor within a resource that usually identifies a specific location
within a file (typically optional).
< TOP >

5.

a.

The steps to follow for executing an SQL query in JDB:


1.

Connect to the database


A JDBC database is identified by its URL. First invoke the getConnection ( ) method on the
DriverManager class and pass it the URL for the database. The DriverManager will locate a Driver
object that can handle the URL ; it then returns a connection object that uses this driver.

2.

Obtain a statement object


Invoke createStatement( ) method on the connection object; it will return a statement object.

3.

Execute the Query


Invoke the executeQuery ( ) method on the statement object and pass it the SQL SELECT in a string ; it
will execute the query and return the results in a ResultSet object.

4.

Position the cursor to the next row


Invoke next ( ) method to point the cursor to the next row in the ResultSet object. The cursor will point
to the first row after we invoke next ( ) for the first time.

Diagram for invoking a SQL Queue


5.

Retrieve the row values one Column at a time


We must invoke a getxxx ( ) call for each column value that we need to retrieve. The exact function we
invoke depends on the columns SQL type. In the above scenario, we invoke getInt ( ) ,
getBigDecimal ( ), getString ( ) ,and getBoolean( ) to retrieve four column values of SQLTYPE
INTEGER, DECIMAL, VARCHAR ,and BIT.

6.

Repeat while there are rows to be processed


Repeat the last two steps as long as next ( ) returns true; it returns false if there are no more rows.

7.

Release the statement object


Invoke close ( ) to free the resources associated with the statement object.

8.

Release the connection object


Invoke close ( ) to free the resources associated with the connection object.

b.

There are two steps in establishing a connection


(1) loading the driver
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for
example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is
jdbc.DriverXYZ , you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
(2) making the connection

When establishing a connection, have the appropriate driver connect to


DBMS. The following line of code illustrates the general
idea:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");
< TOP >

Section C: Applied Theory


6.

a.

No, the file Company.java will not compile. The field age in the Employee class should be declared as public.

The three access specifiers, private, public and protected, provide a variety of ways to produce
many levels of access required.
Any thing declared public can be accessed from any where. Anything declared private cannot be
seen outside of its class. When a member does not have an explicit access specification , it is
visible to subclasses as well as to other classes in the same package. This is default access. When
an element is to be seen outside the current package, but only to classes that subclass the class
directly, then declare that element protected.
Class members Access

b.
c.
d.

Private

No modifier

Protected

Public

Same class

Yes

Yes

Yes

Yes

Same package
subclass

No

Yes

Yes

Yes

Same package nonsubclass

No

Yes

Yes

Yes

Different package
subclass

No

No

Yes

Yes

Different package
non-subclass

No

No

No

Yes

No, The package definition must come first. The given problem is contradicting to the definition of a
package.
After careful observation of the program the output of the code is that its displays all buttons in a single
row.
There may be situations where more than one exception could be raised by a single piece of code. To handle
this type of situation, we can specify two or more catch blocks, each catching a different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one whose type
matches with that of the exception thrown is executed. If one catch block is executed, the others are
bypassed, and execution continues after the try/catch block. The following example traps two different
exception types:
The following program illustrate multiple catch statements:
Class CatchDemo {

public static void main (String args [ ] ) {


try {
int a = 5, b = 0;
int marks [ ] = {10, 20};
System.out.printin (a/b);

System.out.println (marks [3]);


}
catch (Arithmetic Exception e) {
System.out.println (Do not divide by zero sir +e);
}
catch (ArrayIndexOutOfBounds Exception e) {
System.out.println (Do not access an element that does not exist
sir + e);
}
System.out.printin (After try / catch blocks,);
}
}
In the above code, the statement marks [3] is never executed as program terminates at the statement a / b. If
we make b some integer value, marks [3] is executed and thereby second catch block is executed. Remember,
one try block can throw only one exception at a time and when an exception is thrown control comes out of
the try block in search of a suitable catch block. Once, the control comes out of the try block, it never enters
back again. It is advised to split the above try block into two try blocks to make a robust program.
< TOP >

< TOP OF THE DOCUMENT >

S-ar putea să vă placă și