Professional Documents
Culture Documents
Adobe Scan 26-Aug-2022
Adobe Scan 26-Aug-2022
wrapper class?
WBUT 2007, 2009 c)A java package is identified : as
a folder or a file system that
6. What is a and files, related programming language. Each class in can contain
to Java many clasSes
type. The reference during programming we need to havepackage serves sp
a
Answer:
has a corresponding reterence type purpose
It may happen that a
Short objects). A class defines constituent members which enable class instances to have state
Byte and behavior. Data field members (member variables or instance variables) enable a class
numeric strings into numeric values. object to maintain state. Other kinds of members, especially methods, enable a class
Wrapper classes convert
object's behavior. Class instances are of the type of the associated class.
T h e way to store primitive data in an object. public class ExampleClass
The valueOf{) method is available in all wrapper classes except Character
All wrapper classes have typeValue() method. This method returns the value of the private i n t num;
object as its primitive type. public ExampleClass
7. a) What is constructor? What does the finalize method do?
WBUT 2008, 2013, 20171 public ExampleClass (int initialNumValue)
b) Why do we overload a constructor? Explain. WBUT 2008]
c) What are the benefits of organizing classes into package? WBUT 2008] num= initialNumValue;
Answer:
a) 1" Part: Refer to Question No. 1(a) (" Part) of Long Answer Type Questions. public int getNum ( )
return num;
2nd Part:
A finalize method is a protected method of java.lang.Object. This method is called by tne void setNum (int newNumValue)
Dlic
Java garbage collector on object which is least recently used and there are no references
made tothe object for a long time. A finalize method can also be called explicitly from an num = newNumValue;
application program, but this does not ensure that the object will be garbage collected
immediately. This says that Garbage collection cannot be forced in Java. of a class
declaration. lts the blueprint for all
The above code is an example
note of the use of
the keywords private" and "public"
b) A constructor, which does not take any parameters, is known as default x
mpleclass objects. Take The actual number is hjdden
the ut IS an example of data hiding,
also called encapsulation.
constructor. Every Java class automatically provides a default constructor, to S Ihe other classes
have to use the provided
an object of the class. Constructors are also used in a situation when we try
i"ilize that other class can modify
no
values. its
While in simple cases, this really is not
lThis
e also the value of num.
values during object creation. This is done
by parameterizing constructors. is uliC methods to modify because in many cases, you do not want to provide full
known as constructor overloading. essary, it is a good practice,
OOPM-53
0OPM-52
POPULAR PUBLICATIONS OBIECT ORIENTED PROGRAMMING
visibility, or you want to do
something special
when the value of something is changed,
something aw WindowAdapter )
program.
helps wher debugging
a
This also Void windowc Loslng
class from being inherited and therefore preva.
a
public
(WindoWEvent we)
b) The 'final"' keyword prevents ny system. e x i t ( 0 ) ;
to the class's data. If a method is define
sub classing and/or changes being made
we can't provide the reimplementation
for that final method in it's derived n a
then
i.e. overriding is not possible for that method.
classes
An abstract class contains one or moBe abstract method. If all the methods are of.
abstract then use we can declare that class as abstract or interface. But in interface p e frame. setsize (400, 400);
frame.setvisble(true)
methods must be of type abstract.
We can declare final method in abstract class suppose of it is abstract too, then there isno
used to declare like that.
Final abstract int test(String str); 11. Write a program to access static variable and static
keyword properly. meth od to explain 'static
[wSUT 2015]
10. Write a Java program that uses the draw Polygon() method of Graphics clas Answer:
to draw a tiangle with endpoints (25, 30): (75, 80) and (50, 50). [WBUT 2012, 20161 Since the static variables and static methods contain the
Answer: properties of a class and not of
the individual objects, they are also known as class variables and class
import java.lang.*; methods,
respectively.
import java.util.*; The static variables and static methods of a class are also called class variables and class
mport Java.util.List: methods, respectively.
import java. io.*;
import java.awt. * ; The syntax to declare static variable is:
static return_type
mport Java.awt.event.*;
import java.awt.geom. * ;
variable name;
The syntax to access static variable is:
public class Drawtriangle extends Frame ( classname.variable_name
public Polygon mypolygon new The syntax to declare static method is:
public void paint (Graphics g) Polygon();
=
static return_type
Graphics2D ga = (Graphics2D) g; method name
The syntax to to access static method is:
(parameter list);
ga.setPaint (Color.red); class_name method name
ga.draWPolygon (mypolygon); Ifa class member is
declared as static, only one copy of that data member is created,
regardless of the number of objects. All the objects of a class share this single
copy of the
public static void static data member.
List<
maiin (String args []) {
Integer> srcpoints
new ArrayList< Integer
srcpoints:add (25) ; srcpoints.add(30);
=
srcpoints.add(75) ; srCpoints.add(80);
Srcpoints.add(50) ; srcpoints.add(50) ;
StatiC int i-10; //static varlable
Srcpoints.add(srcpoints.get
DrawTriangle frame new (1)); = System.o u t . p r i n t l n ( "Sum of two numbers is: (x*y) ):
for (int i =
0; i DrawTriangle();
srcpoints.sie(); i++)
intx = SrCpoints.get(it+)
int y
CLass StaticExample
srcpoints.get (i);
=
INHERITANCEAND POLYMORPHISM
The output of the program is
Sum of teo
Value of i
numbers
is: 10
is: 70 Multiple Choice Type Questions
Here, variable i and method add() are
declared as static. Therefore. oulside
class 1.
The method
int func
(int i, int j)( ) can be
the nanme of the class in
which they are delined. a) int func (int 1, int j, int k) {}) overloaded using WBUT 2007]
they are accessed using i, floati
b) int func(float
12. Write short notes on the following: Cfloat
d
func (int i, int j) {}
int func (int a, int b) {
a) Access Specifier WBUT 2005, 20061
b) Wrapper class WBUT 2008, 2012, 2015, 20161 float func (int i, int j, float k ) {}
a) (b) & (c)
c) Meta class WBUT 2012, 2016] b) (c)& (d) c) (a), (b), (c)& (e) d) (a), (b), & (e)
Answer: Answer: (d)
a) Access Specifier: Refer to Question No. I of Shori Answer Type Questions
ns.
2. Which one of the following is a valid declaration of an applet? wBUT 2007
b) Wrapper elass: Refer to Question No. 6 of Long Answer Type Questions. a) public class
MyApplet extends java.applet.Applet (
b) public Applet MyApplet{
c) public class MyApplet extends Applet implements Runnable
)Meta class: Refer to Question No. 2 of Long Answer Type Questions d) abstract class My Applet extends java.applet.Applet (
Answer: (a) & (c)
3. Exception is defined
in.... .package. WBUT 2007, 2009]
a) java.util b) java.lang c) java.awt d) java.iio
Answer: (b)
oOPM-57
0OPM-56
POPULAR PUBLICATIONS OBIECT ORIENTED PROGRAMMING
correct
declaration of an abstract method that is intendes
d
be o 12. narrowest valid return Type for method A in line 3?
What is the
public class Returnlt WBUT 2013]
7. What is the WBUT 20101
public? b) public abstract void add (O0
a b s t r a c t void add () d) publicvirtual add ()
a)public etu Type method A (byte x, double y)/"Line
c) public
abstract add () 3
Answer: (a) Return (long)x/ly 2;
8. Consider the class
WBUT 2011
1. Public class Over {
2. public int test (int a, int b)
a) int b) byte c) long d) double
Answer: (d)
3. .
here
4. Il add
5. 13. Runtime binding occurs [WBUT 2014]
overloaded methods would be legal is added at line 472 a) when method overloaded
Which of the following b) interface only
a) Public float test (float a, float b) {} c) class and interface
d) only subpackage
b) Public int test (float a, float b) {} 'Answer:(C)
c) Public int test (int x, int y) {}
d) Public float test (int a, int b) {) 14. Abstract class is used for WBUT 2014]
Answer: (a) & (b) a) inheritance only b) instantiation only
c) both (a) and (b) d) uselesss
signatures in interface?
9. Which three are valid method an
WBUT 2013] Answer: (a)
1. private int getArea();
2. public float get Vol(float x);
15. What is an example of polymorphism? WBUT 2016]
3. public void main (String D args); a) Inner class
4. public static void main (String args); b) Anonymous classes
5. boolean setFlag (Boolean 0 test); c) Method overloading d) Method overriding
a) 1 and12 b) 2, 3 and 5 c) 3, 4 and 5 d) 2 and14 Answer: (c)
Answer: (6)
16. can be represented by
The relation between classes [WBUT 2016]
10. classA WBUT 2013] a) polymorphism b) method c) message d) inheritance
Answer: (d)
appropriate version of function is invoked. Siice the function is linked with a Polymorphism:
particular class much later after the compilation, this process is known as late In object-oriented programming, polymorphism (from the Greek meaning having
multiple forms") is the characteristie of being able to assign a different meaning or usage
because tlhe selection of the
binding. It is also known as dynamic binding to something in different contexts specifically. to allow an entity such as a variable,
appropriate function is done at run time dynamically. Dynamic binding requires function, or an object to have more than one form. There are several di fferent kinds of
use of pointers to objects
which function will be called. polymorphism.
binding is implemented when it is not known
Late
a given name may be allowed to have different
forms and the program
1) A variable with
though early binding is faster than late binding. can determine which form of the variable to use at the time
of execution. For example. a
Suv super types, to provide more relevant information. Refe fo Question No. 11(a) of Long Answer Type
Questions.
Inheritance: sWhat will be the output of the following
with each class A (void show0(system.out.println programme code? EXplain ARIT
Different kinds of objects often have a
certain amount in common
("Inside show of A"):}} 2013]
Mountain bikes. road bikes, and tandem
bikes, for example, all share the characteris class B extends A{void show () {super.show ():
of bicycles (current speed, current pedal cadence, current gear). Yet each also define system.out. printin ("Inside show of B"):)
es class demo {
have two seats and two c
additional features that make them different: tandem bicycles sets
of handlebars; road bikes have drop handlebars; some mountain bikes have an addition
ional
public static void main (String args D)X
lower gear ratio.
Aa1 new B0; a1.show();
chain ring. giving them a
inherit commonly used state and behavior
Object-oriented programming allows classes to Answer:
from other classes. In this example, Bicycle now becomes the superclass
of MountainBike, RoadBike, and TandemBike. In the Java programming language, each
Output:
Inside show of A
class is allowed to have one direct superclass, and each superclass has the potential for an Inside show of B
unlimited number of subclasses: Bicycle In the line ' A al = new B()' class A is reference but the object is o f class B.
The 'super.show calls first the show () method of class A from class B.
int n =
i+j:
3. Explain with the help of an example, how java gets benefited by rface? System.out.println(n);
usingInterta
WBUT 2012, 2015,
2016)
public void add(int i, int j. int k)
Answer:
Refer to Question No. 4(b) of Long Answer Type Questions
0OPM-63
0OPM-62
POPULAR PUBLICATIONS OBIECT ORIENTED PROGRAMMINC
when 3 parameters
is passed. Person is concrete class that
a
l ii) this method will be called Here represents a person, while
int n = itj+k; ete class that represents the details of a person who is
Employment aly
System.out.println(n): them together, you would have everything necessary toemployed. If
define and you cou an
implement
Employee class.
ExCept in Java you can't. Inheriting implementation from mo than
E Derclass multiple
int ){
public void add(int i, int j, int k, one
implementation inheritance IS not a feature of the language.
called when 4 parameters is passed. allows a class
i i ) this method will be to have a single superclass and no more.
int n= itj+k+l; On the other hand, a class can implement multiple interfaces. In other words, ava
suDports muluple intertace inheritance. Suppose the PersonLike interface is:
System.out.println(n)
publ1c
1nterIace
PersonLike (
public static void main(String [}args){ string getName);
bbl = new b(); int getAget)i.
b) 1" Part:
his during
type of polymorphism is achievedwant to the program. Programmers
writing ofMethods are
impose. as well
as constructors
awar
are of the polymorphic nature they
0OPM-65
OOPM-64
POPULAR PUBLICATIONS OHJECT ORIENTED PROGRAINING
i int j method
public vold acid (1nt int| Second class
k int1)
The valid overloading methods in the same class are:
int n 1+)+k+l; void mair(String
public s t a t i c
1. Change in data type of the arguments System.out .print in(n); lanil)
public void sum ( float x, float y) ) Overiding obj new overiding ():
public void sum( flOat x, int y)t}
public s t a t i c void main (String
2. Change in the number of arguments o b j . d i s p l a y( ) :
Daa
public void sum (int x, int y, int z) ( b bi new b )
3. Return type is not considered. Hence the following line is not a valid bl.add (1 2 5);
overloading. l is a Second class method
//public int s um ( int x, int y) ( ) Oulpul:
Although we are using the same name in the overloaded versions but actualy each Lpil:8
method is different and is unique on it's own. That is why, often overloading is not
the method as final.
considered as polymorphism. The return type has nothing to do with the implementation c) We can prevent overriding in Java by declaring
details of a method, hence it is not considered during overloading
class' and interface'?
2. What are the differences between 'abstract
wBUT 2005, 2007, 2009, 2010, 2011, 2013]
2nd Part:
OVERLOADING OVERRIDING Answer: Interface
i) Method overloading is defining several| i) Method overriding is when Abstract class
a
child class 1. An abstract class can containAn intertace can have only
abstract methods.
methods in the same class, that accept different redefines the same method as a parent class,
mplementation of some inethods apart
and types
numbers of parameters. In this with the case.| same parameters. Irom the abstract methods. This makes
the actual method called is decided at compile-| For example, the standard Java class
time. based on the number and types of java.util.LinkedHashSet extends read only clasS.
abstract class tomake a inheris class that mplements or inherits an
an adstract
For instance A class that extends or
arguments the methodjava.util.HashSet. The method add) s| .
same classntertace need
not be in the same hierarchy in
whether
of add(). based on A n e w abstract class caot is not a mandate that these
implementation Into class hierarchy. For exampie
o
eee.as
same hierarchy in which
is a HashSet or a LinkedHashSet. 1his a
the
ne
sme
s e s wil
be in the
classes inherits or extends interface belongs.
called pol ymorphism. the abslract
class needshe
ime bstract class, then
11) Overloading is an
example of compile time ii) Overriding is an example or
ro un nierirchy lhe
polymorphism. polymorphism. The JVM does not Kn b e placed higher up his Can disturh
classes.
be called bove lhese two OOPM-67
which version of method woula
0OPM-66
OBIECT ORIENTED PROGRAMMING
POPULARPUBLICATIONS
An interiace in Java
supports multiple inheritance. Unlike classes.
Interface brovide any concrete
an
interta
Abstract class implementation. Rather the implementation IS
a
extra
o declare an nieriace we interface. To have a class
class.
implementation
This may
involve
overhead
some
Actually there are three uses of super keyword. Overriding through dynamic linking Implementelass();
0OPM-68
OBIECT ORIENTED PROGRAMMING
POPULAR PUBLICATIONS s tem. out.printin"interface1
+ is extended byinter face2 " )%
also needs to be impleme
()
public void display2 public s t a t i c vold main (String [] args)
Interface2") ;
"Display of
System.out.println(
i xedDataType
Mi
mxdtyP new
MixedDataType ();
mxdtyp.display1 ();
mxdtyp.di6play2 ();
mxdtyp.display3 ();
Output
Display of Interfacel
Display of Interface2
5. a) What is an Interface? Implement Interface in java with a simple code. b) In object-oriented programming (OOP), inheritance is a way compartmentalize
to and
whicn
WBUT 2007, 2009] reuse code by creating
collections of attributes and behaviors called objects ca
b) Explain inheritance with its types. WBUT 2007, 2009, 2010] based on previously.created objects.
OR, The derived class inherits some or all of the traits or properties
from the base class.
level.
A
How many types of Inheritance in java7
wBUT 201] class can also inherit properties from more than one class or from
m o r e than o n e A
Answer: derived class with only one base class is called single inheritance and one with severa
a) An interface in Java supports multiple inheritance. Unlike classes. an interface does the
combine
base classes is called mulliple inheritances. Multiple inheritances allow
us to
not provide any conerete implementation. Rather the implementation is provided by a n e w classes. Now,
in
features of several existing classes as a starting point for defining
class. which implements the interlace. from another derived clas. Suppose a
case of multilevel inheritance, a, class is derived
To declare an interface we use the keyword nterlace. To have a class class for another derived
interface the keyword implements is used. iplementing an class is .derived from one class, which in turn serves as a base
traitss
the other hand. the
package matrix.ad.edu; class. So, here the features inheriting continue level by level. On
This process is known as
interface inter facel of o n e class may be inherited by more than one class.
need to apply two o r m o r e
hierarchical inheritance. There could be situations where we
Hybrid inheritance
0OPM-71
OOPM-70
OBIECT ORIENTED PROGRAMMING
POPULAR PUBLICATIONS
irterface
of inheritance java
supports a r Stack lerfece
6. What is inheritance? How many types Queue
Discuss it. Given a method that does
not
declare any exXception, can I overrire? that size, long
method in a to throw an exception?
subclass WBUT 2007, 2017 site bong
O push)
Answer: insertO
pop)
1" Part: remove0
The term inheritance in object oriented programming implies a parent-child relatian
between two or more than two classes. In Java, inheritance is achieved by using the onship
extends keyword.
Illustration
The diagram shown below illustrates a parent-child relationship between two classes. cimplemertaionClass»
The class Parent has two private instance variables and a set of public get set methods MyClass
which provides a way to access the variables outside the class. eth ds,
O insertO
The class child inherits the properties of the parent except the private instance variables
popo
That is, the child class has an automatic access to get set
the methods of the parent class. pushO
Apart from this the child class can also define it's own attributes. Here the child class
o remove0
defines a boolean variable and the corresponding methods to access the variable.
This inheritance relationship is often referred to as 3rd Part:
"There IS-A relationship between' child and parent" When you extend a class, the subclass inherits the methods of the super class. You can
0OPM-72
POPULAR PUBLICATIONS
OBJECT ORIENTED PRoGRAINING
methods of a parent class is always available in the child class. The child clo key word is used
The hio. to refer the
parent
changes the implementation details. just In sonme cases he
child class will constructor or method in pau child
relathan overriding these
rather
reler to
imethods explicitly in the the parent consstr
is. thal il should be lirst class
The basic rules for overriding a method are: super
statement to be called in body.
The only
the child elass
resurn tion
A method overriding is possible only when there is a parent-child relationeL: c o n s t r u c t o r .
n
between two classes. The overriding method should always be in the child class
The overriding method in the child class and the overridden method of
the ho. ect the following code for
class must be same in terms of the number ot parameters, tne data type and arent public class Figure overloading method: WBUT 2009, 2010]
the ret
eturn
ype as well.
Public String draw (String s)
Let us consider the following programs
Class Parent ReturnFigure Drawn"
public String format
( String inputstr)
public vold draw (string s) )
public void draw (double £)
Answer:
return ("#"+inputstr+"#"):
public void draw(String s, double 'f) ( )
1 corrected overlading
class Child extends Parent public void draw (double f ) )
Siringedlnstrument.
two more classes
that implement the
functionality guitar.play() ElectricBassGuitar O; new
ElectricGuitar.java:
public bassGuitar new
ElectricBassGuitar (5) ;
class ElectricGuitar extends guitar .play();|
public ElectricGuitar() StringedInstrument (
super (): bassGuitar.play ();
Chis.name = "Guitar";
In this example, we create two different instances of an
this.number0EStrings = 6; ElectricGuitar and an
ElectricBassGuitar classes and we call their play methods. A sample execution of the
public aforementioned main method is shown below:
super)
ElectricGuitar (int nunberOfStrings) An electric 6-string Guitar is
rocking!
this.name = "Guitar"'; An electric 4-string Bass Guitar is
An electric 7-string Guitar is rocking! rocking
An electric 5-string Bass Guitar is rocking!
this.number0EStrings nuunberOf Stringss; =
override
public void 11. Write a super class interface employee has name and idhasnumber. Write
play () ( manager and labour derived from employee class. Manager class member data
System.out.println("An
+name electric "
numberOfStrings +"-string
g-function
member data q ficationOvertime
andDailywage, and manager allowance and rank labour class has
and Grade. WBUT 2017]
"
is " Answer:
rocking ! ") ;
Class Employee
ElectricBassGuitar.java
public class
int id;
string name;
ElecttricBassGuitar
public ElectricBassGuitar() ( extends StringedInstrument
super ( ); Lass manager extends Employee
this.name =
"Bass Guitar";
this.number0fStrings = 4; string qfunction;
string fication;
publiç
super():ElectricBassGuitar (int
int allowance;
this.name =
"Bass
numberOfStrings) ( int rank;
Guitar"
this.number0f Strings = ass labour extends Employee
Override
numberofStringii; int Dailywage:
int overtime;
public void
play () char Grade;
Class A
0OPM-79
OOPM-78
POPULAR PUBLICATIONS
OBIECT ORIENTEDPROGRAMMING
(string [) args) child c (Child) p
main
public s t a t i c void
c.display ();
public void e) A covariant return type is a method return type that, in the superclass's methood
display ()
declaration, is the supertype of the return in the subclass's overriding method declaration.
System. out.println(" In parent"); Lising 4-21 provides a demonstration ofthis language feature.
ADemonstration of Covariant Return Types
Class SuperReturnType
Child.java @override
public class Child extends
Parent Public String toString()
@Override
Maininherit.java Public String tostring()
public class MainInherit
return "subclass return type";
public static void
main(String[] args)
Parent P =
new class Superclass
Child(); //
dynamic method dispatch
OOPM-80 0OPM-81
POPULARPUBLICATIONS OBIECT ORIENTED PROGRAMIMING
int cix this.x -
SuperReturnType createReturnType ()
int dy this.y
Return new SuperReturnType(); return tioat
Math. Sqrt (dz dx dy dy):
/float distance of
M2 (//0verload detirnitio* (Point p)
Superclass
distance return distance (p.X, p.y);)
Sublcass extends
Class
publiC clasS CovarDemo / *M3* tioat distance (int , int y, int z) {//Another detinitio
of dis tance
int dx = this.x X;
Public static void main(String[] args)
int dy this.yY
SuperReturnType = new Superclass ().createReturnType (); int dz t h l s ,z Z
Output: Superclass r e t u r n
// type (tloat) Math.sqrt (dx*dx dy dy dz dz) :
System.out.println (suprt) ; return
SubReturn subrt = new Subclass () .createReturnType();
/7 Output: subclass return type /M4*/ floatt distance (Point 3D pt)
System.out.printin (subrt); pt.z) i
return distance (pt.x, pt.Y,
SubReturnType return type. Futhermore, this instance doesn't need to be downcast to Eloat dl = pl.distance
°Distance
trom Pi to Origin
="
d0)
SubReturnType when assigning to variable subrt. S y s t e m . o u t .println to pl =" dl)
System.out.println
"Distance rrom p2 M4 will be referred
0, 0);
(0,
) Polymorphism: d
di
p3.distance
p4.distance (P3);
M4 will be
0)
referred
="
trom ps to origind l ) ;
=
trom p3 to p4 ="
polymorphism on nethods. Polymorphism, meaning one object and many shapes, is System.out print ln
"Distance
Simple concept that allows a method to have multiple implementations. This Is also
known as nmethod overload. Following illustrates the idea of polymorphism:
W Polymorphism concept /
class point
int x, Y Output: from PI to Origin
11.18034
(int x, int Distance 7.211102
Point
this.X = Y:
y) ( 1 I t is a constructor Distance from P2 to Pl
12.247449
OOPM-84 0OPM-85
POPULAR PUBLICATIONS
OBECTORIENTED PROGRAMMING
STRING AND STRING BUFFER String s
=
new String ("Stanford");
str += "Lost!!";
the same
Multiple Choice Type Questions looks like this: concatenation, you wouid need
that
StringBuffer ("Stanford")
=
str new
StringBufter
1. Consider the following
class definitions: WBUT 20o9 s t r . a p p e n d ( " L o s t ! ! " ) :
override the equals() method from the Object class, contents of string buffers
ffers not averts to a string representing the
should be data in this
converted to String objects for string comparison. string buffer
if index. is 6. insert(int offset, char c)
A StringlndexOutOfBoundsException is thrown
wrong index in String Buffer manipulations
an not valid when
when using inserts the
f that the string representation of the char,
Note StringButfer class has argument into
Used based on the application need. got many overloaded 'insert'
this string
bun be
Creation of String buffers methods whicn
ca
StringBuffer Constructors
public class StringBufferDemo 7. delete(int start, int end)
Removes the characters in a
substring of this StringBuffer
public static void main(String [] args) (
Examples of Creation of Strings
8. replace(int start, int end, String str)
StringBuffer strBufl new
StringBuffer
=
("Bob")
StringBuffer strBuf2 Replaces the characters in a substring of this StringBuffer with characters in the
=
new
StringButter(100); l/With String. specifiea
capacity 100
ringBuffer strBuf3 =
new
stringBuf fer () ;
//Default
Capacity 16 9. reverse()
The character sequence contained in this
System.out.println( "strBufi1"strBufl) ;
System.out.println( "strBuf2 sequence.
string buffer is replaced by the reverse of the
capacity
strBuf2.capacity ())
System.out.println("strBuf3 capacity 10. append(String str)
strBuf3.capacity ()); Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded 'append' methods which can be
EXCEPTION HANDLING 6.
1. class Class 1{
OBIECT ORIENTED PROGRANIMING
2. public static void main WBUT 2011]
Multiple Choice Type Questions 3. int total 0; (String args [1) {
1. Exception is defined in . .
4. int []i =
new int [3];
package. wBUT 2007, 20161 5. for (int j=1:j<=i. length;
a) java.util b) java.lang c)java.awt j++)
Answer: (b) d) java.ioo 6. total+ (i ] =j);=
7. System.out.printin (total);
2. public int m1 (int x){ 8.)
int count =1; WBUT 2008 9
What is the output of the
try ( program above?
a) 3
Count += x;
count+ m2 (count); b) 4
6
count++;
d) None. The system will throw an
catch (Exception e) e) None. The compiler will throw a Array Index Out. of Bounds Exception
return count;
{count x;)
Answer: (c) syntax error on line 6.
Referring to the above, when m1(2) is invoked, m2() 7. Which of the following statements is correct?
and m1() returns which one of the following? throws an
ArithmeticException a) the 'try' block should be followed WBUT 2012, 2015]
a) 1 b) 2 by
a "catch' block
c) 3 d) 4 b) the 'try' block should be followed by a finally' block
Answer: (6) e) The system will exit c) the 'try' block should be followed by either a
d) the 'ca 'blo or a 'finally' block
'try' block should be followed by at least two
3. How can 'catch' blocks
you have a "try" block that
invokes methods that throw two Answer: (c)
exceptions? different
a) Catch one exception in a "catch" WBUT 2008] 8. Stack over run Is an
b) Setup nested "catch" blocks for block and the other in a "finally" block a) error
WBUT 2014, 2015]
c) Catch one exception in a "catch" each exceptioon b) exception c) virus d) worm
Answer: (b)
d) Use wait () between the calls to block and the other via the return value
e) Include a "catch" block for each process all exceptions before continuing
Answer: (e) exception Short Answer Type Questions
4. How can 1. How Throws and Throw
you ensure that the
memory allocated by an are different? Explain. WBUT 2011, 2016]
object is freed? OR,
a) By invoking the free WBUT 2009] Discuss the difference between 'throw' and 'throws' clause.
method on the WBUT 2013]
b) By calling
system.gc() method
object Answer:
c)By setting all reference to the The throw clause
d) Garbage collection object to new
JVM top free the cannot be forced. The values (say null) The catch block however does not restrict the normal flow of execution, which is outside
Answer: (d) memory used by an objectprogrammer cannot torGe the try-catch block. But it is a good.practice to stop fiurther execution ater an exception
as occurred. In such a situation the throw to stop execution of a
is
clause used explicitly
progranm flow alter a try block throws an exception. We use the throw statement in eatch
5. Which exception is thrown by the block, where the exception is captured. I he throw statement is used normally to throw
read() method of
a) Exception inputStream class0091 Checked exCeption like 1OExceptionn. sQL.ENCeption. \Whenever a checked exNception is
d) lOException b) FileNotFoundException [WBU hrown explicitly by a throw clause. we need to Luse the throWs clause also in the method
Answer: (d) e) None of these c) ReadException
rom wliere tie exeeption is thrown.
0OPM-90 O0PM-91
POPULAR PUBLICATIONS OBIECT ORIENTED PROGRAMMING
The throws clause
ve from the diagram, Throwable has two direct descendants:
can see
method signature, which throws a checked e v c o .
Error and EXception.
The throws clause is used as a
throw a checkea exception from a catch blois
to be remembered that whenever you ock, the
method must associate the throws clause. Errors
ccurs. the virtual machine throws an Error. Typical Java programs shou not
Such
Method Error: main. catch Errors. In addition, it's unlikely that typical Java programs will ever throw ETO
Answer: either.
The name of the exception suggests that the program tried to call a method that d
oesn't
exist. In this context, it sounds like the program does not have a main method, thouh Exceptions
would help if you posted the code that caused the error and the context in which hee cods
code
Most programs throw and catch objects that derive from the Exception class. Exceptions
was run. indicate that a problem occurred but that the problem is not a serious systemic problem.
user tried to runa .class Most programs you write will throw and catch Exceptions.
This might have happened ifthe file or a .jar file that has n0 main The Exception class has many descendants defined in the Java packages. hese
method in Java, the main method is the entry
-
to
point begin executing the program.
Normally the compiler is supposed to prevent this from happening so if this does happen descendants indicate various types of exceptions that can occur. For exampi
it's usually because the name of the method being called is getting determined at run llegalAccess Exception signals that a particular method could not be found.
time, rather than compile-time. andNegativeArraySizeException indicates that a program attempted to create an array
To fix this problem, a new programmer must either add the "main' method with a negative size.
that its main that's missing) or change the method call to the name
(assuming still One Exception subclass has special meaning in the Java language: RuntimeException.
exist.
of a method that does
Runtime Exceptions
the Java virtual
3. Discuss the Exception class hierarchy stating from the 'Throwable' The RuntimeException class represents exceptions that occur within
class. machine (during runtime). An example of a runtime exception NullPointerException,
is
WBUT 2013] an object through a null
Answer: which occurs when a method tries to access a member of
tries to dereference a
This diagram illustrates the class
hierarchy of the Throwable class and its most reference. A NullPointerException can occur anywhere a program
often outveighs the benefit
significant subclasses. reference to an object. The cost of checking for the exception
of catching it.
of
Object Because runtime exceptions ubiquitous and attempting to catch or specity all
are so
them all the time would be a fruitless exercise (and a fruitful source of unreadable and
to go uncaught and
unmaintainable code). the compiler allows runtime exceptions
Throwable unspecified. these
RuntimeException classes. We can catch
The Java packages define several
like other exceptions. Howe ver,
a method is not required to specify that it
exceptions just addition, you can create your own
In
EXception throws RuntimeExceptions. he Controversy contains a thorough
RuntimeExceptionsubclasses. Runtime ExCeptions--
Error runtime exceptions.
of when and how to
use
Oiscussion
Runtim eEXception
Long Answer Type Questions
with examples, user defined and system defined
1. What are exceptions? Explain, [WBUT 2005]
exceptions. OR,
can be created and thrown.
Explain how user defined exception objects
WBUT 2013]
OOPM-93
0OPM-92
POPULAR PUBLICATIONS
Answer: OBJECT ORIENTED PROGRAMMING
Exceptions in java are any abnormal, unexpected events or extraordinary co Answer
may occur at runtime. They could be file not found exception. unable to conditic Ons thar 1 Part:
exception and so on. On such conditions java throws an exception ohiotio In Java input is
taken from the
method or keyboard by passing command line
by using methods in
Exceptions are basically Java objects. No Project can never escape a java error. Java from the class from arguments to
the i
A user defined exception is exception class by API provider
provided or BufferedReader and
Streamtokenizer classes.Java 1/0 like
nputduca
provider which extends Exception defined in the classes of JAVA API.IU's eCation If command line
arugements are used then
with the unconventional action in your codes.JA VA use try-catch Ised interpreter. For
example java Test 1 23. This will passpass the arguments we
with java
construct to tal. 3 arguments to the main
In user defined exception class.you must rewrite method extends
its parent
The argumentsIpasSed will be accepted in the String metnod.
array that is parameterized in the
Exception. You can throw the exception out in try construct and deal with in catch class main method. he string array is then iterated and
converted to required data ype
Imports System operation. o
Public Class EmployeeListNotFoundException The other way of
accepting input from
the key board is to the input eventS Dy
Inherits Exception wrapping the system.in in a BufferedReader. The followingcapture
piece of code explains the
Public Sub New () same
End Sub
Public Sub New (message
BufferedReader br =
new BufferedReader (new
As String)
MyBase. New (message) InputstreamReader ( System.in));
int count 0;
End Sub double sum = 0;
Public Sub New (message As String, inner As StreamTokeni zer st new StreamTokenizer (br) ;
Exception)
MyBase.New (message, inner) if (st.nextToken () ==
st.TT_NUMBER)
End Su'
End Class count. = (int) st.nval; r e t u r n s the actual mumeric value
system defined exceptions are created by the java
compiler itself.
Example (a progranm that, tries to open a file named by the first
System.out.println():
br = new BufferedReader (new
for reading) command-line argument InputStreamReader (System. in) ) ;
public static void main (String [] st new StreamTokenizer (br)
args)
System.out.println ("Enter the
numbers: ")
for (int i = 0; i< count;)
Inputstreamistream;
File
inputFile; double num = 0;
try (
lf (st.nextToken ( ) == st.TT_NUMBER)
inputFile =
new
File(args [0])
istream = new
/ may throw
Input Stream (inputFile) ; num = st.nval;
0OPM-95
0OPM-94
POPULAR PUBLICATIONS OBIECT ORIENTED PROGRAMMING
Lastly, a try block should alway be
In Java exceptions are broadlu
are broadly classified foll
abnormal flow with proper exception handling. compilation errors. by a catch or a finally block to avoid any
into two types:
. Checked Exception 2 nd Part:
WBUT 2009]
str
String.value0f (x);
=
nally
executed. In such a scenario 0OPM-97
block. we put the block of cod
0OPM-96
POPULAR PUBLICATIONS Par OBIECT ORIENTED PROGRAMMING
evception called
Answer:
1" Part: ofa program
equals 3.
quaiot
class
to 14.
Equal ExXception
NotEqual Exc "NotEqualException" that is thrown
An exception is an event, which
occurs during the execution ogram, that disrupts oublic String msg; extends
the normal flow of the program's
instructions. blic Not Exceptior
ion
2. What type of the following stream is used to read binary data? WBUT 2012] 4. Which of the following statements is true? WBUT 2009]
b) InputStream Reader
a) InputStream a) The wait method defined in the thread class can be used to convert a
while (Tokenize.hasMoreTokens()) {
new
StringTokenizer(s," "); ne isAlive( ) method tells whether a
level 10
MAX_PRIORITY represents the
Answer: (b)
0OPM-10
0OPM-100