0% found this document useful (0 votes)
44 views133 pages

Question and Answer

nil

Uploaded by

vinoth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views133 pages

Question and Answer

nil

Uploaded by

vinoth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 133

DEPARTMENT OF INFORMATION TECHNOLOGY

REGULATION 2021–III SEMESTER

CS3391–OBJECT ORIENTED PROGRAMMING


CS3391 OBJECTORIENTEDPROGRAMMING

COURSEOBJECTIVES:

 TounderstandObjectOrientedProgrammingconceptsandbasicsofJavaprogramming
language

 Toknowtheprinciples ofpackages,inheritance and interfaces

 Todevelopajavaapplicationwiththreadsandgenericsclasses

 Todefineexceptionsanduse I/Ostreams

 TodesignandbuildGraphicalUser InterfaceApplicationusingJAVAFX66

UNITI INTRODUCTIONTO OOPANDJAVA

Overview of OOP – Object oriented programming paradigms – Features of Object Oriented


Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays –
Operators–ControlStatements–ProgrammingStructuresinJava–DefiningclassesinJava –
ConstructorsMethods -Access specifiers - Static members- Java Doc comments

UNITIIINHERITANCE,PACKAGESAND INTERFACES

OverloadingMethods–ObjectsasParameters–ReturningObjects–Static,NestedandInner
Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding –
Dynamic Method Dispatch –Abstract Classes – final with Inheritance. Packages and
Interfaces: Packages – Packages and Member Access –Importing Packages – Interfaces.

UNITIIIEXCEPTIONHANDLINGAND MULTITHREADING

ExceptionHandlingbasics–MultiplecatchClauses–NestedtryStatements–Java’sBuilt-in
Exceptions – User defined Exception. Multithreaded Programming: Java Thread Model–
Creating a Thread and Multiple Threads – Priorities – Synchronization – Inter Thread
Communication- Suspending –Resuming, and Stopping Threads –Multithreading. Wrappers–
Auto boxing.

UNITIVI/O,GENERICS,STRING HANDLING

I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics:
GenericProgramming–Genericclasses–GenericMethods–BoundedTypes–Restrictions and
Limitations. Strings: Basic String class, methods and String Buffer Class.

UNITV JAVAFXEVENTHANDLING, CONTROLS AND COMPONENTS

JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls:
Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text
Controls–ScrollPane.Layouts–FlowPane–HBoxandVBox–BorderPane–StackPane–
GridPane. Menus – Basics – Menu – Menu bars – MenuItem.
COURSEOUTCOMES:

Oncompletionofthiscourse, thestudentswillbe able to

CO1:Applytheconceptsofclassesandobjectstosolvesimpleproblems CO2:Develop

programs using inheritance, packages and interfaces

CO3:Makeuseofexceptionhandlingmechanismsandmultithreadedmodeltosolvereal world
problems

CO4:BuildJavaapplicationswithI/Opackages,stringclasses,Collectionsandgenerics concepts

CO5:IntegratetheconceptsofeventhandlingandJavaFXcomponentsandcontrolsfor developing
GUI based applications

TEXT BOOKS:

1. HerbertSchildt,“Java:TheCompleteReference”,11thEdition,McGrawHillEducation, New
Delhi, 2019

2. HerbertSchildt,“IntroducingJavaFX8Programming”,1stEdition,McGrawHill
Education, New Delhi, 2015 67

REFERENCE:

1. CayS.Horstmann,“CoreJava Fundamentals”,Volume1,11thEdition,PrenticeHall,2018.
CS3391 OBJECTORIENTEDPROGRAMMING

UNITI INTRODUCTIONTO OOPANDJAVA


Overview of OOP – Object oriented programming paradigms – Features of Object Oriented
Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays –
Operators – Control Statements – Programming Structures in Java – Defining classes in Java
– Constructors-Methods -Access specifiers - Static members- Java Doc comments

1. Explainthefeaturesofobjectoriented programming.

Object-orientedprogrammingorganizesaprogramarounditsdatathatis,objects)andasetof well-
defined interfaces to that data. An object-oriented program can be characterized as data
controlling access to code.

1) ABSTRACTION:

Abstraction is a process of showingonly “relevant” data and “hide” unnecessary details of


anobjectfromtheuser.Forexample,whenyoulogintoyourbankaccountonline,youenter your
user_id and password and press login, what happens when you press login, how the input
data sent to server, how it gets verified is all abstracted away from the you.
Eg.Car,ATM machine

2) ENCAPSULATION:

 Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.
 Onewaytothinkaboutencapsulationisasaprotectivewrapperthatpreventsthecode
anddatafrombeingarbitrarilyaccessedbyothercodedefinedoutsidethewrapper.Access to the
code and data inside the wrapper is tightly controlled through a well-defined interface.

Class:
A class defines the structure and behavior (data and code) that will be shared by a set
of objects. Each object of a given class contains the structure and behavior defined by
the class

Object:
Objectis aninstanceofa class. Objectshavestates and behaviors.

3) INHERITANCE:
Inheritance is the process by which one object acquires the properties of another object. This
is important because it supports the concept of hierarchical classification.

4) POLYMORPHISM:
 Polymorphismreferstotheabilityofavariable,objectorfunctiontotake onmultiple forms.
The concept of polymorphism is often expressed by the phrase “one interface,
multiple methods.” This means that it is possible to design a generic interface to a
groupofrelatedactivities.Thishelpsreducecomplexitybyallowingthesameinterface to be
used to specify a general class of action.
TypesofPolymorphism
1) Static Polymorphism
2) DynamicPolymorphism
Static Polymorphism:
Polymorphismthatisresolvedduringcompilertimeisknownasstaticpolymorphism.Method
overloadingcanbeconsideredasstaticpolymorphismexample. Method Overloading: This
allows us to have more than one methods with same name in a class that differs in signature.
DynamicPolymorphism
 It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a
processinwhichacalltoanoverriddenmethodisresolvedatruntimerather,thats why it
is called runtime polymorphism

2. Explainaboutthejava buzzwords.

Javabuzzwordsare:
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
1) Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. Assuming that you have some programming experience, you will not find
Java hard to master. If you already understand the basic concepts of object oriented
programming, learning Java will be even easier. Best of all, if you are an experienced
C++ programmer, moving to Java will require very little effort. Because Java inherits
theC/C++syntaxandmanyoftheobject-orientedfeaturesofC++,mostprogrammers have
little trouble learning Java.

2) Secure:
 As an Internet programming language, Java is used in a networked and distributed
environment. If you download a Java applet (a special kind of program) and run it on
your computer, it will not damage your system because Java implements several
securitymechanismstoprotectthesystemagainstharmcausedbystrayprograms.The
security is based on the premise that nothing should be trusted.

3) Portable
 Because Java is architecture neutral, Java programs are portable. They can be run on
any platform without being recompiled. Moreover, there are no platform-specific
features in the Java language.

4) Object-Oriented
Java is anobject-orientedprogramming language. Everything in Java is an object.
Object-orientedmeansweorganizeoursoftwareasacombinationofdifferenttypesof
objectsthatincorporatebothdataandbehaviour.Allcodebelongtosomeclass.Classes are in
turn arranged in a hierarchy or packagestructure

5) Robust
Java is simple. Java is not using pointers. Java support Exception handling. The
try/catch/finally series allows for simplified error recovery. Java is Strongly typed
language – many errors caught during compilation.
6) Multithreaded
Java was designed to meet the real-world requirement of creating interactive,
networked programs. To accomplish this, Java supports multithreaded programming,
whichallowstowriteprogramsthatdomanythingssimultaneously.Java’seasy-to-use
approach to multithreading allows to think about the specific behaviour of your
program, not the multitasking subsystem.
7) Architecture-Neutral
The Java designers designed the Java Virtual Machine(JVM). Thegoal of JVM is
“write once; run anywhere, anytime, forever.”
8) Interpreted:
Javaenablesthecreationofcross-platformprogramsbycompilingintoanintermediate
representation called Java bytecode. This code can be executed on any system that
implements the Java Virtual Machine.
9) High Performance:
Java is faster than other traditional interpreted programming languages because Java
bytecodeis"close"tonativecode.TheJavabytecodewascarefullydesignedsothatit
wouldbeeasytotranslatedirectlyintonativemachinecodeforveryhighperformance by
using a just-in-time compiler. Java run-time systems that provide this feature lose
none of the benefits of the platform-independent code.
10) Distributed:
Java is designed for the distributed environment of the Internet because it handles
TCP/IPprotocols.Infact,accessingaresourceusingaURLisnotmuchdifferentfrom
accessing a file. Java also supports Remote Method Invocation (RMI). This feature
enables a program to invoke methods across a network.
11) Dynamic:
Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time. This makes it possible to
dynamicallylinkcodeinasafeandexpedientmanner.Thisiscrucialtotherobustness of the
Java environment, in which small fragments of bytecode may be dynamically updated
on a running system.

3. Explainaboutliteralsinjava.
Integer Literals
Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all
decimal values, meaning they are describing a base 10 number. Two other bases that can be
used in integer literals are octal (base eight) and hexadecimal (base 16). Octal values are
denoted in Java by a leading zero.Integer literals create an int value, which in Java is a 32-bit
integer value.
When a literal value is assigned to a byte or short variable, no error is generated if the literal
valueiswithintherangeofthetargettype.Aninteger literalcan always beassignedtoa long variable.
However, to specify a long literal, you will need to explicitly tell the compiler that
theliteralvalueisoftypelong.Youdothisbyappendinganupper-orlowercaseLtothe literal. For
example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long. An integer can also
be assigned to a char as long as it is within range.
Floating-PointLiterals
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a whole
number component followed by a decimal point followed by a fractional component.
Floating-point literals in Java default to double precision. To specify a float literal, you must
appendanForf totheconstant.You canalsoexplicitlyspecifyadouble literalby appending
a D or d. Doing so is, of course, redundant. The default double type consumes 64 bits of
storage, while the smaller float type requires only 32 bits.

Boolean Literals
Boolean literals are simple.There are only two logical values that a Booleanvalue can have,
trueandfalse. Thevaluesof trueand falsedonotconvertinto anynumericalrepresentation.
ThetrueliteralinJavadoesnotequal1,nordoesthefalseliteralequal0.InJava,theBoolean literals
can only be assigned to variables declared as boolean or used in expressions with Boolean
operators.
CharacterLiterals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can
beconvertedintointegersandmanipulatedwiththeintegeroperators,suchastheadditionand
subtractionoperators.Aliteralcharacterisrepresentedinsideapairofsinglequotes.Allofthe visible
ASCII characters can be directly entered inside the quotes, such as 'a', 'z', and '@'.
StringLiterals
String literals in Java are specified like they are in most other languages—by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are
"HelloWorld"
"two\nlines"

4. Explainoperatorsinoperators.
Javaprovidesarichoperatorenvironment.Mostofits operatorscanbedivided into the
following four groups:
1. Arithmetic Operators
2. BitwiseOperators
3. RelationalOperators
4. Logical Operators
ArithmeticOperators
Arithmeticoperatorsareusedinmathematicalexpressionsinthesamewaythat theyareused in
algebra. The following table lists the arithmetic operators:

TheModulusOperator
The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types. The following example program demonstrates
the %:
ArithmeticCompoundAssignment Operators
Javaprovidesspecialoperatorsthatcanbeusedtocombineanarithmeticoperationwith an
assignment. As you probably know, statements like the following are quite common in
programming:
a=a+4;
InJava,you canrewritethis statementasshown here:
a+=4;
TheBitwise Operators
Javadefinesseveralbitwiseoperatorsthatcanbeappliedtotheintegertypes, long,int, short,
char,andbyte.Theseoperatorsactupontheindividualbitsoftheiroperands.Theyare summarized
in the following table:

Thebitwiseoperatorsmanipulate thebitswithin an integer.


Alloftheintegertypesarerepresentedbybinarynumbersofvaryingbitwidths.For example, the byte
value for 42 in binary is 00101010, where each position represents a power
oftwo,startingwith20attherightmostbit.Thenextbitpositiontotheleftwouldbe21,or2, continuing
toward the left with 22, or 4, then 8, 16, 32, and so on. So 42 has 1 bits set at
positions1, 3, and5 (counting from0 at theright); thus, 42is the sumof 21 +23 +25, which
is 2 + 8 +32.
All of the integer types (except char) are signed integers. This means that they can represent
negative values as well as positive ones. Java uses an encoding known as two’s complement,
whichmeansthatnegativenumbersarerepresentedbyinverting(changing1’sto0’sand vice versa)
all of the bits in a value, then adding 1 to the result.
TheBitwiseLogical Operators
Thebitwiselogicaloperatorsare&,|,^,and~.Thefollowingtableshowstheoutcomeof each
operation. In the discussion that follows, keep in mind that the bitwise operators are applied
to each individual bit within each operand.
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically,theydetermineequalityandordering.Therelationaloperatorsareshownhere:

Theoutcomeoftheseoperationsisabooleanvalue.Therelationaloperatorsaremost frequently
used in the expressions that control the if statement and the various loop statements.
Boolean Logical Operators

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way
thattheyoperateonthebitsofaninteger.Thelogical !operatorinvertstheBooleanstate:
!true==falseand!false==true.Thefollowingtableshowstheeffectofeachlogical operation:

The? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the ?. It can seem somewhat confusing at first, but the ? can
be used very effectively once mastered. The ? has this general form:
expression1?expression2:expression3

Here,expression1canbeanyexpressionthatevaluatestoabooleanvalue.Ifexpression1is true,
then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operationisthatoftheexpressionevaluated.Both expression2andexpression3arerequired to
return the same type, which can’t be void.
Hereis an exampleofthewaythat the ? is employed:
ratio=denom ==0 ?0 :num / denom;
OperatorPrecedence
Table shows the order of precedence for Java operators, from highest to lowest. The first row
shows items that you may not normally think of as operators: parentheses,
square brackets, and the dot operator. Technically, these are called separators, but they act
likeoperators in an expression. Parentheses areused to alterthe precedence of an operation.
Asyouknowfromthepreviouschapter,thesquarebracketsprovidearrayindexing.Thedot operator
is used to dereference objects.

5. Explainaboutcontrol statements.
Java’sprogramcontrolstatementscanbeput intothefollowing categories:
1. Selection
2. Iteration
3. jump

Selectionstatementsallowyourprogramtochoosedifferent pathsofexecutionbasedupon
theoutcomeofan expressionorthestateofavariable.Iterationstatements enableprogram
execution to repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion.
Java’sSelectionStatements
Javasupportstwoselection statements:
ifandswitch.

If:

thegeneralformoftheif
statement:
if(condition)statement1;
else statement2;
Here,eachstatementmaybeasinglestatementoracompoundstatement enclosedincurly braces
(that is, a block). The condition is any expression that returns a boolean value. The else
clause is optional.

Nestedifs

A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statementalwaysreferstothenearestifstatementthatiswithinthesameblockastheelse and that is
not already associated with an else.

if(i == 10)
{ if(j<20)a=b;
if(k>100)c=d; // this if is
elsea= c; // associatedwith this else
}
elsea=d;

Theif-else-if Ladder
Acommonprogramming constructthatis baseduponasequenceofnestedifsistheif-else-if
ladder.Itlookslikethis:

if(condition)
statement;
elseif(condition)
statement;
elseif(condition)
statement;
...
else
statement;

switch

TheswitchstatementisJava’smultiwaybranchstatement.Itprovidesaneasywaytodispatch
executiontodifferentpartsofyourcodebasedonthevalueofanexpression.Assuch,itoften
providesabetteralternativethanalargeseriesofif-else-ifstatements.Hereisthegeneralform of a
switch statement:
switch(expression)
{ case value1:
//statementsequence
break;
casevalue2:
//statementsequence
break;
...
casevalueN:

//statementsequence
break;
default:
//defaultstatementsequence
}

IterationStatements

Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met. As you will see, Java has a loop to fit any
programming need.

While

ThewhileloopisJava’smostfundamentalloopstatement.Itrepeatsastatementorblockwhile its
controlling expression is true. Here is its general form:
while(condition){
// body ofloop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
astheconditionalexpressionistrue.Whenconditionbecomesfalse,controlpassestothenext
lineofcodeimmediatelyfollowingtheloop.Thecurlybracesareunnecessaryifonly asingle
statement is being repeated.

do-while

Thedo-whileloopalwaysexecutesitsbodyatleast once,becauseitsconditionalexpression is at
the bottom of the loop. Its general form is

do {
// body ofloop
} while (condition);
Eachiterationofthedo-whileloopfirstexecutesthebodyoftheloopandthenevaluatesthe
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Hereisareworkedversionofthe“tick”programthatdemonstratesthedo-whileloop. It
generates the same output as before.

For:

Hereisthegeneralformofthetraditionalforstatement:
for(initialization;condition;iteration){
// body
}
Ifonly one statementis being repeated, thereis no needforthecurly braces.
The for loop operates as follows. When the loop first starts, the initialization portion of the
loopisexecuted.Generally,thisisanexpressionthatsetsthevalueoftheloopcontrolvariable,
whichactsasacounterthatcontrolstheloop.Itisimportanttounderstandthattheinitialization
expression is only executed once. Next, condition is evaluated. This must be a Boolean
expression.Itusuallyteststheloopcontrolvariableagainstatargetvalue.Ifthis expressionis true,
then the body of the loop is executed. If it is false, the loop terminates.
Next,theiterationportionoftheloopisexecuted.Thisisusuallyanexpressionthatincrements
ordecrementstheloopcontrolvariable.Thelooptheniterates,firstevaluatingtheconditional
expression, then executing the body of the loop, and then executing the iteration expression
with each pass. This process repeats until the controlling expression is false.

JumpStatements
Javasupportsthreejumpstatements:break,continue,andreturn.Thesestatementstransfer
control to another part of your program.

Using break
InJava,thebreakstatementhasthreeuses.First, asyouhaveseen,itterminatesastatement
sequenceinaswitchstatement.Second,itcanbeusedtoexitaloop.Third,itcanbeusedas a
“civilized” form of goto.

Usingbreak toExit a Loop


By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop

Using continue
Sometimesitisusefultoforceanearlyiterationofaloop.Thatis,youmightwanttocontinue running
the loop but stop processing the remainder of the code in its body for this particular
iteration.Thisis,ineffect,agotojustpastthebodyoftheloop,totheloop’send.Thecontinue
statement performs such an action. In while and do-while loops, a continue statement causes
control to be transferred directly to the conditional expression that controls the loop.
return
The last control statement is return. The return statement is used to explicitly return from a
method.Thatis,itcausesprogramcontroltotransferbacktothecallerofthemethod.Assuch, it is
categorized as a jump statement.
6. Explainaboutclass,object,methodandconstructorsinjava.
(or)
Explainaboutconstructoroverloading.

Class:
Aclassdefinesthestructureandbehaviour(dataandcode)thatwillbesharedbyaset
ofobjects.Eachobjectofagivenclasscontainsthestructureandbehaviourdefinedby the
class
Object:
Objectis aninstanceofa class. Objectshavestates andbehaviours.
Method:
Amethodis a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation. It is used to achieve the reusability of code.
Constructors:
Aconstructorisablockofcode.Constructoriscalledwhenaninstanceoftheobjectis created, and
memory is allocated for the object.
Constructoroverloadingisatechniquethatenablesasingleclasstohavemorethanone constructor
that varies by the list of arguments passed.

 Constructornamemustbethesameasitsclassname
 AConstructormusthave noexplicitreturntype
 Aconstructorcannotbeabstract,static,final,andsynchronized
Type of constructor:
1. Defaultconstructor
2. Parameterizedconstructor

Program:

classBox
{
double width;
doubleheight;
double depth;
Box()
{
width = 5;
height=4;
depth= 3;
}

Box(doublew, doubleh,double d)
{
width=w;
height=h;
depth = d;
}

double volume()
{
returnwidth*height* depth;
}
}
classBoxDemo
{
publicstatic void main(String args[])
{
Boxb1 =new Box();
Boxb2=newBox(3,6,9);
double vol;
vol = b1.volume();
System.out.println("Volumeofbox1is"+vol); vol
= b2.volume();
System.out.println("Volumeofbox2is "+vol);
}
}

7. Explainaboutaccesscontroloraccessspecifiers.
 Encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control. Through
encapsulation,youcancontrolwhatpartsofaprogramcanaccessthemembers of a
class.
 Bycontrollingaccess,youcanpreventmisuse.
 Javasuppliesarich setofaccess modifiers.

 Java’saccessmodifiersarepublic,private,andprotected.Javaalsodefinesa default
access level.

NoModifier
Private Protected Public
(Default)
Sameclass Yes Yes Yes Yes
Samepackage subclass No Yes Yes Yes
Samepackagenon-subclass No Yes Yes Yes
Differentpackage subclass No No Yes Yes
Differentpackagenon-subclass No No No Yes

1) protectedappliesonlywheninheritanceisinvolved.
2) Whenamemberofaclassismodifiedbypublic,thenthatmembercanbe accessed by
any other code.
3) Whenamemberofaclassisspecifiedasprivate,thenthatmembercanonlybe
accessed by other members of its class.
4) Whennoaccessmodifierisused,thenbydefaultthememberofaclassispublic within
its own package, but cannot be accessed outside of its package.

8. Explainaboutstaticmembers (staticvariable,staticmethod,staticblock).

 When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object. You can declare both methods and
variables to be static. The most common example of a static member is main( ).
main( ) is declared as static because it must be called before any objects exist.
1) Static variable:
 Instancevariablesdeclaredasstaticare,essentially,globalvariables.Whenobjects of its
class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable.

2) Static method:
 Methodsdeclaredasstatichaveseveralrestrictions:
 Theycanonlydirectlycallotherstaticmethods.
 Theycanonlydirectlyaccess staticdata.
 They cannot refer to this or super in any way. (The keyword super relates to
inheritance and is described in the next chapter.)

3) Static block:
If you need to do computation in order to initialize your static variables, you can
declareastaticblockthatgetsexecutedexactlyonce,whentheclassisfirstloaded.
Thefollowingexampleshowsaclassthathasastaticmethod,somestaticvariables, and a
static initialization block:
Demonstratestaticvariables,methods,andblocks.

classstudent
{
int a;
staticintb;
student(){
b++;
}
static
{
System.out.println("Firststatic block");
}
static
{
System.out.println("Secondstatic block");
}
publicvoid showData()
{
System.out.println("Value of a = "+a);
System.out.println("Valueofb="+b);
}

static void display()


{
System.out.println("Thisis static method");
}
}
publicclass studemo
{
publicstatic void main(String args[]){
students1=newstudent();
s1.showData();
students2=newstudent();
s2.showData();
student.display();
}
}

output:
First static block
Secondstaticblock
Value of a =0
Value of b =1
Value of a =0
Value of b =2
Thisis staticmethod

9. Explainaboutjavadoccomments.

Java supports three types of comments. The first two are the // and the /* */. The third type is
called a documentation comment. It begins with the character sequence /**. It ends with */.
Documentation comments allow you to embed information about your program into the
programitself.Youcanthenusethejavadocutilityprogram(suppliedwiththeJDK)toextract
theinformationandputitintoanHTMLfile.Documentationcommentsmakeitconvenientto
document your programs. You have almost certainly seen documentation that uses such
commentsbecausethatisthewaytheJavaAPIibrarywasdocumented. BeginningwithJDK 9,
javadoc includes support for modules.

ThejavadocTags
Thejavadocutility recognizesseveral tags,including thoseshown here:
TheGeneralForm ofaDocumentationComment
After the beginning /**, the first line or lines become the main description of your class,
interface,field,constructor,method,ormodule.Afterthat,youcanincludeoneormoreofthe various
@ tags. Each @ tag must start at the beginning of a new line or follow one or more asterisks
(*) that are at the start of a line. Multiple tags of the same type should be grouped together.
For example, if you have three @see tags, put them one after the other. In-line tags (those
that begin with a brace) can be used within any description. Here is an example of a
documentation comment for a class:
javadoc Outputs
ThejavadocprogramtakesasinputyourJavaprogram’ssourcefileandoutputsseveralHTML
filesthatcontaintheprogram’sdocumentation.Informationabouteachclasswillbeinitsown HTML
file. javadoc will also output an index and a hierarchy tree. Other HTML files can be
generated. Beginning with JDK 9, a search box feature is also included.

/**
* TheAddNumprogramimplementsanapplicationthat
* simplyaddstwogivenintegernumbersandPrints
* the output on thescreen.
* @authorJohn
* @version1.0
* @since30-06-2019
*/

publicclassaddnum {
/**
* Thismethodis usedto addtwo integers.This is
* athe simplest formof aclassmethod, just to
* showtheusageofvarious javadocTags.
* @paramnumAThis isthe firstparamter toaddNum method
* @paramnumBThisis thesecondparametertoaddNum method
* @returnint Thisreturns sumof numAand numB.
*/
publicintaddNum(intnumA,intnumB)
{ return numA + numB;
}

/**
* Thisis the mainmethod which makesuse of addNum method.
* @paramargsUnused.
* @return Nothing.
*/

publicstatic void main(String args[])


{
addnum obj = new addnum();
intsum=obj.addNum(10,20);
System.out.println("Sumof 10and 20is :"+sum);
}
}

Compile:
Z:\>javacaddnum.java
Html file creation:
Z:\>javadocaddnum.java
Htmlfilewill becreated in thesame directory.

12. Developprogramtosortnumbersinascendingorder.
classGFG {
publicstaticvoidmain(String[]args)
{
intarr[]={4,3,2,1};
for(inti=0;i<arr.length;i++){
for(intj=i+1;j<arr.length;j++){ inttemp =
0;
if(arr[j]<arr[i]){
temp = arr[i];
arr[i]=arr[j];
arr[j] = temp;
}
}
System.out.print(arr[i]+"");
}
}
}

Output
1234

CS8392 OBJECTORIENTEDPROGRAMMING
UNIT- I
Part-A
1. DifferentiatebetweenProcess-orientedprogrammingandObject-oriented
programming
1) Process-orientedmodel:

Process-oriented model approach characterizes a program as a series of linear steps.


The process-oriented model can be thought of as code acting on data. Procedural
languages such as C employ this model to considerable success. Problems with this
approach appear as programs grow larger and more complex.

2) Object-orientedprogramming:
To manage increasing complexity object-oriented programming was conceived.
Object-oriented programming organizes a program around its data (that is, objects)
and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.
2. Defineabstraction:
Abstraction is a process where you show only “relevant” data and “hide”
unnecessarydetailsofan objectfromtheuser.For example,whenyoulogintoyour
Amazon account online, you enter your user_id and password and press login, what
happenswhenyoupresslogin,howtheinputdatasenttoamazonserver,howitgets verified
is all abstracted away from the you.
3. Defineencapsulation.

Encapsulationisthemechanismthatbindstogethercodeandthedataitmanipulates, and
keeps both safe from outside interference and misuse.
4. Whatis classesand an objects?

A class defines the structure and behavior (data and code) that will be shared by a set
of objects. Each object of a given class contains the structure and behavior defined by
theclass, as ifit werestampedout by amold in theshapeofthe class. Forthis reason,
objects are sometimes referred to as instances of a class. Thus, a class is a logical
construct; an object has physical reality.
5. Defineinheritance.
Inheritanceistheprocessbywhichoneobjectacquiresthepropertiesofanotherobject. This
is important because it supports the concept of hierarchical classification. Most
knowledge is made manageable by hierarchical (that is, top-down) classifications.
6. Whatismeantbypolymorphism?Specifyitstype.

Polymorphism is theconcept where an object behaves differently in different


situations. There are two types of polymorphism – compile time
polymorphismandruntimepolymorphism.Polymorphismcouldbestaticand
dynamic both. Method Overloading is static polymorphism while,
Methodoverriding is dynamic polymorphism.
7. DifferentiatebetweenmethodOverloadingandmethodOverriding
Method Overloading means more than one method having the same method name
thatbehavesdifferentlybasedontheargumentspassedwhilecallingthemethod.This called
static because, which method to be invoked is decided at the time of compilation.
Method Overriding means aderived class is implementing amethod of its super class.
The call to overridden method is resolved at runtime, thus called runtime
polymorphism
8. Listthejavabuzzwords.(Or)Listthecharacteristicsofjava.
1) Simple
2) Secure
3) Portable
4) Object-oriented
5) Robust
6) Multithreaded
7) Architecture-neutral
8) Interpreted
9) High performance
10) Distributed
11) Dynamic

9. Whatis theuseof constructor?


Aconstructorinitializesanobjectimmediatelyuponcreation.Ithasthe
same name as the class in which it resides and is syntactically similar to a
method. Once defined, the constructor is automatically called when the object
is created, before the new operator completes.
Constructors look alittle strangebecausetheyhaveno returntype, not
evenvoid.Thisisbecausetheimplicitreturntypeofaclass’constructoristhe class
type itself.
Java’s access modifiers are public, private, and protected. Java also
defines a default access level. protected applies only when inheritance is
involved.
10. StateTheuseofthis Keyword.
Sometimes a method will need to refer to the object that invoked it. To allow this,
Java defines the this keyword. this can be used inside any method to refer to the
current object. That is, this is always a reference to theobject on which themethod
was invoked.
11. Whatisdonein garbagecollection?
When no references to an object exist, that object is assumed to be no longer
needed,andthememoryoccupiedbytheobjectcanbereclaimedbythegarbage
collection. Garbage collection only occurs at irregular intervals during the
execution of your program.
12. Whatistheuseoffinalizemethod?
Sometimes an object will need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or
character font, then you might want to make sure these resources are freed before an
object is destroyed. To handle such situations, Java provides a mechanism called
finalization.Byusingfinalization,youcandefinespecificactionsthatwilloccurwhen an
object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run
time calls that method whenever it is about to recycle an object of that class. Inside
thefinalize()method,youwillspecifythoseactionsthatmustbeperformedbefore an
object is destroyed.

13. Specifyvariousaccesscontrolsupportedbyjava.
Encapsulation provides another important attribute: access control. Through
encapsulation,youcancontrolwhatpartsofaprogramcanaccessthemembers of a
class.
By controlling access, you can prevent misuse. For example, allowing access to data
only through a well-defined set of methods, you can prevent the misuse of that data.
How a member can be accessed is determined by the access modifier attached to its
declaration.
Java’saccessmodifiersarepublic,private,andprotected.Javaalsodefinesa default
access level. protected applies only when inheritance is involved.
1) Public:Whenamemberofaclassismodifiedby public,thenthatmember can be
accessed by any other code.

2) Private:Whenamemberofaclassisspecifiedas private,thenthatmember can


only be accessed by other members of its class.

3) Protected:protectedmemberscanbeaccessedbythesamepackageandits
derived classes.

4) Default:Whennoaccessmodifierisused,thenbydefaultthememberofa
classispublicwithinitsownpackage,butcannotbeaccessedoutsideofits
package.

14. Statethesituationwherestaticmembers(staticvariable,staticmethod,andstatic are


used.

There will be times when you will want to define a class member that will be used
independentlyofanyobjectofthatclass.Normally,aclassmembermustbeaccessed only in
conjunction with an object of its class. However, it is possible to create a member
that can be used by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword static.
Whenamemberisdeclaredstatic,itcanbeaccessedbeforeanyobjectsofitsclass
arecreated,andwithoutreferencetoanyobject.Youcandeclarebothmethodsand variables
to be static. The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.

Instance variables declared as static are, essentially, global variables. When objects
ofitsclassaredeclared,nocopyofastaticvariableismade.Instead,allinstancesof the class
share the same static variable.

Methods declared as static have several restrictions:


Theycanonlydirectlycallotherstaticmethods.
They can only directly access static data.
Theycannotrefer to this orsuperinany way.
If you need to do computation in order to initialize your static variables,
youcandeclareastaticblockthatgetsexecutedexactlyonce,whentheclassis first
loaded.
15. Statethe useoffinal keyword.
A field can be declared as final. Doing so prevents its contents from being
modified, making it, essentially, a constant. This means that you must initialize
a final field when it is declared.
Example:
finalintFILE_NEW=1;
16. Whatis theuse ofbreak andcontinuestatement?
Thebreakstatementisusedtoterminatetheloopimmediately. Thecontinue statement is
used to skip the current iteration of the loop.
Part-B
1. Discussvarious features ofOOP.
2. Elaboratethe aboutvariousJava buzzwords.
3. Elaborateaboutvariouscategoriesofoperatorsinjava.
4. Explainaboutonedimensionalandtwodimensionalarraysinjavawithexample
programs.

5. Discuss the use of constructor and finalize() method in java with


programmingexample.Showhowgarbagecollectionisachievedhere.
6. Explainabout class,method and constructoroverloading in java.
7. Explainaboutselection statementsin java.
8. Explainaboutvariousliteralsinjava.(or)Explainaboutvariousdatatypes in
java.

9. Explainaboutthe controlstatements injavawithexampleprograms.


10. Illustratemethodoverloadingwithexample program.
11. Explainstaticfieldand staticmethodwith example.
12. DiscussaboutjavaDoc.Explainthecommentsforclasses,methods, fields.

13. Create a class to print the area of a square and a rectangle. The class has two methods
with the same name but different number of parameters. The method for printing area
of rectangle has two parameters which are length and breadth respectively while the
other method for printing area of square has one parameter which is side of square.

14. Developaprogrambycreatingan'Employee'classhavingthefollowingmethods and


print the final salary.

'getInfo()'whichtakesthesalary,numberofhoursofworkperdayof employee
as parameter.
'AddSal()' which adds Rs.100 to salary of the employee if it is less than Rs.5000.
'AddWork()'whichaddsRs.50tosalaryofemployeeifthenumberofhoursofwork per day
is more than 6 hours.

12. SupposeyouhaveaPiggieBankwithaninitialamountofRs.500andyouhavetoadd some


more amount to it. Create a class 'AddAmount' with a data member named 'amount'
with an initial value of Rs.500. Now make two constructors of this class as follows: 1
- without any parameter - no amount will be added to the Piggie Bank 2 -
havingaparameterwhichistheamountthatwillbeaddedtoPiggieBankCreateobject of the
'AddAmount' class and display the final amount in Piggie Bank.

13. Developajavaprogramto findsmallestnumber inan array.


14. Developaprogramtoprinttheareaofatrianglebycreatingaclassnamed'Area'taking
thevaluesofitsBreadthandHeightasparametersofitsconstructorandhavinga
method named 'returnArea' which returns the area of the triangle. Breadth and Height
of triangle are entered through keyboard.

15. Developajavaprogramthattake20integerinputsfromuserandprintthe
following: number of positive numbers

number of negative
numbers number of odd
numbersnumberofeven
numbers number of 0.

16. Create a class named 'Programming'. While creating an object of the class, if nothing
ispassedtoit,thenthemessage"Ilikeprogramminglanguages"shouldbeprinted.If some
String is passed to it, then in place of "programming languages" the name of that
String variable should be printed. For example, while creating object if we pass
"Java", then "I like Java" should be printed.
17. Writeajavaprogramtofindwhetherthenumberisoddorevennumbersinanarray.
18. Writeajavaprogramtoperformthefollowingfunctionsusingclasses,objects,
constructors and destructors where essential.
i) Getas inputthe marksof5 studentsin 5 subjects
ii) Calculatethetotalandaverage
iii) Printtheformattedresults onthescreen
19. DevelopaminiprojectforMarksheetPreparationsystemusingJava concepts.

20. WriteaJavaprogramthatpromptstheuserforanintegerandthenprintsoutallprime
numbers up to that Integer.

21. WriteaJavaProgramthatreadsalineofintegers,andthendisplayseachinteger,and the sum


of all the integers

CS3391OBJECTORIENTEDPROGRAMMING
UNITIIINHERITANCE,PACKAGESAND INTERFACES
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner
Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding –
DynamicMethodDispatch–AbstractClasses–finalwithInheritance.PackagesandInterfaces:
Packages – Packages and Member Access –Importing Packages – Interfaces.

1. Explainaboutoverloading methods.

Method Overloadingis a feature that allows a class to have multiple methods with the same
name but with different number of parameter and different type of parameters.

Methodoverloading is oneof thewaysthat Javasupports polymorphism.

When an overloaded method is invoked,Javauses thetypeand/ornumberofarguments as its


guideto determinewhich version oftheoverloaded method to actually call. Thus, overloaded
methodsmustdifferinthetypeand/ornumberoftheirparameters.Whileoverloadedmethods
mayhavedifferentreturntypes,thereturntypealoneisinsufficienttodistinguishtwoversions of a
method. When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.

Example:

classOverloadDemo
{
void test()
{
System.out.println("No parameters");
}
voidtest(int a)
{
System.out.println("a="+ a);
}

voidtest(int a,int b)
{
System.out.println("aand b: " +a+"" +b);
}
doubletest(double a)
{
System.out.println("doublea:"+a);
return a*a;
}
}

classOverload
{
publicstatic void main(String args[])
{
OverloadDemoob=newOverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10,20);
result= ob.test(123.25);
System.out.println("Resultofob.test(123.25):"+ result);
}
}

Thisprogram generatesthefollowing output:

Noparameters
a: 10
aand b: 10 20
doublea:123.25
Resultofob.test(123.25):15190.5625

2. Explainaboutoverloadingconstructorsorconstructoroverloading.
Class:
Aclassdefinesthestructureandbehaviour(dataandcode)thatwillbesharedbyaset
ofobjects.Eachobjectofagivenclasscontainsthestructureandbehaviourdefinedby the
class
Object:
Objectis aninstanceofa class. Objects havestates andbehaviours.
Method:
Amethodis a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation. It is used to achieve the reusability of code.
Constructors:
Aconstructorisablockofcode.Constructoriscalledwhenaninstanceoftheobjectis created, and
memory is allocated for the object.
Constructoroverloadingisatechniquethatenablesasingleclasstohavemorethanone constructor
that varies by the list of arguments passed.
 Constructornamemustbethesameasitsclassname
 AConstructormusthave noexplicitreturntype
 Aconstructorcannotbeabstract,static,final,andsynchronized
Type of constructor:
3. Defaultconstructor
4. Parameterizedconstructor

classBox
{
double width;
doubleheight;
double depth;
Box(doublew, doubleh,double d)
{
width=w;
height=h;
depth = d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
//constructorusedwhencubeiscreated
Box(double len)
{
width= height=depth=len;
}
double volume()
{
returnwidth*height* depth;
}
}
classOverloadCons
{
publicstatic void main(String args[])
{

Boxmybox1=newBox(10,20,15); Box
mybox2 = new Box();
Boxmycube=newBox(7); double
vol;
vol = mybox1.volume();
System.out.println("Volumeofmybox1is"+vol); vol
= mybox2.volume();
System.out.println("Volumeofmybox2is"+vol); vol
= mycube.volume();
System.out.println("Volumeofmycubeis"+vol);
}
}

Output:

Volumeofmybox1is3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

5. Explainaboutusingobjectsasparameters.

Objectscanbepassed asparameterto methods and constructors..


Forexample,thefollowingversionof Box allows oneobjecttoinitializeanother:

classBox
{
double width;
doubleheight;
double depth;
Box(Box ob)
{
width = ob.width;
height=ob.height;
depth = ob.depth;
}
Box(doublew,doubleh,doubled)
{ width = w;
height=h;
depth = d;
}
Box()
{ width=-1;
height=-1;
depth=-1;
}
Box(doublelen){
width= height=depth=len;
}
double volume()
{
returnwidth*height* depth;
}
}
classOverloadCons2
{
publicstatic void main(String args[])
{
Boxmybox1=newBox(10,20,15); Box
mybox2 = new Box();
Boxmycube=new Box(7);
Boxmyclone=newBox(mybox1);//createcopyofmybox1
double vol;
vol = mybox1.volume();
System.out.println("Volumeofmybox1is"+vol);
vol = mybox2.volume();
System.out.println("Volumeofmybox2is"+vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);vol
= myclone.volume(); System.out.println("Volume
of clone is " + vol);
}
}

6. Explainaboutreturning objects.
Amethodcanreturnany typeofdata,includingclasstypesthatyoucreate.Forexample,in
thefollowingprogram,theincrement()methodreturnsanobjectinwhichthevalueofais ten
greater than it is in the invoking object.

classTest
{
int a;
Test(inti)
{
a=i;}
Testincrement()
{
Testtemp=newTest(a+10);
return temp;
}
}
classtestdemo
{
publicstatic void main(String args[])
{
Testob1=new Test(2);
Testob2;
ob2 = ob1.increment();
System.out.println("ob1.a:"+ob1.a);
System.out.println("ob2.a:"+ob2.a);
ob2 = ob2.increment();
System.out.println("ob2.aaftersecondincrease:"+ ob2.a);
}
}

Output:

ob1.a:2
ob2.a:12
ob2.aaftersecondincrease: 22

7. ExplainaboutNestedandInner Classes.

Definingaclasswithinanotherclassisknownasnested classes.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
definedwithinclassA,thenBdoesnotexist independentlyofA.Anested classhasaccessto
themembers,includingprivatemembers,oftheclassinwhichitisnested.However,the enclosing
class does not haveaccess to themembersofthenestedclass. A nestedclass that is declared
directly within its enclosing class scope is a member of its enclosing class. It is also possible
to declare a nested class that is local to a block.
Therearetwo typesof nested classes:
1) static
2) non-static.
STATICNESTEDCLASSES:
A static nested class is one that has the static modifier applied. Because it is static, it must
accessthemembersofitsenclosingclassthroughanobject.Thatis,itcannotrefertomembers of its
enclosing class directly. Because of this restriction, static nested classes are rarely used.
NON-STATIC NESTED CLASSES:
Aninner class is a non-staticnested class. It has access to all ofthe variablesand methods of
itsouterclassandmayrefertothemdirectlyinthesamewaythatothernon-staticmembersof the outer
class do.
Thefollowing program illustrates howto define and usean inner class. Theclass named
Outerhasoneinstancevariablenamedouter_x,oneinstancemethodnamedtest(),and defines
one inner class called Inner.

classOuter{ int
x = 100; void
test() {
Innerin=newInner();
in.display();
}
//thisisaninnerclass class
Inner {
voiddisplay() {
System.out.println("display:outer_x="+ x);
}
}
}
classInnerClassDemo{
publicstaticvoidmain(Stringargs[])
{ Outer out = new Outer();
out.test();
}
}
Outputfromthisapplicationisshown here:
display:outer_x=100

In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of InnerClassDemo creates an instance of
classOuterandinvokesitstest()method.ThatmethodcreatesaninstanceofclassInner and the
display( ) method is called.
Itisimportantto realizethataninstanceofInnercanbecreatedonlywithinthe scope
ofclassOuter.TheJavacompilergeneratesanerrormessageifanycodeoutsideofclass Outer
attempts to instantiate class Inner. (In general, an inner class instance must be created by
an enclosing scope.) You can, however, create an instance of Inner outside of Outer by
qualifying its name with Outer, as in Outer.Inner.

8. Explaintypesofinheritancein java.

 Inheritance is the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
 Inheritanceallowsthecreationofhierarchicalclassifications.
 Usinginheritance,youcancreateageneralclassthatdefinesbehaviorcommontoaset of
related items. This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
Superclass:Aclassthatisinheritediscalledasuperclass.

Subclass: The class that does the inheriting is called a subclass. Therefore, a subclass is a
specializedversionofasuperclass.Itinheritsallofthemembersdefinedbythesuperclassand adds its
own, unique elements.
InheritanceBasics:
 To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.
 Beingasuperclassforasubclassdoesnotmeanthatthesuperclasscannotbeusedby itself.
Further, a subclass can be a superclass for another subclass.
Thegeneralformof aclass declarationthatinherits asuperclassisshown here:

classsubclass-nameextendssuperclass-name
{
// body ofclass
}

Youcanonlyspecifyonesuperclassforanysubclassthatyoucreate.Javadoesnotsupportthe
inheritance of multiple superclasses into a single subclass. You can create a hierarchy of
inheritance in which a subclass becomes a superclass of another subclass. However, no class
can be a superclass of itself.
A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.

TYPESOFINHERITANCEINJAVA:
1) Single Inheritance: refers to a sub and super class relationship where a class extends the
another class.

2) Multilevel inheritance: refers to a sub and super class relationship where a class extends
thesubclass.ForexampleclassCextendsclassBandclassBextendsclassA.
3) Hierarchicalinheritance:referstoasubandsuperclassrelationshipwheremorethan one
classes extends the same class. For example, classes B, C & D extends the same class A.

4) MultipleInheritance:referstotheconceptofoneclassextendingmorethanoneclasses, which
means a sub class has two super classes. For example class C extends both classes A and B.
Java doesn’t support multiple inheritance.

MEMBERACCESSANDINHERITANCE:

Although a subclass includes all of the members of its superclass, it cannot


accessthose members of the superclass that have been declared as private.
ProtectedMember:
Theprivatemembersofaclasscannotbedirectlyaccessedoutsidetheclass.Only methodsof that
class can access the private members directly. Sometimes it may be necessary for a
subclasstoaccessaprivatememberofasuperclass.Ifyoumakeaprivatememberpublic,then anyone
can access that member. So, if a member of a superclass needs to be accessed in a subclass
andyet still prevent its directaccessoutside theclass, youmust declare that member protected.
Followingtabledescribesthe difference

Modifier Class Subclass World


Public Y Y Y
Protected Y Y N
Private Y N N

Following program illustrates how the methods of a subclass can directly access a protected
member of the superclass.

1) Single inheritance:
Whenaclassinheritsanotherclass,itisknownasasingleinheritance.
Example:Aclass Shapes issuperclassand derivetheclass: Rectangle
classshape
{
protected double length;
protected double breadth;
shape(double l,doubleb)
{
length = l;
breadth=b;
}
}
classrectangleextendsshape
{
rectangle(doublel,double b)
{
super(l,b);
}

double area()
{
return length*breadth;
}
}

classshapedemo1
{
publicstatic void main(String args[])
{
rectangle r=new rectangle(5,6);
System.out.println("Areaofrectangle:"+r.area());
}
}

Output:
Areaofrectangle: 30.0

2)Hierarchical inheritance:

Whenmorethanoneclasses inheritasame classthen thisiscalledhierarchical inheritance.


Shape

Rectangle
Triangle
Example:AclassShapesissuperclassandderivethetwoclasses:RectangleandTriangle class
shape
{
protected double length;
protected double breadth;
shape(double l,doubleb)
{
length = l;
breadth=b;
}
}
classrectangleextendsshape
{
rectangle(doublel,double b)
{
super(l,b);
}

double area()
{
return length*breadth;
}
}

classtriangleextendsshape
{
triangle(doublel,double b)
{
super(l,b);
}
double area()
{
return 0.5*length*breadth;
}
}
classshapedemo1
{
publicstatic void main(String args[])
{
triangle t=new triangle(3,4);
rectangler=newrectangle(5,6);
System.out.println("Area of triangle : " + t.area());
System.out.println("Areaofrectangle:"+r.area());
}
}

Output:
Area of triangle : 6.0
Areaofrectangle:30.0
3) MULTILEVEL INHERITANCE:

Whenthereisachainofinheritance,itisknownasmultilevelinheritance.

Considerthefollowingprogram.Init,thesubclassBoxWeightisusedasasuperclasstocreate the
subclass called Shipment. Shipment inherits all of the traitsof BoxWeight and Box, and
adds a field called cost, which holds the cost of shipping such a parcel.

classBox
{
private double width;
privatedoubleheight;
private double depth;

Box(doublew,doubleh,doubled)
{ width = w;
height=h;
depth = d;
}
doublevolume(){
returnwidth*height* depth;
}
}

classBoxWeightextendsBox{ do
uble weight;
BoxWeight(doublew,doubleh,doubled,doublem){ super(w,
h, d);
weight=m;
}
}

classShipmentextendsBoxWeight{ do
uble cost;
Shipment(doublew,doubleh,doubled,doublem,doublec){ super(w, h,
d, m);
cost= c;
}
}

classshipmentdemo{
publicstaticvoidmain(Stringargs[]){
Shipmentshipment1=newShipment(10,20,15,10,3.41);
double vol;
vol = shipment1.volume();
System.out.println("Volumeofshipment1is"+vol);
System.out.println("Weightofshipment1is"+shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
}
}

Output:

Volumeofshipment1is3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41

Because of inheritance, Shipment can make use of the previously defined classes of Box and
BoxWeight, adding only the extra information it needs for its own, specific application. This
is part of the value of inheritance; it allows the reuse of code.
Thisexampleillustratesoneotherimportantpoint:super()alwaysreferstotheconstructorin the
closest superclass. The super( ) in Shipment calls the constructor in BoxWeight. The super(
) in BoxWeight calls the constructor in Box. In a class hierarchy, if a superclass constructor
requires parameters, then all subclasses must pass those parameters “up the line.” This is true
whether or not a subclass needs parameters of its own.

4) MULTIPLEINHERITANCE
Javadoes not support Multipleinheritances

9. Explaintheusesofsuper keyword.

Wheneverasubclassneedstorefertoitsimmediatesuperclass,itcandosobyuseofthe keyword
super.
superhastwogeneralforms.
1) Thefirstcallsthesuperclass’ constructor.
2) Thesecondisusedtoaccessamemberofthesuperclassthathasbeenhiddenbya member of a
subclass.

1) USINGSUPERTOCALLSUPERCLASSCONSTRUCTORS:

A subclass can call a constructor defined by its superclass by use of the


followingform of super:
super(arg-list);
Here,arg-list specifiesanyargumentsneededbytheconstructorinthesuperclass.super( )
mustalwaysbethefirst statementexecutedinsideasubclass’constructor.

Example:
classBox
{
double width;
double height;
double depth;
Box(doublew, doubleh,double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
returnwidth*height* depth;
}
}
classBoxWeightextendsBox
{
double weight;
BoxWeight(doublew, double h,doubled, doublem)
{
super(w,h,d);
weight = m;
}
}
classDemoBoxWeight
{
publicstatic void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); double
vol;
vol = mybox1.volume();
System.out.println("Volumeofmybox1is"+vol);
System.out.println("Weightof mybox1is "+mybox1.weight);
}
}
Output:
Volumeofmybox1is3000.0
Weight of mybox1 is 34.3

2) A SECONDUSE FOR SUPER:

Thesecondformofsuperactssomewhatlikethis,exceptthatitalwaysreferstothe superclass of the


subclass in which it is used. This usage has the following general form:

super.member
Here,membercan beeitheramethodoraninstancevariable.

This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
Usingsupertoovercomenamehiding.
class A
{
int i;
}
classBextends A
{
inti;//thisihidestheiinA B(int
a, int b)
{
super.i=a; // i in A
i = b; // i in B
}
voidshow(){
System.out.println("iinsuperclass:"+super.i);
System.out.println("i in subclass: " + i);
}
}

classUseSuper{
publicstaticvoidmain(Stringargs[]){ B
subOb = new B(1, 2);subOb.show();
}
}

Thisprogram displaysthe following:


iinsuperclass:1 i
in subclass: 2

Although the instance variable i in B hides the i in A, super allows access to the i defined
inthesuperclass.Asyouwillsee,supercanalsobeusedtocallmethodsthatarehiddenby a
subclass.

10. Explainabouttypesofpolymorphism.

 Polymorphismistheconceptwhereanobjectbehavesdifferentlyindifferent
situations.
 Therearetwotypesofpolymorphism–compiletimepolymorphismandruntime
polymorphism. Polymorphism could be static and dynamic.
 MethodOverloadingisstaticpolymorphismwhile,Methodoverridingisdynamic
polymorphism.
Polymorphismreferstotheabilityofavariable,objectorfunctiontotakeonmultiple forms.

TypesofPolymorphism

1) StaticPolymorphism:(or)compiletimepolymorphism
Polymorphism that is resolved during compiler time is known as static polymorphism. Method
overloadingcanbeconsideredasstaticpolymorphismexample. Method Overloading: This allows us to
have more than one methods with same name in a class that differs in signature.

Exampleprogram:
class addition
{
voidadd(inta,intb)
{
System.out.println("Sum="+(a+b));
}
voidadd(inta,intb,intc)
{
System.out.println("Sum="+(a+b+c));
}
}

classdemo
{
publicstaticvoidmain(Stringargs[])
{
addition a1=new addition();
addition a2=new addition();
a1.add(4,7);
a3.add(50,30,60);
}
}

2) DYNAMICPOLYMORPHISM:
METHODOVERRIDING:
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within its subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden.
 Asuperclassreferencevariablecanrefertoasubclass object.

DYNAMICMETHODDISPATCH:

Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time. Dynamic method dispatch is important
because this is how Java implements run-time polymorphism.

Overridden methods are another way that Java implements the “one
interface,multiple methods” aspect of polymorphism.

classshape
{
doubledim1length;
double breadth;

shape(doublea,doubleb){ length
= a;
breadth=b;
}
doublearea(){
System.out.println("Areaforshapeisundefined.");
return 0;
}
}
classRectangleextendsshape{ R
ectangle(doublea,doubleb)
{ super(a, b);
}
doublearea(){
return(length*breadth);
}
}

classTriangle extendsshape
{
Triangle(doublea,doubleb)
{
super(a,b);
}
doublearea(){
return(length*breadth/2);
}
}

classshapedemo{
publicstaticvoidmain(Stringargs[])
{ shape s1 = new shape(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Shape s2;
s2 = s1;
System.out.println("Areais"+s2.area()); s2
= t;
System.out.println("Areaoftriangleis"+s2.area()); s2 =
r;
System.out.println("Areaofrectangle is"+s2.area());
}
}
output:

Areaforshapeisundefined.
Area is 0
Area of triangleis 45
Areaofrectangleis40

11. Explainaboutabstractclassesandabstract methods.

Anabstractclassisaclassthatisdeclared abstract—itmayormaynotincludeabstractmethods. Abstract


classes cannot be instantiated, but they can be subclassed.
Example:
abstractclassshape
{
….
}
Anabstractmethodisamethodthatisdeclaredwithoutanimplementation(withoutbraces,and followed by
a semicolon), like this:
abstractvoidarea(doublex,doubley);

program:

abstract class shape {


double length; double
breadth;
shape(doublea,doubleb)
{ length = a;
breadth=b;
}
abstractdouble area();
}
classRectangle extendsshape
{
Rectangle(doublea, doubleb)
{
super(a,b);
}
double area()
{
System.out.println("InsideAreaforRectangle.");
return length * breadth;
}
}

classTriangleextendsshape{ T
riangle(doublea,doubleb)
{ super(a, b);
}
doublearea(){
System.out.println("InsideAreaforTriangle.");
return length * breadth / 2;
}
}

classshapedemo
{
publicstatic void main(String args[])
{
Rectangler=newRectangle(9,5);
Triangle t = new Triangle(10, 8);
shape s2;
s2 = r;
System.out.println("Areais"+s2.area()); s2
= t;
System.out.println("Areais"+s2.area());
}
}

10. Explaintheuses offinalkeywordin inheritance.

Thekeywordfinalhasthreeuses.
1) finalkeywordcanbeusedtocreatetheequivalentofanamedconstant.
Example: finaldouble PI=3.14;

2) finalkeywordcanbeusedtoprevent overriding
3) finalkeywordcanbeusedtoprevent inheritance

1) finalcanbeusedto createtheequivalentofanamed constant.


Example:
finaldoublePI=3.14;

2) usingfinal toprevent overriding:

While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specifyfinalasamodifieratthestartofitsdeclaration.Methodsdeclaredasfinalcannotbe
overridden. The following fragment illustrates final:
classA {
finalvoidmeth(){
System.out.println("Thisis a final method.");
}
}
classB extendsA {
voidmeth(){//ERROR!Can'toverride.
System.out.println("Illegal!");
}
}

Becausemeth() is declared as final, it cannot beoverriddenin B. Ifyou attempt to do so, a


compile-time error will result.
Methodsdeclaredas final cansometimesprovideaperformanceenhancement:Thecompiler is
free to inline calls to them because it “knows” they will not be overridden by a subclass.
When a small final method is called, often the Java compiler can copy the bytecode for the
subroutine directly inline with the compiled code of the calling method, thus eliminating the
costly overhead associated with a method call. Inlining is an option only with final methods.
Normally,Javaresolvescallstomethodsdynamically,atruntime.Thisiscalledlatebinding.
However, since final methods cannot be overridden, a call to one can be resolved at compile
time. This is called early binding.

3) usingfinal toprevent inheritance:


Sometimesyouwillwanttopreventaclassfrombeinginherited.Todothis,precedetheclass
declarationwithfinal.Declaringaclassasfinalimplicitlydeclaresallofitsmethodsas final,
too.Asyoumightexpect,itisillegaltodeclareaclassasbothabstractandfinalsincean
abstractclassisincompletebyitselfandreliesuponitssubclassestoprovidecomplete implementations.

Hereis anexampleofa finalclass:

finalclassA{
//...
}
//Thefollowing class is illegal.

classB extends A{ // ERROR!Can't subclass A


//...
}
Asthecomments imply,it isillegal for B toinheritAsinceAis declaredasfinal.

12. Explainaboutpackagesin java.

Ajavapackageisagroupofsimilartypesofclasses,interfacesandsub-packages.Packageinjavacan be
categorized in two form, built-in package and user-defined package. There are many built-in packages
such as java, lang, awt, javax, swing, net, io, util, sql etc.
AdvantageofJava Package:
1) Javapackageisusedtocategorizetheclassesandinterfacessothattheycanbeeasilymaintained.
2) Javapackageprovidesaccessprotection.
3) Javapackageremovesnamingcollision.
You can define classes inside a packagethat are not accessible by code outside that package. Youcan
also define class members that are exposed only to other members of the same package. This allows
yourclassestohaveintimateknowledgeofeachother,butnotexposethatknowledgetotherestofthe world.

Defininga Package:
To create a package is quite easy: simply include a package command as the first statement in a Java
source file. Any classes declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. If you omit the package statement, the
classnamesareputintothedefaultpackage,whichhasnoname.Whilethedefaultpackageisfinefor short,
sample programs, it is inadequate for real applications. Most of the time, you will define a package
for your code.
Thisisthegeneralformofthepackagestatement:
packagepkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage:
package MyPackage;
Morethanonefilecanincludethesame packagestatement.Thepackagestatementsimplyspecifies to
which package the classes defined in a file belong. It does not exclude other classes in other files
from being part of that same package. Most real-world packages are spread across many files.
Example:
package pack;
publicclassdis
{
publicvoiddisplay()
{
System.out.println("Thisisasimplepackage");
}
}

Filename:dis.java
Compile:Z:\>javac–d.dis.java

IMPORTINGPACKAGES:

In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the import
statement:
importpkg1:
importpack.dis;
class demo
{
publicstaticvoidmain(Stringargs[])
{
disd=newdis();
d.display();
}
}
Filename:demo.java
Compile:
Z:\>javacdemo.java
Run:
Z:\>javademo

Output:
Thisisasimplepackage

13. Whatismeantbyinterface?Howitisdeclaredandimplementedinjava.Give example.

 Aninterfacescanhavemethodsandvariablesbutthemethodsdeclaredininterfacecontain only
method signature, not body.
 Aninterfaceinjavaisablueprintofaclass.Ithasstaticconstantsandabstractmethods. The
interface in java is a mechanism to achieve abstraction.
 Youcannotinstantiateaninterface.
 Aninterfacedoesnotcontainanyconstructors.
 Allofthemethodsinaninterfaceareabstract.
 Aninterfacecannotcontaininstancefields.Theonlyfieldsthatcanappearinaninterfac
e must be declared both static and final.
 Aninterfaceisnotextendedbyaclass;itisimplementedbyaclass.
 Aninterfacecanextendmultipleinterfaces.

Oneinterfacecanextendanother.

interfaceA
{
voidmethod1();
voidmethod2();
}
interfaceBextendsA
{
voidmethod3();
}
classinterimplementsB
{
public void method1()
{ System.out.println("Implementmethod1()."
);
}
public void method2()
{ System.out.println("Implementmethod2()."
);
}
public void method3()
{ System.out.println("Implementmethod3()."
);
}
}
classinterdemo{
publicstaticvoidmain(Stringarg[])
{ interob = new inter();
ob.method1();
ob.method2();
ob.method3();
}
}

Implementmultipleinterfaces:

Multipleinheritance(extends)isnotallowed.Interfacesarenotclasses,however,andaclass can
implement more than one interface.

interfaceInter1
{
publicvoidtest(inti);
}
interfaceInter2
{
publicvoidtest(Strings);
}

publicclassMultInterfacesimplementsInter1,Inter2
{
publicvoidtest(inti)
{
System.out.println("InMultInterfaces.I1.test");
}
publicvoidtest(Strings)
{
System.out.println("InMultInterfaces.I2.test");
}
}
classmultidemo
{
publicstaticvoidmain(Stringargs[])
{
MultInterfacest=newMultInterfaces(); t.test(42);
t.test("Hello");
}
}

CS3391/OBJECTORIENTED PROGRAMMING
Unit-
2PART-
A
1. What is meant by inheritance?
Inheritance is the process by which one object acquires the properties of another object.
Inheritance allows the creation of hierarchical classifications. Using inheritance, you can
createageneralclassthatdefinesbehaviorcommontoasetofrelateditems.Thisclasscan then be
inherited by other, more specific classes, each adding those things that are unique to it.
Superclass:Aclassthatisinheritediscalledasuperclass.
Subclass:Theclassthat doestheinheriting iscalledasubclass.

2. Whatismeantbypolymorphism?Specifyitstype.
Polymorphism is the concept where an object behaves differently in different situations.
There are two types of polymorphism – compile time polymorphism and runtime
polymorphism.
Polymorphismcouldbestaticanddynamicboth. MethodOverloadingisstaticpolymorphism
while, Method overriding is dynamic polymorphism.

3. Differentiatebetween methodOverloadingandmethodOverriding.
 Method Overloadingmeans more than one method having the same method name that
behavesdifferentlybasedontheargumentspassedwhilecallingthemethod.Thiscalled static
because, which method to be invoked is decided at the time of compilation
 MethodOverridingmeansasubclassisimplementingamethodofitssuperclass.Thecall to
overridden method is resolved at runtime, thus called runtime polymorphism

4. DefineDynamicmethoddispatch.(runtimepolymorphismordynamicpolymorphism)
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. Dynamic method dispatch is important
because this is how Java implements run-time polymorphism.
5. Definemethodoverriding.
Inaclasshierarchy,whenamethodinasubclasshasthesamenameandtypesignature as a
method in its superclass, then the method in the subclass is said to override the
method in the superclass. When an overridden method is called from within its
subclass, it will always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
4. Whatarethe uses ofthefinal keyword?
1) finalkeywordcanbeusedtocreatetheequivalentofanamedconstant.
Example:
finaldoublePI=3.14;

2) finalkeywordcan beused topreventoverriding


3) finalkeywordcanbeusedtoprevent inheritance

5. Whatisanobject class?
Object is a superclass of all otherclasses. This means that areferencevariableoftype
Object can refer to an object of any other class. Also, since arrays are implemented
as classes, a variable of type Object can also refer to any array.

6. Whatisanabstract class?
Anabstractclassisaclassthatisdeclaredabstract—itmayormaynotincludeabstract methods.
Abstract classes cannot be instantiated, but they can be subclassed.
Anabstractmethodisamethodthatisdeclaredwithoutanimplementation(withoutbraces, and
followed by a semicolon), like this:
abstractvoidarea(double x,double y);

7. Defineinterfaceandwritesyntaxofinterface.
Aninterfaceinjavaisa blueprintofaclass.Ithasstaticconstantsandabstract methods.
Theinterfaceinjavaisamechanismtoachieveabstraction.Therecanbeonlyabstract methods
in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Inotherwords,youcansaythatinterfacescanhavemethodsandvariablesbutthemethods declared
in interface contain only method signature, not body.

Syntax:
accessinterfacename{
return-typemethod-name1(parameter-list);
return-typemethod-name2(parameter-list);
type final-varname1 = value;
typefinal-varname2=value;
//...
return-typemethod-nameN(parameter-list);
type final-varnameN = value;
}

8. Compareclassesandinterfaces.
BASIS FOR
CLASS INTERFACE
COMPARISON

Basic Aclassisinstantiatedtocreate An interface can never be instantiated as


objects. themethodsareunabletoperformany
action on invoking.

Keyword Class Interface

Accessspecifier Themembersofaclasscanbe Themembersofaninterfacearealways


private,publicor protected. public.

Methods The methods of a class are Themethodsinaninterfacearepurely


definedtoperformaspecific abstract.
action.
BASIS FOR
CLASS INTERFACE
COMPARISON

Implement/Extend A class can implement any An interface can extend multiple


numberofinterfaceandcan interfacesbutcannotimplementany
extend only one class. interface.

Constructor Aclasscanhaveconstructorsto Aninterfacecanneverhaveaconstructor as


initialize the variables. there is hardly any variable to
initialize.

9. Whatis aninnerclass?
Innerclassisaclass withinanotherclass.suchclasses areknown asnestedclasses.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
definedwithinclassA,thenBdoesnotexistindependentlyofA.Anestedclasshasaccess
tothemembers,includingprivatemembers,oftheclassinwhichitisnested.However,the
enclosingclassdoesnothaveaccesstothemembersofthenestedclass.Anestedclassthat is
declared directly within its enclosing class scope is a memberof its enclosing class. It is
also possible to declare a nested class that is local to a block.

10. Howdoyouimplementmultipleinheritanceinjava?
Javadoesnotallowmultipleinheritance:

To reduce the complexity and simplify the language Toavoidthe


ambiguity caused by multiple inheritance

ItcanbeimplementedusingInterfaces.
11. Definesuperclassandsubclass.

Theprocessofderivinganewclassfromanexistingclassisinheritance.Aclassthatisinherited is called a
superclass and the class that does the inheriting is called a subclass.

12. Statethe use ofkeyword super.


It canbeusedtoreferimmediateparentclassinstancevariablewhen bothparentand childclass have
member with same name
Itcanbeusedtoinvokeimmediateparentclassmethod whenchildclasshasoverridden that method.
super()canbeusedtoinvokeimmediateparentclassconstructor.
13. Defineabstractclass?

Abstract classes are classes from which instances are usually not created. It is basically used to
contain common characteristics of its derived classes. Abstract classes generally act as super
classes. Methods can also be declared as abstract. This implies that non-abstract classes must
implement these methods.

14. WhentouseabstractMethods&abstractclass?
Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same
Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.
15. What’sthedifferencebetweenaninterfaceandanabstract class?
Anabstractclassmaycontaincodeinmethodbodies,whichisnotallowedinaninterface. With
abstract classes, we have to inherit our class from it and Java does not allow multiple
inheritance. On the other hand, we can implement multiple interfaces in your class.
16. State the situation where static members(static variable,staticmethod, and static
are used.
There will be times when you will want to define a class member that will be used
independentlyofanyobjectofthatclass.Normally,aclassmembermustbeaccessedonly in
conjunction with an object of its class. However, it is possible to create a member that can
be used by itself, without reference to a specific instance. To create such a member,
precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. You can declare both methods and variables
tobestatic.Themostcommonexampleofastaticmemberismain().main()isdeclared as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When objects of its
classaredeclared,nocopyofastaticvariableismade.Instead,allinstancesoftheclass share the
same static variable.

Methodsdeclaredasstatichaveseveralrestrictions:
Theycanonlydirectlycallotherstaticmethods. They
can only directly access static data.
Theycannotrefer tothisorsuperinany way.
If you need to do computation in order to initialize your static variables, you can
declareastaticblockthatgetsexecutedexactlyonce,whentheclassisfirstloaded.

17. Whataretheuses ofpackage?


Ajavapackageisagroupofsimilartypesofclasses,interfacesandsub-packages.Package
injavacanbecategorizedintwoform,built-inpackageanduser-definedpackage.There are
many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
AdvantageofJavaPackage:
1) Javapackageisusedtocategorizetheclassesandinterfacessothattheycanbeeasily
maintained.
2) Javapackageprovidesaccessprotection.
3) Javapackage removesnamingcollision.

18. Whatarethedifferencebetween staticvariableandinstance variable?


Instance variables Static(class) variables
Class variables also known as static variables are
Instance variables are declared in a class, but
declaredwiththestatickeywordinaclass,but
outsideamethod, constructororany block.
outside a method, constructor or a block.
Instance variables are created when an object is
Staticvariablesarecreatedwhentheprogramstarts and
createdwiththeuseofthekeyword'new'and
destroyed when the program stops.
destroyed when the object is destroyed.
Instance variables can be accessed directly by
Staticvariablescanbeaccessedbycallingwiththe class
calling the variable name inside the class.
nameClassName.VariableName.
However,withinstaticmethods(wheninstance
variablesaregivenaccessibility),theyshould be
called using the fully qualified
name.ObjectReference.VariableName.
Instance variables hold values that must be
referenced by more than one method, There would only be one copy of each class
constructor or block, or essential parts of an variableperclass,regardlessofhowmany
object'sstatethatmustbepresentthroughout the objects are created from it.
class.

19. What’sthedifferencebetweenconstructorsandothermethods?
Constructorsareusedtoinitializetheobject’sstate.Likemethods,aconstructoralsocontainscollection of
statements(i.e. instructions) that are executed at time of Object creation. Each time an object is
created using new() keyword at least one constructor (it could be default constructor) is invoked to
assign initial values to the data members of the same class.
Amethodisacollectionofstatementsthatperformsomespecifictaskandreturntheresulttothecaller. A method
can perform some specific task without returning anything. Methods allow us to reuse the code
without retyping the code. In Java, every method must be part of some class.

Part-B

1. Whatis inheritance?Writeaprogram for inheriting aclass.


2. Explainmultilevelinheritancewithexample program.
3. Canjavasupportmultipleinheritances?Illustrateyouranswerwithexamplejava
program.
4. Whatdoesitmeanthataclassormethodisabstract?Canwemakeaninstanceof abstract
class? Explain it with example.
5. Explainindetailaboutconstructoroverloadingwithanexampleprogram.
6. Explainmethodoverloadingwithanexampleprogram.
7. Discussaboutobjectasparameterwithanexampleprogram.
8. Discussaboutobject asreturntype withanexampleprogram.
9. Explaindynamicbindingand finalkeywordwith example.
10. Whatis polymorphism injava?Explain howpolymorphism supported in java.
11. Definepolymorphism.Showhowcompiletimepolymorphismisachievedin java
program with example program.
12. Explaindynamic dispatch method Ormethod overriding.
13. Explainabouttypes ofpackageswith an exampleprogram.
14. Explainaboutabstractclassandabstractmethod.
15. Write a program to create an interface for customer. In this keep the method called
information(),show()andalsomaintainthetaxrate.Implementtheinterfaceinemployee class
and calculate the tax of an employee based on their income.

Tax
Income percentage
<=Rs 2,50,000 Nil
Rs 2,50,000– Rs 5,00,000 5%
Rs 5,00,000– 10,00,000 20%
>Rs 10,00,000 30%
16. Defineinnerclasses.Howto accessobjectstateusing innerclasses.Give an example.
17. Explainnestedinterfacewithexample program.
18. Whatisaninterface?Showthathowinterface canbeextended.

19. Whatismeantbyinterface?Howitisdeclaredandimplementedinjava.Give
example.
20. WriteaJavaProgramtocreateanabstractclassnamedShapethatcontainstwointegers
andanemptymethodnamedprintArea()andCircumference().Providethreeclassesnamed
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
EachoneoftheclassescontainsthemethodtoprintArea()andCircumference().Thatprints the
area and circumference of the given shape.
21. Create a java class shape with constructor toinitialize the one parameter
“dimension”.Nowcreatethreesubclassesofshapewiththefollowingmethods.
i) “Circle”withmethodtocalculatetheareaandcircumferenceofthecirclewithdimension as
radius.
ii) “Square”withmethodtocalculatetheareaandlengthofdiagonalofsquare.
iii)“Sphere” with method to calculate the volume and surface area.
CS3391 OBJECTORIENTEDPROGRAMMING

UNITIIIEXCEPTIONHANDLINGANDMULTITHREADING
ExceptionHandlingbasics–MultiplecatchClauses–NestedtryStatements–Java’sBuilt-inExceptions–User defined
Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication- Suspending –Resuming, and Stopping Threads –
Multithreading. Wrappers – Auto boxing.

1. Explainaboutexceptionhierarchy.
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Whenan Exceptionoccurs
thenormalflowoftheprogramisdisruptedandtheprogram/Applicationterminatesabnormally,which is not
recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
 Auserhasenteredaninvaliddata.
 Afilethatneedstobeopenedcannotbe found.
 Anetworkconnectionhasbeenlostinthe middleofcommunicationsortheJVMhasrunout
ofmemory.
 AJavaexceptionisanobjectthatdescribesanexceptional(thatis,error)conditionthathas
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
tohandletheexceptionitself,orpassiton.Eitherway,atsomepoint,theexceptionis caughtand
processed.
 Exceptions canbegenerated by theJavarun-timesystem,or theycanbemanuallygenerated by
your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the
Java language or the constraints of the Java execution environment. Manually generated
exceptions are typically used to report some error condition to the caller of a method.
 Javaexceptionhandlingismanagedviafivekeywords:
try,

catch,

throw,

throws,

finally.

 Programstatementsthatyouwanttomonitorforexceptionsarecontainedwithinatryblock.Ifan
exceptionoccurswithinthetryblock,itisthrown.Yourcodecancatchthisexception(using catch) and
handleitinsomerational manner.System-generated exceptions areautomatically thrown by the
Java run-time system.
 Tomanuallythrowanexception,usethekeywordthrow.Anyexceptionthatisthrownoutofa
method must bespecified as such by a throws clause.Any codethat absolutely must be executed
after a try block completes is put in a finally block.

EXCEPTIONHIERARCHY:
 Allexceptiontypesaresubclassesofthebuilt-inclassThrowable.Thus,
Throwableisatthetopoftheexceptionclasshierarchy.
 Immediately below Throwable are two subclasses that partition exceptions into two distinct
branches.
 OnebranchisheadedbyException.Thisclassisusedforexceptionalconditionsthatuserprograms
shouldcatch.Thisisalsotheclassthatyouwillsubclasstocreateyourowncustomexceptiontypes. There
is an important subclass of Exception, called RuntimeException. Exceptionsof thistype are
automatically defined for the programs that you write and include things such as division by zero
and invalid array indexing.

 Theother branch is topped by Error, which defines exceptions thatarenot expected to becaught
under normal circumstances by your program. Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the run-time environment, itself. Stack overflow
is an example of such an error.

USINGTRYANDCATCH:

AlthoughthedefaultexceptionhandlerprovidedbytheJavarun-timesystemisusefulfordebugging, you
will usually want to handle an exception yourself.

Exceptionhandlerprovidestwobenefits.
1) Itallowsyoutofixtheerror.
2) Itpreventstheprogramfromautomaticallyterminating.
Program:

classExc2
{
publicstaticvoidmain(Stringargs[])
{
intd,a;
try
{
d=0;
a=42 /d;
System.out.println("Thiswillnotbeprinted.");
}
catch(ArithmeticExceptione)
{
System.out.println("Divisionbyzero.");
}

System.out.println("Aftercatchstatement.");
}
}

Thisprogramgeneratesthefollowingoutput:Division by
zero.
Aftercatchstatement.

2. Explainaboutmultiplecatchclauses.
Insomecases,morethanoneexceptioncouldberaisedbyasinglepieceofcode.Tohandlethistypeof situation,
you can specify twoor more catch clauses, each catching a different type of exception. When
anexceptionisthrown,each catchstatementisinspectedinorder,andthefirstonewhosetypematches that of
the exception is executed. After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block. The following example traps two different exception
types:Demonstrate multiple catch statements.
classMultipleCatches
{
publicstaticvoidmain(Stringargs[])
{
try
{int a = 0;
System.out.println("a="+a);
int b = 42 / a;
intc[]={1};
c[42] = 99;
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+ e);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexoob:"+e);
}
System.out.println("Aftertry/catchblocks.");
}
}
Output:
a=0
Divideby0:java.lang.ArithmeticException:/byzero After
try/catch blocks.

3. Explainaboutnestedtrystatements.

Thetrystatementcanbenested.Thatis,atrystatementcanbeinsidetheblockofanothertry.Each
time a try statement is entered, the context of that exception is pushed on the stack. If an inner try
statementdoesnothaveacatchhandlerforaparticularexception,thestackisunwoundandthenext try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds,oruntilallofthenested trystatementsareexhausted.Ifno catchstatementmatches,thenthe Java
run-time system will handle the exception. Here is an example that uses nested try statements:

Anexampleofnestedtrystatements.class NestTry
{
publicstaticvoidmain(Stringargs[])
{
try{
inta=0;
int b = 42 / a;
System.out.println("a="+a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
intc[]={1}; c[42]
= 99;
}
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexout-of-bounds:"+e);
}
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+e);}}}
Thisprogramnestsonetryblockwithinanother.Theprogramworksasfollows.Whenyouexecutethe
program with no command-line arguments, a divide-by-zero exception is generated by the outer try
block.Executionoftheprogramwithonecommand-lineargumentgeneratesadivide-by-zeroexception
fromwithin thenested try block. Since the innerblockdoes notcatch thisexception, itispassed onto
theoutertryblock,whereitishandled.Ifyouexecutetheprogramwithtwocommand-linearguments, an array
boundary exception is generated from withinthe inner try block.

Output:
Divideby0:java.lang.ArithmeticException:/byzero
Outputwhena=1:
a=1
Divideby0:java.lang.ArithmeticException:/byzeroC:\>java NestTry
One Two
Outputwhena=2:
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

finally:
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a problem in some methods. For
example,ifamethodopensafileuponentryandclosesituponexit,thenyouwillnotwantthecodethat
closesthefiletobebypassedbytheexception-handlingmechanism.Thefinallykeywordisdesignedto
addressthiscontingency.
Finally creates a block of code that will be executed after a try /catch block has completed and before
the code following the try/catch block. The finally block will execute whether or not an exception is
thrown.If an exception isthrown,the finally block willexecuteeven ifno catch statementmatchesthe
exception.

4. Explainin detail aboutvarious typesofexception.

An exception is a problem that arises during the execution of a program. Whenan 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.

Twotypes ofexceptions are


 Built in exception
 Userdefined exception

1) BUILT-INEXCEPTIONS:
Inside the standard package java.lang, Java defines several exception classes. The mostgeneralof
exceptionsarethesubclassesofthestandardtypeRuntimeException. Theseexceptions
neednotbeincludedinanymethod's throws list.

i) CheckedException
Checkedexceptionsarecheckedatcompile-time.TheclasseswhichdirectlyinheritThrowableclass except
RuntimeException and Error are known as checked exceptions.
e.g.IOException,SQLExceptionetc.Checkedexceptionsarecheckedatcompile-time.

ii) UncheckedException
Uncheckedexceptionsarenotcheckedatcompile-time,buttheyarecheckedatruntime.Theclasses
whichinheritRuntimeExceptionareknownasuncheckedexceptions. Theseexceptionsneednotbe
included in any method's throws list.
ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExceptionetc.
Program:

classMultipleCatches
{
publicstaticvoidmain(Stringargs[])
{
try
{
inta=0;
System.out.println("a="+a);intb= 42 /
a;
intc[]={1}; c[42]
= 99;
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+ e);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexoob:"+e);
}
System.out.println("Aftertry/catchblocks.");
}
finally
{
System.out.println("Finallyblock");
}
}
Output:
C:\>javaMultipleCatchesa=0
Divideby0:java.lang.ArithmeticException:/byzero After
try/catch blocks.
Finallyblock

2) USERDEFINEDEXCEPTION:

User can create their own exception types to handle situations specific to user applications. This is quite
easy to do: just define a subclass of Exception .
The Exception class does not define any methods of its own. It inherits the methods provided by
Throwable.Thus,allexceptions,includingthosethatyoucreate,havethemethodsdefinedby Throwable
available to them.
Exceptiondefinesfourconstructors.Twosupportchainedexceptions.Theothertwoareshownhere:

Exception( )
Exception(Stringmsg)

Thefirstform createsan exception thathasno description.Thesecond form letsyou specify adescription of


the exception.

Program:

classMyExceptionextendsException
{
intdetail;MyException(int
a)
{
detail=a;
}
publicString toString()
{
return"MyException:"+detail;
}
}
classExceptionDemo
{
staticvoidcompute(inta)throwsMyException
{
System.out.println("Calledcompute”);
if(a > 10)
throw new MyException(a);
System.out.println("Normalexit");
}
publicstaticvoidmain(Stringargs[])
{
try
{
compute(1);
compute(20);
}
catch(MyExceptione)
{
System.out.println("Caught"+e);
}
}
}

Output:

Calledcompute(1)Normalexit
Called compute(20)
Caught
MyException[20]

5. Discussthelifecycleofthreadswithneatdiagram.
Answer:

 Threadisthesmallestunitofdispatchablecode.Thismeansthatasingleprogramcanperform
twoormoretaskssimultaneously.Forinstance,atexteditorcanformattextatthesametime that it
isprinting, as long asthesetwo actions arebeing performed by two separate threads.
 Threads are lighter weight. They share the same address space and cooperatively share the
sameheavyweightprocess.Interthreadcommunicationisinexpensive,andcontextswitching
from one thread to the next is lower in cost.
 Multithreading enables to write efficient programs that make maximum use of the
processingpoweravailableinthesystem.Multithreadingkeeptheidletimetoaminimum.
Threadsexistinseveral states.
1) Athreadcanbe running.ItcanbereadytorunassoonasitgetsCPUtime.
2) Arunningthreadcanbesuspended,whichtemporarilyhaltsitsactivity.
3) Asuspendedthreadcanthenbe resumed,allowingittopickupwhereitleft off.
4) Athreadcanbeblockedwhenwaitingforaresource.
5) At any time,a thread can beterminated, which haltsits execution immediately.
Onceterminated, a thread cannot be resumed.

ObtainingAThread’sState
Athreadcanexistinanumberofdifferentstates.Youcanobtainthecurrentstateofathread by
calling the getState( ) method defined by Thread. It is shown here:

Thread.StategetState()
It returns a value of type Thread.State that indicates the state of the thread at the time at
which the call was made. State is an enumeration defined by Thread.Here are the values
that can be returned by getState( ):

Value State
Athreadthathassuspendedexecutionbecauseitiswaiting to
BLOCKED acquire a lock.
NEW Athreadthathasnotbegunexecution.

Athreadthateitheriscurrentlyexecutingorwillexecute when it
RUNNABLE gains access to the CPU.

TERMINATED Athreadthathascompletedexecution.

Athreadthathassuspendedexecutionforaspecifiedperiod of
time, such as when it has called sleep( ). This state is also
TIMED_WAITING entered when a timeout version of wait( ) or join( ) is called.

A thread that has suspended execution because it is waiting


forsomeactiontooccur.Forexample,itiswaitingbecauseof a call
WAITING toa non-timeout version of wait( ) or join( ).

Given a Thread instance, you can use getState( ) to obtain the state of a thread. For
example,thefollowingsequencedeterminesifathreadcalledthrdisintheRUNNABLEstateatthe time
getState( ) is called:

Thread.Statets= thrd.getState();

if(ts==Thread.State.RUNNABLE)//...
It is important to understand that a thread’s state may change after the call to getState( ). Thus,
depending on the circumstances, the state obtained by calling getState( ) may not reflect the actual
state of the thread only a moment later. For this (and other) reasons, getState( ) is not intended to
provideameansofsynchronizingthreads.It’sprimarilyused fordebuggingorforprofilingathread’s run-
time characteristics.

6. DevelopaprogramforcreatingthreadsbyusingThreadclassandRunnableinterface.
(or)Whydoweneedbothstart()andrun()methodboth?canweachieveitwithonlyrun() method?

Answer:
We can call run() method if we want but then it would behave just like a normal method and we
would not be able to take the advantage of multithreading. When the run method gets called though
start()methodthenanewseparatethreadisbeingallocatedtotheexecutionofrunmethod,soifmore than one
thread calls start()methodthat means their run methodis being executedby separatethreads (these
threads run simultaneously).
Javadefinestwowaysinwhichthiscanbeaccomplished:
1) ByextendingtheThreadclass.
2) ByimplementtheRunnableinterface.

1. CreatingthreadbyusingThreadclass:
CreateanewclassthatextendsThread,andthencreateaninstanceofthatclass.Theextendingclass
mustoverridethe run()method,whichistheentrypointforthenewthread.Itmust also call start() to begin
execution of the new thread.

classmultithreadingextendsThread
{

publicvoidrun()

try
{

System.out.println("Thread"+Thread.currentThread().getId()+"is running");
}

catch(Exceptione)

{
System.out.println("Exceptioniscaught");

publicclassmultithreadingdemo
{

publicstaticvoidmain(String[]args)

multithreadingm1=newmultithreading();
multithreading m2=new multithreading();
m1.start();
m2.start();
}

Output:

Thread21isrunning
Thread22isrunning
2. CreatingthreadbyusingRunnableinterface:
TheeasiestwaytocreateathreadistocreateaclassthatimplementstheRunnableinterface. To
implement Runnable, a class need only implement a single method called run( ), which is
declared like this:

publicvoidrun()
Inside run( ), you will define the code that constitutes the new thread. It is important to
understandthatrun()cancallothermethods,useotherclasses,anddeclarevariables,justlikethe main
thread can. The only difference is that run( ) establishes the entry point for another, concurrent
thread of execution within your program. This thread will end when run( ) returns.
AfteryoucreateaclassthatimplementsRunnable,youwillinstantiateanobjectoftypeThread
fromwithinthatclass.Threaddefinesseveralconstructors.Theonethatwewilluseisshownhere:

Thread(RunnablethreadOb)

Thread(RunnablethreadOb,StringthreadName)
Thread(String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable


interface. This defines where executionof thethreadwill begin. The name ofthenew thread is
specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which
isdeclaredwithinThread.Inessence,start()executesacalltorun().Thestart()methodisshown here:

voidstart()

Hereisanexamplethatcreatesanewthreadandstartsitrunning:

classmultithreadingimplementsRunnable
{

publicvoidrun()

try

System.out.println("Thread"+Thread.currentThread().getId()+"is running");

catch(Exceptione)
{

System.out.println("Exceptioniscaught");

}
}

publicclassmultithreadingdemo

publicstaticvoidmain(String[]args)

multithreadingm1=newmultithreading();
Thread t1 = new Thread(m1);
multithreadingm2=newmultithreading();
Thread t2 = new Thread(m2);
t1.start();

t2.start();
}

Output:
Thread21isrunning
Thread22is running

3. Developajavaprogramthatprovide synchronizationfortwothreadsdepositandwithdraw in a
bank application.
(or)Whatisthreadsynchronization?Discusswithanexample. Answer:
Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethatthe
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization. Java provides unique, language-level support for it.

Thesynchronizationismainlyusedto
 Topreventthreadinterference.
 To prevent consistency problem.
Synchronizationcanbedoneintwoways:
1) UsingSynchronizedMethods
2) UsingsynchronizedStatementorsynchronizedblock

1) UsingSynchronizedMethods:

Synchronization is easy in Java, because all objects have their own implicit monitor associated with
them.Toenteranobject’smonitor,justcallamethodthathasbeenmodifiedwiththesynchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any
other synchronized method) on the same instance have to wait. To exit the monitor and

relinquish control of the object to the next waiting thread, the owner of the monitor simply returns
from the synchronized method.

Program:

classbank{
intamount=5000;

synchronizedvoidtransaction(intn,charc){ try
{

if(c=='d')

System.out.println("BeforedepositBalance="+amount); amount
=amount+n;
System.out.println("AfterdepositBalance="+amount);

elseif(c=='w'){
System.out.println("BeforewithdrawBalance="+amount);
amount=amount-n;

System.out.println("AfterwithdrawBalance="+amount);

Thread.sleep(400);
}

catch(Exceptione)

System.out.println(e);}

}
classdepositextendsThread

{
bank t;
deposit(bankx){
t=x;
}
public void run(){

t.transaction(4000,'d');

}
}

classwithdrawextendsThread{ bank
t;
withdraw(bankx){
t=x;
}
public void run(){
t.transaction(2000,'w');
}

publicclasstestsync{

publicstaticvoidmain(Stringargs[]){
bank obj = new bank();
depositt1=newdeposit(obj);
withdrawt2=newwithdraw(obj);
t1.start();
t2.start();

Output:
Before deposit Balance =5000
After deposit Balance =9000
BeforewithdrawBalance=9000
After withdraw Balance =7000
2) ThesynchronizedStatement:(synchronizedblock)

While creating synchronized methods within classes that you create is an easy and effective means
ofachievingsynchronization,itwillnotworkinallcases.Tounderstandwhy,considerthefollowing.
Imagine that you want to synchronize access to objects of a class that was not designed for
multithreaded access. That is, the class does not use synchronized methods.

Further,thisclasswasnotcreatedbyyou,butbyathirdparty, andyoudonothaveaccessto the


sourcecode.Thus,youcan’tadd synchronizedto theappropriatemethodswithintheclass.How can
access to anobject of this class be synchronized? Fortunately, the solutionto this problem is quite
easy: Yousimply put calls to the methods defined by this class inside a synchronized block.

Thisisthegeneralformofthesynchronizedstatement:
synchronized(object) {
//statementstobesynchronized

Here, object is a reference to the object being synchronized. A synchronized block ensures that a
call to a method that is a member of object occurs only after the current thread has successfully
entered object’s monitor.

Program:

classbank{

intamount=5000;

voidtransaction(intn,charc){
try

if(c=='d')

{
System.out.println("BeforedepositBalance="+amount); amount
=amount+n;
System.out.println("AfterdepositBalance="+amount);

elseif(c=='w'){

System.out.println("BeforewithdrawBalance="+amount);
amount = amount-n;
System.out.println("AfterwithdrawBalance="+amount);

}
Thread.sleep(400);

catch(Exceptione){System.out.println(e);}

classdepositextendsThread{ b
ank t;
deposit(bankx){
t=x;
}
publicvoidrun(){
synchronized(t)
{

t.transaction(4000,'d');
}

}
classwithdrawextendsThread{ bank
t;
withdraw(bankx){
t=x;
}

public void run(){


synchronized(t)
{ t.transaction(2000,'w');
}
}

publicclasstestsync{

publicstaticvoidmain(Stringargs[])
{ bank obj = new bank();
deposit t1=new deposit(obj);
withdrawt2=newwithdraw(obj);
t1.start();
t2.start();
}

Output:
Before deposit Balance =5000
After deposit Balance =9000
BeforewithdrawBalance=9000
After withdraw Balance =7000

4. Write a java program for inventory problem to illustrate the usage of thread synchronized
keywordandinterthreadcommunicationprocess.Theyhavethreeclassescalledconsumer,
producerand stock.
(Or)Explainaboutinterthreadcommunicationwithexampleprogram.

 Javaincludesan elegant interprocesscommunication mechanism viathewait( ),notify(),and


notifyAll( ) methods. Inter-thread communicationis all about allowing synchronized threads
to communicate with each other. These methods are implemented as final methods in Object,
soallclasseshavethem.Allthreemethodscanbecalledonlyfromwithinasynchronizedcontext.
wait()tellsthecallingthreadtogiveupthemonitorandgotosleepuntilsomeotherthread enters the same
monitor and calls notify( ).
notify()wakesupathreadthatcalledwait()onthesameobject.
notifyAll( ) wakes up all the threads that called wait() on the sameobject. Oneof the threads will be
granted access.

Consider the following sample program thatimplements a simple form of the producer/ consumer
problem.Itconsistsoffourclasses:Queue,thequeuethatyou’retryingtosynchronize;Producer,the
threaded object that is producing queue entries; Consumer, the threaded object that is consuming
queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

classQueue

intn;

booleanvalueSet= false;

synchronizedintget()
{
while(!valueSet)
try {
wait();

catch(InterruptedExceptione)
{

System.out.println("InterruptedExceptioncaught");

}
System.out.println("Got:"+n);
valueSet = false;
notify();
returnn;

synchronizedvoidput(intx)

{
while(valueSet)
try {
wait();

catch(InterruptedExceptione)
{

System.out.println("InterruptedExceptioncaught");

n= x;
valueSet = true;
System.out.println("Put:"+n);
notify();
}

classProducerextendsThread{ Que
ue q;
Producer(Queueq1){ q
= q1;
}
publicvoidrun()
{ int i = 0;
while(true) {
q.put(i++);
}
}

classConsumerextendsThread{ Que
ue q;
Consumer(Queueq1){ q
= q1;
}

publicvoidrun()
{ while(true) {
q.get();
}
}

publicclassPCFixed
{

publicstaticvoidmain(Stringargs[])

Queue q = new Queue();


Producer p=new Producer(q);
Consumerc=newConsumer(q);
p.start();
c.start();

System.out.println("PressControl-Ctostop.");
}

}
Output:

Put:1
Got:1

Put:2

Got:2

Put:3

Got:3

Put:4
Got:4

Put:5
Got:5

10. Explainaboutcreatingmultiplethreadsandthreadpriorities.

Theprogramcancreateasmanythreadsasitneeds. class

multithreading extends Thread

publicvoidrun()

try

System.out.println("Thread"+Thread.currentThread().getId()+"is running");

catch(Exceptione)

System.out.println("Exceptioniscaught");

}
}

publicclassmultithreadingdemo

publicstaticvoidmain(String[]args)

multithreadingm1=newmultithreading();

multithreadingm2=newmultithreading();

m1.start();

m2.start();

Output:

Thread21isrunning

Thread22isrunning

UsingisAlive()andjoin()

Oftenyouwillwantthemain threadtofinishlast.Thiscanbeaccomplishedbycallingsleep()withinmain(
),withalong enoughdelayto ensurethatallchildthreadsterminatepriortothemainthread.However,this
ishardlyasatisfactorysolution,anditalsoraisesalargerquestion:Howcanonethreadknowwhenanother thread
has ended? Fortunately, Thread provides a means by which you can answer this question.

Twowaysexisttodeterminewhetherathreadhasfinished.

1) First,youcancallisAlive()onthethread.Thismethodisdefinedby Thread,anditsgeneralformisshown here:


finalbooleanisAlive()

TheisAlive()methodreturnstrueifthethreaduponwhichitiscalledisstillrunning.Itreturnsfalse
otherwise.isAlive()isoccasionallyuseful.
2) Mostcommonlyusedmethodto waitforathreadtofinishiscalled join(),shownhere: final

void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.

classjointhreadextendsThread{ public

void run() {

try{

System.out.println(Thread.currentThread().getName());

Thread.sleep(100);

catch (InterruptedException e) {

System.out.println("Thread interrupted");

publicclassJoinExample{

publicstaticvoidmain(String[]args)

{ jointhread t1 = new jointhread();

jointhread t2 = new jointhread();

t1.start();

t2.start();

System.out.println("t1Alive-"+t1.isAlive());

System.out.println("t2Alive-"+t2.isAlive());

try{
t1.join();

t2.join();

catch (InterruptedException e) {

System.out.println("Thread interrupted");

System.out.println("t1Alive-"+t1.isAlive());

System.out.println("t2Alive-"+t2.isAlive());

System.out.println("Processing finished");

Output:

Thread-0
Thread-1
t1 Alive - true
t2 Alive - true
t1Alive-false
t2Alive-false
Processingfinished

THREADPRIORITIES:

 Thread priorities are used by the thread scheduler to decide when each thread should be allowed to
run. In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the
amount of CPU time that a thread gets often depends on several factors besides its priority. (For
example, how an operating system implements multitasking can affect the relative availability of CPU
time.)
 A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority
thread is runningand a higher-priority thread resumes (from sleeping or waiting on I/O,for example),
it will preempt the lower-priority thread.

Tosetathread’spriority,usethesetPriority()method,whichisamemberof Thread.

finalvoidsetPriority(intlevel)
Here, levelspecifies thenewpriority settingforthecallingthread.Thevalueof levelmust bewithin therange
MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to
default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final
variables within Thread.

Youcanobtainthecurrentprioritysettingbycallingthe getPriority()methodofThread,shownhere:

finalintgetPriority()

12. Explainaboutdeadlock.

 Deadlockoccurswhentwothreadshaveacirculardependencyonapairofsynchronizedobjects.
 Forexample,supposeonethreadentersthemonitoronobjectX andanotherthreadentersthemonitor on
object Y.
 If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the
thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to
accessX,itwouldhavetoreleaseitsownlockonYsothatthefirstthreadcouldcomplete.Deadlockis a difficult
error to debug for two reasons:
1) Ingeneral,itoccursonlyrarely,whenthetwothreadstime-sliceinjusttheright way.
2) Itmayinvolvemorethantwothreadsandtwosynchronizedobjects.

//OnlineJavaCompiler

//Usethiseditortowrite,compileandrunyourJavacodeonline

publicclassTestThread

static String r1 = "java";

staticStringr2="program";

public static void main(String args[])

{ ThreadDemo1T1=newThreadDemo1();

ThreadDemo2T2=newThreadDemo2();

T1.start();

T2.start();

}
staticclassThreadDemo1extendsThread

publicvoidrun()

synchronized(r1)

System.out.println("Thread1:Holdinglock1...");

System.out.println("Thread1:Waitingforlock2...");

synchronized(r2)

System.out.println("Thread1:Holdinglock1&2...");

staticclassThreadDemo2extendsThread

publicvoidrun()

synchronized(r2)

System.out.println("Thread2:Holdinglock2...");

System.out.println("Thread2:Waitingforlock1...");

synchronized(r1)

System.out.println("Thread2:Holdinglock1&2...");

}
}

}}

Output

Thread1:Holdinglock1...

Thread2:Holdinglock2...

Thread1:Waitingforlock2...

Thread2:Waitingforlock1...

As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the
firstconditions that you should check for.

13. Explainaboutsuspending,resuming,andstoppingthreads.

 stop()methodinThread–Thismethodterminatesthethreadexecution.
 suspend()methodin Thread–Ifyouwantto stop thethreadexecutionandstartitagainwhena certain event
occurs. ...
 resume()methodinThread–resume()methodworkswithsuspend()method.

 The mechanisms to suspend, stop, and resume threads differ between early versions of Java, such as
Java1.0,andmoremodernversions,beginningwithJava2.PriortoJava2,aprogramused suspend(),
resume(),andstop(),whicharemethodsdefinedbyThread,topause,restart,andstoptheexecution of a
thread. Although these methods seem to be a perfectly reasonable and convenient approach to
managing the execution of threads, they must not be used for new Java programs.

 Here’s why. The suspend( ) method of the Thread class was deprecated by Java 2 several years ago.
Thiswas donebecause suspend() cansometimescauseserioussystemfailures.Assumethatathread as
obtained locks on critical data structures. If that thread is suspended at that point, those locks are not
relinquished. Other threads that may be waiting for those resources can be deadlocked.
 Theresume() methodisalsodeprecated.Itdoesnotcauseproblems,butcannotbeusedwithoutthe
suspend() method as its counterpart. Thestop() methodofthe Thread class, too, wasdeprecated
byJava 2. This was done because this method can sometimes cause serious system failures.
 Assumethat a thread is writingto a critically important data structureand has completedonly part of
itschanges.Ifthatthreadisstoppedatthatpoint,thatdatastructuremightbeleftinacorruptedstate. The
trouble is that stop( ) causes any lock the calling thread holds to be released. Thus, the corrupted data
might be used by another thread that is waiting on the same lock.
 Becauseyoucan’tnowusethesuspend(),resume(),orstop()methodstocontrolathread,youmight be
thinking that no way exists to pause, restart, or terminate a thread.
 But, fortunately, this is not true. Instead, a thread must be designed so that the run( )
methodperiodically checks to determine whether that thread should suspend, resume, or stop its
ownexecution. This is accomplished by establishinga flagvariablethat indicates theexecution
stateofthe thread. As long as this flag is set to “running,” the run( ) method must continue to let the
thread execute.Ifthisvariableissetto“suspend,”thethreadmustpause.Ifitissetto“stop,”thethreadmust
terminate. Ofcourse,avarietyofwaysexistinwhichto writesuchcode,butthecentralthemewillbe the
same for all programs.
 Thefollowingexampleillustrateshowthe wait()andnotify()methodsthatareinheritedfrom Object can be
used to control the execution of a thread. Let us consider its operation. The NewThread class
containsabooleaninstancevariablenamedsuspendFlag,whichisusedtocontroltheexecutionofthe
thread.Itisinitializedtofalsebytheconstructor.Therun()methodcontainsasynchronizedstatement block
that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the
executionofthethread.Themysuspend()methodsetssuspendFlagtotrue.Themyresume()method sets
suspendFlag to false and invokes notify( ) to wakeup thethread. Finally, the main( ) method has been
modified to invoke the mysuspend( ) and myresume( ) methods.

classNewThreadimplementsRunnable

Stringname;

Thread t;

boolean suspendFlag;

NewThread(Stringthreadname)

name=threadname;

t = new Thread(this, name);

System.out.println("Newthread:"+t);

suspendFlag = false;

t.start();

publicvoidrun()

try

for(inti=3;i >0;i--)

System.out.println(name+":"+i);

Thread.sleep(200);

synchronized(this)

while(suspendFlag)

{
wait();

catch(InterruptedExceptione)

System.out.println(name+"interrupted.");

System.out.println(name+"exiting.");

voidmysuspend()

suspendFlag=true;

synchronizedvoidmyresume()

suspendFlag=false;

notify();

classSuspendResume

publicstaticvoidmain(Stringargs[])

NewThreadob1=newNewThread("One");

NewThreadob2=newNewThread("Two");

try

Thread.sleep(1000);

ob1.mysuspend();
System.out.println("SuspendingthreadOne");

Thread.sleep(1000);

ob1.myresume();

System.out.println("Resuming thread One");

ob2.mysuspend();

System.out.println("SuspendingthreadTwo");

Thread.sleep(1000);

ob2.myresume();

System.out.println("ResumingthreadTwo");

catch(InterruptedExceptione)

System.out.println("MainthreadInterrupted");

//waitforthreadstofinish try

System.out.println("Waitingforthreadstofinish."); ob1.t.join();

ob2.t.join();

catch(InterruptedExceptione)

System.out.println("MainthreadInterrupted");

System.out.println("Mainthreadexiting.");

Output:
Newthread:Thread[One,5,main]

Newthread:Thread[Two,5,main]

One: 3

Two:3

One:2

Two:2

One:1Two:1

One exiting.

Two exiting.

Suspending thread One

Resuming thread One

Suspending thread Two

Resuming thread Two

Waitingforthreadstofinish.

Main thread exiting.

14. Explainabouttypewrappersinjava.

Javausesprimitivetypes(alsocalledsimpletypes),suchasintordouble,toholdthebasicdatatypessupported
bythelanguage.Primitivetypes,ratherthanobjects,areusedforthesequantitiesforthesakeofperformance. Using
objects forthese values would add an unacceptable overhead to even the simplestof calculations. Thus, the
primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when you will need an object
representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the
standard data structures implemented by Java operate on objects, which means that you can’t use these data
structures to store primitive types. To handle these situations, Java provides type wrappers, which are classes
that encapsulate a primitive type within an object.

ThetypewrappersareDouble,Float,Long,Integer,Short,Byte,Character,andBoolean.Theseclassesoffera
widearrayofmethodsthatallowyoutofullyintegratetheprimitivetypesintoJava’sobjecthierarchy.

Character:

Character is a wrapper around a char. The constructor for Character is Character(char ch)

Here,chspecifiesthecharacterthatwillbewrappedbythe Characterobjectbeingcreated.
ToobtainthecharvaluecontainedinaCharacterobject,callcharValue(),shownhere:

charcharValue( )

Itreturnstheencapsulatedcharacter.

Boolean

Booleanisawrapperaroundbooleanvalues.Itdefinestheseconstructors:

Boolean(booleanboolValue)

Boolean(String boolString)

In thefirst version,boolValuemust beeithertrueor false.In thesecond version, ifboolStringcontainsthestring


“true”(inuppercaseorlowercase),thenthenew Booleanobjectwillbetrue.Otherwise,itwillbefalse. To

obtain a boolean value from a Boolean object, use booleanValue( ), shown here:

booleanbooleanValue()

Itreturnsthebooleanequivalentoftheinvokingobject.

TheNumericTypeWrappers

Byfar,themostcommonlyusedtypewrappersarethosethatrepresentnumericvalues.Theseare Byte,Short, Integer,


Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number
declaresmethodsthatreturnthevalueofanobjectineachofthedifferentnumberformats.Thesemethodsare shown
here:

byte byteValue( )

doubledoubleValue()

float floatValue( )

int intValue( )

longlongValue()

shortshortValue()
Forexample,doubleValue()returnsthevalueofanobjectasadouble,floatValue()returnsthevalueasafloat, and so
on. These methods are implemented by each of the numeric type wrappers.

Allofthenumerictypewrappersdefineconstructorsthatallowanobjecttobeconstructedfromagivenvalue, or a
string representation of that value. For example, here are the constructors defined for Integer:

Integer(int num)

Integer(Stringstr)

Ifstrdoesnotcontainavalidnumericvalue,thenaNumberFormatExceptionisthrown.Allofthetypewrappers
overridetoString().Itreturnsthehuman-readableformofthevaluecontainedwithinthewrapper.Thisallows
youtooutputthevaluebypassingatypewrapperobjectto println(),forexample,withouthavingtoconvertit
intoitsprimitivetype.Thefollowingprogramdemonstrateshowtouseanumerictypewrappertoencapsulate a value
and then extract that value.

//Demonstrateatypewrapper.

class Wrap {

publicstaticvoidmain(Stringargs[])

{ Integer iOb = new Integer(100);

inti= iOb.intValue();

System.out.println(i+""+iOb);//displays100 100

This program wraps the integer value 100 inside an Integer object called iOb. The program then obtains
thisvalue by calling intValue( ) and stores the result in i.

Theprocessofencapsulatingavaluewithinanobjectiscalled boxing.Thus,intheprogram, this line

boxes the value 100 into an Integer:

IntegeriOb=newInteger(100);

Theprocessofextractingavaluefromatypewrapperiscalled unboxing.Forexample,the program

unboxes the value in iOb with this statement:

inti= iOb.intValue();
Thesamegeneralprocedureusedbytheprecedingprogramtoboxandunboxvalueshasbeenemployedsince the
original version of Java. However, with the release of JDK 5, Java

fundamentallyimprovedonthisthroughtheadditionofautoboxing,describednext.

15. Explainaboutautoboxingandunboxing.

BeginningwithJDK5,Javaaddedtwoimportantfeatures:

autoboxingandauto-unboxing.

Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object.

Auto-unboxing is theprocessby which thevalueofa boxed object is automatically extracted (unboxed) froma
typewrapperwhenitsvalueisneeded.Thereisnoneedtocallamethodsuchas intValue()ordoubleValue().

The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms, removing
thetediumofmanuallyboxingandunboxingvalues.Italsohelpsprevent errors.Moreover,itisveryimportant
togenerics,whichoperatesonlyonobjects.Finally,autoboxingmakesworkingwiththeCollectionsFramework much
easier.

Withautoboxingitisnolongernecessarytomanuallyconstructanobjectinordertowrapaprimitivetype.You need
only assign that value to a type-wrapper reference. Java automatically constructs the object for you. For
example, here is the modern way to construct an Integer object that has the value 100:

IntegeriOb=100; //autoboxanint

Noticethatnoobjectisexplicitlycreatedthroughtheuseofnew.Javahandlesthisforyou,automatically.

Tounboxanobject,simplyassignthatobjectreferencetoaprimitive-typevariable.Forexample,tounboxiOb, you can


use this line:

inti=iOb; //auto-unbox

Javahandlesthedetailsforyou.

Hereistheprecedingprogramrewrittentouseautoboxing/unboxing:

//Demonstrateautoboxing/unboxing.

classAutoBox
{

publicstaticvoidmain(Stringargs[])

IntegeriOb=100;//autoboxanint int i

= iOb; // auto-unbox

System.out.println(i+""+iOb); //displays100 100

Autoboxing/UnboxingBooleanandCharacterValues

Javaalso supplieswrappersforbooleanandchar.TheseareBooleanandCharacter. Autoboxing/unboxing applies


to these wrappers, too. For example, consider the following program:

//Autoboxing/unboxingaBooleanandCharacter.

classAutoBox5

publicstaticvoidmain(Stringargs[])

Booleanb=true;

if(b)

System.out.println("bistrue");

Characterch='x'; //boxachar

charch2=ch; //unboxachar

System.out.println("ch2is"+ch2);

Theoutputisshownhere: b

is true

ch2isx
CS3391/OBJECTORIENTEDPROGRAMMING

Unit-III

Part-A

1. Whatisanexception?
Exceptionisanabnormalconditionwhichoccursduringtheexecutionofaprogramanddisruptsnormalflowof
theprogram.Thisexceptionmustbehandledproperly.Ifitisnothandled,programwillbeterminatedabruptly.

2. Howtheexceptionsarehandledinjava?ORExplainexceptionhandlingmechanisminjava?
Exceptionsinjavaarehandledusingtry,catchandfinallyblocks.

tryblock:Thecodeorsetofstatementswhicharetobemonitoredforexceptionarekeptinthisblock. catch block :

This block catches the exceptions occurred in the try block.

finallyblock:Thisblockisalwaysexecutedwhetherexceptionisoccurredinthetryblockornotandoccurred exception
is caught in the catch block or not.

3. Whatisthedifferencebetweenerrorandexceptioninjava?
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused by the
application itself. For example, NullPointerException occurs when an application tries to access null object.

4. Canwewriteonlytryblockwithoutcatchandfinallyblocks?
No,Itshowscompilationerror.Thetryblockmustbefollowedbyeithercatchorfinally block. You can

remove either catch block or finally block but not both.

5. Whatisunreachablecatchblockerror?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most
generalones.i.esub classes ofException must comefirst and superclasseslater.Ifyoukeep superclassesfirst and
sub classes later, compiler will show unreachable catch block error.

6. Describethehierarchyofexceptionsinjava?
Allexceptiontypesaresubclassesofthebuilt-inclassThrowable.Thus,Throwableisatthetopofthe exception class
hierarchy.

ImmediatelybelowThrowablearetwosubclassesthatpartitionexceptionsintotwodistinctbranches.

OnebranchisheadedbyException.Thisclassisusedforexceptionalconditionsthatuserprogramsshouldcatch. This is
also the class that you will subclass to create your own custom exception types. There is an important subclass
of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that
you write and include things such as division by zero and invalid array indexing.
TheotherbranchistoppedbyError,whichdefinesexceptionsthatarenotexpectedtobecaughtundernormal
circumstancesbyyourprogram.ExceptionsoftypeErrorareusedbytheJavarun-timesystemtoindicateerrors having
to do with the run-time environment, itself. Stack overflow is an example of such an error.

7. Whatareruntimeexceptionsinjava.Giveexample?
The exceptions which occur at run time are called as run time exceptions. These exceptions are unknown to
compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run time exceptions. These
exceptions are unchecked type of exceptions. For example, NumberFormatException, NullPointerException,
ClassCastException,

8. Whatarecheckedanduncheckedexceptionsinjava?
Checkedexceptionsaretheexceptionswhichareknowntocompiler.Theseexceptionsarecheckedatcompile time
only. Hence the name checked exceptions. These exceptions are also called compile time exceptions. Because,
these exceptions will be known during compile time.

Uncheckedexceptionsarethoseexceptionswhicharenotatallknowntocompiler.Theseexceptionsoccuronly at run
time. These exceptions are also called as run time exceptions. All sub classes of java.lang.RunTimeException
and java.lang.Error are unchecked exceptions.

9. WhatisRe-throwinganexceptioninjava?
Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can
re-throw that exception using throw keyword. It is called re-throwing an exception.

10. Whatistheuseofthrowskeywordinjava?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that
callers ofthe method can guard themselves against that exception. You do this by including a throws clausein
the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is
necessaryforallexceptions,exceptthoseoftypeErrororRuntimeException,oranyoftheirsubclasses.Allother
exceptionsthatamethodcanthrowmustbedeclaredinthethrowsclause.Iftheyarenot,acompile-timeerror will
result.

11. Whatisthedifferencebetweenfinal,finallyandfinalizeinjava? final


keyword :

finalisakeywordwhichisusedtomakeavariableoramethodoraclassas“unchangeable“.

finallyBlock:

finally is a block which is used for exception handling along with try and catch blocks. finally block is always
executed whether exception is raised or not and raised exception is handled or not. Most of time, this block is
used to close the resources like database connection, I/O resources etc.

finalize()Method:

finalize()methodisaprotectedmethodofjava.lang.Objectclass.Itisinheritedtoeveryclassyoucreateinjava. This
method is called by garbage collector thread before an object is removed from the memory. finalize() method
is used to perform some clean up operations on an object before it is removed from the memory.

12. Howdoyoucreatecustomizedexceptionsinjava?
In java, we can define our own exception classes as per our requirements. These exceptions are called user
defined exceptions in java OR Customized exceptions. User defined exceptions must extend any one of the
classes in the hierarchy of exceptions.

13. Whatisthedifferencebetweenthrow,throwsandthrowableinjava?
throw In Java :

throwis a keyword in java which is used to throwan exception manually.Usingthrowkeyword, you can throw
anexceptionfromanymethodorblock.But,thatexceptionmustbeoftypejava.lang.Throwableclassorit’ssub classes.
Below example shows how to throw an exception using throw keyword.

throwsInJava:

throws is also a keyword in java which is used in the method signature to indicate that this method may throw
mentionedexceptions.Thecallertosuchmethodsmusthandlethementionedexceptionseitherusingtry-catch blocks
or using throws keyword. Below is the syntax for using throws keyword.

ThrowableInJava:

Throwable is a super class for all types of errors and exceptions in java. This class is a member of
java.langpackage.Onlyinstancesofthisclassorit’ssubclassesarethrownbythejavavirtualmachineorbythe
throwstatement.Theonlyargumentofcatchblockmustbeofthistypeorit’ssubclasses.Ifyouwanttocreate your own
customized exceptions, then your class must extend this class. Click hereto see the hierarchy of exception
classes in java.

15. Whichclassisthesuperclassforalltypesoferrorsandexceptionsinjava?
java.lang.Throwableisthesuperclassforalltypesoferrorsandexceptionsinjava.

16. DefineProcess-basedmultitasking:(Multiprocessing)
A process is a program that is executing. Thus, process-based multitasking is the feature that allows your
computerto run twoor more programs concurrently.For example, process-based multitaskingenables you to
run the Java compiler at the same time that you are using a text editor or visiting a web site. In process-based
multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

17. DefineThread-basedmultitasking:(Multithreading)
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means
thatasingleprogramcanperformtwoormoretaskssimultaneously.Forinstance,atexteditorcanformattext at
thesame time that it is printing, as long as these two actions arebeing performed by two separate threads.
Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the
details.

18. Differentiatebetweenmultitaskingandmultithreading.
Sl.n Multitasking Multithreading
o.

1 Itisaprocessofexecutingmanyprocesses Itisaprocessofexecutingmultiplethreads(sub-
running simultaneously. process).

2 Processisprograminexecution.Theyare Threadisbasicallyalightweightsub-process.Itisa
Heavy weight. smallest unit of processing.
3 Inmultitaskingseparatememoryis allocated Threads(sub-process)aresharingcommon memory.
to each process.

4 Interprocesscommunicationisexpensive Interthreadcommunicationisinexpensive.

5 Contextswitchingfromoneprocessto Contextswitchingfromonethreadtoanotheris
another is costly. inexpensive.

19. DefineMultithreading.
Multithreadingenablestowriteefficientprogramsthatmakemaximumuseoftheprocessingpoweravailable in the
system. One important way multithreading achieves this is by keeping idle time to a minimum.

20. ListaretheStatesofthread.
 Athreadcanberunning.ItcanbereadytorunassoonasitgetsCPUtime.
 Arunningthreadcanbesuspended,whichtemporarilyhaltsitsactivity.
 Asuspendedthreadcanthenberesumed,allowingittopickupwhereitleft off.
 Athreadcanbeblockedwhenwaitingforaresource.
 Atanytime,a threadcanbe terminated,whichhaltsitsexecutionimmediately.Onceterminated, a
thread cannot be resumed.
21. HowcanyoucreatethreadinJava?
Javadefinestwowaysforcreatingthread.
1) ByextendingtheThreadclass.
2) ByimplementtheRunnableinterface.

22. Whatdoyoumeanbysynchronization?
Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethattheresource will
beused by only onethread at a time. Theprocess by which this is achieved is called synchronization. Java
provides unique, language-level support for it.

Synchronizationcanbedoneintwoways:

1) UsingSynchronizedMethods
2) UsingsynchronizedStatementorsynchronizedblock

23. Whatistheneedforsynchronization?
Thesynchronizationismainlyusedto

 Topreventthreadinterference.
 Topreventconsistencyproblem.

24. Whatismeantbymonitor?
A monitor isan object that isused as amutually exclusivelock. Only onethread can owna monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are
saidtobewaitingforthemonitor.Athreadthatownsamonitorcanreenterthesamemonitorifitsodesires.

25. Howwillyousetthepriorityofthethread?
Threadprioritiesareusedbythethreadschedulertodecidewheneachthreadshouldbeallowedto run. In
theory, higher-priority threads get more CPU time than lower-priority threads.

Tosetathread’spriority,usethesetPriority()method.
finalvoidsetPriority(intlevel)

Thevalueof level must bewithin therange MIN_PRIORITY and MAX_PRIORITY. Currently, these
valuesare1and10,respectively.Toreturnathreadtodefaultpriority,specify NORM_PRIORITY, which
is currently 5.

Part-B

1. Developajavaprogramforhandlingdividebyzeroexceptionwithmultiplecatches.
2. DevelopajavaprogramforhandlingArrayIndexOutOfBoundsExceptionexception
with finally block.

3. Developajavaprogramforexceptionhandlingwiththrowandthrowskeyword.
4. Explainnestedtry/catchwithexampleprogram.
5. Developajavaprogramwithmultiplecatchclauses.
6. DevelopajavaprogramwithmulticatchthatcanhandlebothArithmeticException and
IndexOutOfBoundsException.

7. Discussaboutexceptionhandlinginnestedtry/catch.
8. Explainabouttypesofexceptionwithanexample.
9. DevelopaJavaprogramtoimplementuserdefinedexceptionhandling.
10. Discussthelifecycleofthreadswithneatdiagram.
11. DevelopaprogramforcreatingthreadsbyusingThreadclassandRunnableinterface.
12. Whydoweneedbothstart()andrun()methodboth?canweachieveitwithonlyrun()method?
13. Writeajavaprogramthatsynchronizethreethreadsofthesameprogramanddisplaythecontent the text
supplied through these threads.
14. Developajavaprogramthatprovidesynchronizationfortwothreadsdepositandwithdrawinabank
application.
15. Definethread.Explainthestateofthreads.Statereasonforsynchronizationinthread. Write
simple concurrent programming to create, sleep and delete thread.
16. Whatisthreadsynchronization?Discusswithanexample.
17. Writeajavaprogramforinventoryproblemtoillustratetheusageofthreadsynchronizedkeyword and
interthread communication process. They have three classes called consumer, producerand stock.
18. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, second thread computes
thesquareofthenumberandprints.Ifthevalueisodd,the thirdthreadwillprintthevalueofcubeof the
number.
19. Developajavaapplicationprogramforgeneratingfourthreadstoperformthefollowingoperation.
i) GettingNnumbersasinput
ii) Printingevennumbers
iii) Printingoddnumbers.
iv) Computingtheaverage
20. Explainaboutwrapperclasses.
21. Elaborateindetailaboutautoboxing.
22. DiscussaboutSuspending,Resuming,andStoppingThreads.
CS3391 OBJECTORIENTEDPROGRAMMING

UNITIIIEXCEPTIONHANDLINGANDMULTITHREADING
ExceptionHandlingbasics–MultiplecatchClauses–NestedtryStatements–Java’sBuilt-inExceptions–User defined
Exception. Multithreaded Programming: Java Thread Model–Creating a Thread and Multiple Threads –
Priorities – Synchronization – Inter Thread Communication- Suspending –Resuming, and Stopping Threads –
Multithreading. Wrappers – Auto boxing.
7. Explainaboutexceptionhierarchy.
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.Whenan Exceptionoccurs
thenormalflowoftheprogramisdisruptedandtheprogram/Applicationterminatesabnormally,which is not
recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
 Auserhasenteredaninvaliddata.
 Afilethatneedstobeopenedcannotbe found.
 Anetworkconnectionhasbeenlostinthe middleofcommunicationsortheJVMhasrunout
ofmemory.
 AJavaexceptionisanobjectthatdescribesanexceptional(thatis,error)conditionthathas
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
tohandletheexceptionitself,orpassiton.Eitherway,atsomepoint,theexceptionis caughtand
processed.
 Exceptions canbegenerated by theJavarun-timesystem,or theycanbemanuallygenerated by
your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the
Java language or the constraints of the Java execution environment. Manually generated
exceptions are typically used to report some error condition to the caller of a method.
 Javaexceptionhandlingismanagedviafivekeywords:
try,

catch,

throw,

throws,

finally.

 Programstatementsthatyouwanttomonitorforexceptionsarecontainedwithinatryblock.Ifan
exceptionoccurswithinthetryblock,itisthrown.Yourcodecancatchthisexception(using catch) and
handleitinsomerational manner.System-generated exceptions areautomatically thrown by the
Java run-time system.
 Tomanuallythrowanexception,usethekeywordthrow.Anyexceptionthatisthrownoutofa
method must bespecified as such by a throws clause.Any codethat absolutely must be executed
after a try block completes is put in a finally block.

EXCEPTIONHIERARCHY:
 Allexceptiontypesaresubclassesofthebuilt-inclassThrowable.Thus,
Throwableisatthetopoftheexceptionclasshierarchy.
 Immediately below Throwable are two subclasses that partition exceptions into two distinct
branches.
 OnebranchisheadedbyException.Thisclassisusedforexceptionalconditionsthatuserprograms
shouldcatch.Thisisalsotheclassthatyouwillsubclasstocreateyourowncustomexceptiontypes. There
is an important subclass of Exception, called RuntimeException. Exceptionsof thistype are
automatically defined for the programs that you write and include things such as division by zero
and invalid array indexing.

 Theother branch is topped by Error, which defines exceptions thatarenot expected to becaught
under normal circumstances by your program. Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the run-time environment, itself. Stack overflow
is an example of such an error.

USINGTRYANDCATCH:

AlthoughthedefaultexceptionhandlerprovidedbytheJavarun-timesystemisusefulfordebugging, you
will usually want to handle an exception yourself.

Exceptionhandlerprovidestwobenefits.
3) Itallowsyoutofixtheerror.
4) Itpreventstheprogramfromautomaticallyterminating.
Program:

classExc2
{
publicstaticvoidmain(Stringargs[])
{
intd,a;
try
{
d=0;
a=42 /d;
System.out.println("Thiswillnotbeprinted.");
}
catch(ArithmeticExceptione)
{
System.out.println("Divisionbyzero.");
}

System.out.println("Aftercatchstatement.");
}
}

Thisprogramgeneratesthefollowingoutput:Division by
zero.
Aftercatchstatement.

8. Explainaboutmultiplecatchclauses.
Insomecases,morethanoneexceptioncouldberaisedbyasinglepieceofcode.Tohandlethistypeof situation,
you can specify twoor more catch clauses, each catching a different type of exception. When
anexceptionisthrown,each catchstatementisinspectedinorder,andthefirstonewhosetypematches that of
the exception is executed. After one catch statement executes, the others are bypassed, and execution
continues after the try / catch block. The following example traps two different exception
types:Demonstrate multiple catch statements.
classMultipleCatches
{
publicstaticvoidmain(Stringargs[])
{
try
{int a = 0;
System.out.println("a="+a);
int b = 42 / a;
intc[]={1};
c[42] = 99;
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+ e);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexoob:"+e);
}
System.out.println("Aftertry/catchblocks.");
}
}
Output:
a=0
Divideby0:java.lang.ArithmeticException:/byzero After
try/catch blocks.

9. Explainaboutnestedtrystatements.

The try statement can be nested. That is, a try statement can be inside the block of another try. Each
timeatrystatementisentered,thecontextofthatexceptionispushedonthestack.Ifaninnertry
statementdoesnothaveacatchhandlerforaparticularexception,thestackisunwoundandthenext try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds,oruntilallofthenested trystatementsareexhausted.Ifno catchstatementmatches,thenthe Java
run-time system will handle the exception. Here is an example that uses nested try statements:

Anexampleofnestedtrystatements.class NestTry
{
publicstaticvoidmain(Stringargs[])
{
try{
inta=0;
int b = 42 / a;
System.out.println("a="+a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
intc[]={1}; c[42]
= 99;
}
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexout-of-bounds:"+e);
}
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+e);}}}
Thisprogramnestsonetryblockwithinanother.Theprogramworksasfollows.Whenyouexecutethe
program with no command-line arguments, a divide-by-zero exception is generated by the outer try
block.Executionoftheprogramwithonecommand-lineargumentgeneratesadivide-by-zeroexception
fromwithin thenested try block. Since the innerblockdoes notcatch thisexception, itispassed onto
theoutertryblock,whereitishandled.Ifyouexecutetheprogramwithtwocommand-linearguments, an array
boundary exception is generated from withinthe inner try block.

Output:
Divideby0:java.lang.ArithmeticException:/byzero
Outputwhena=1:
a=1
Divideby0:java.lang.ArithmeticException:/byzeroC:\>java NestTry
One Two
Outputwhena=2:
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

finally:
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a problem in some methods. For
example,ifamethodopensafileuponentryandclosesituponexit,thenyouwillnotwantthecodethat
closesthefiletobebypassedbytheexception-handlingmechanism.Thefinallykeywordisdesignedto address
this contingency.
Finally creates a block of code that will be executed after a try /catch block has completed and before
the code following the try/catch block. The finally block will execute whether or not an exception is
thrown.If an exception isthrown,the finally block willexecuteeven ifno catch statementmatchesthe
exception.

10. Explainin detail aboutvarious typesofexception.

An exception is a problem that arises during the execution of a program. Whenan 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.

Twotypes ofexceptions are


 Built in exception
 Userdefined exception

3) BUILT-INEXCEPTIONS:
Inside the standard package java.lang, Java defines several exception classes. The mostgeneralof
exceptionsarethesubclassesofthestandardtypeRuntimeException. Theseexceptions
neednotbeincludedinanymethod's throws list.

iii) CheckedException
Checkedexceptionsarecheckedatcompile-time.TheclasseswhichdirectlyinheritThrowableclass except
RuntimeException and Error are known as checked exceptions.
e.g.IOException,SQLExceptionetc.Checkedexceptionsarecheckedatcompile-time.

iv) UncheckedException
Uncheckedexceptionsarenotcheckedatcompile-time,buttheyarecheckedatruntime.Theclasses
whichinheritRuntimeExceptionareknownasuncheckedexceptions. Theseexceptionsneednotbe
included in any method's throws list.
ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExceptionetc.

Program:
classMultipleCatches
{
publicstaticvoidmain(Stringargs[])
{
try
{
inta=0;
System.out.println("a="+a);intb= 42 /
a;
intc[]={1}; c[42]
= 99;
}
catch(ArithmeticExceptione)
{
System.out.println("Divideby0:"+ e);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("Arrayindexoob:"+e);
}
System.out.println("Aftertry/catchblocks.");
}
finally
{
System.out.println("Finallyblock");
}
}
Output:
C:\>javaMultipleCatchesa=0
Divideby0:java.lang.ArithmeticException:/byzero After
try/catch blocks.
Finallyblock

4) USERDEFINEDEXCEPTION:

User can create their own exception types to handle situations specific to user applications. This is quite
easy to do: just define a subclass of Exception .
The Exception class does not define any methods of its own. It inherits the methods provided by
Throwable.Thus,allexceptions,includingthosethatyoucreate,havethemethodsdefinedby Throwable
available to them.
Exceptiondefinesfourconstructors.Twosupportchainedexceptions.Theothertwoareshownhere:

Exception( )
Exception(Stringmsg)

Thefirstform createsan exception thathasno description.Thesecond form letsyou specify adescription of


the exception.

Program:

classMyExceptionextendsException
{
intdetail;MyException(int
a)
{
detail=a;
}
publicString toString()
{
return"MyException:"+detail;
}
}
classExceptionDemo
{
staticvoidcompute(inta)throwsMyException
{
System.out.println("Calledcompute”);
if(a > 10)
throw new MyException(a);
System.out.println("Normalexit");
}
publicstaticvoidmain(Stringargs[])
{
try
{
compute(1);
compute(20);
}
catch(MyExceptione)
{
System.out.println("Caught"+e);
}
}
}

Output:

Calledcompute(1)Normalexit
Called compute(20)
Caught
MyException[20]

11. Discussthelifecycleofthreadswithneatdiagram.
Answer:

 Threadisthesmallestunitofdispatchablecode.Thismeansthatasingleprogramcanperform
twoormoretaskssimultaneously.Forinstance,atexteditorcanformattextatthesametime that it
isprinting, as long asthesetwo actions arebeing performed by two separate threads.
 Threads are lighter weight. They share the same address space and cooperatively share the
sameheavyweightprocess.Interthreadcommunicationisinexpensive,andcontextswitching
from one thread to the next is lower in cost.
 Multithreading enables to write efficient programs that make maximum use of the
processingpoweravailableinthesystem.Multithreadingkeeptheidletimetoaminimum.
Threadsexistinseveral states.
6) Athreadcanbe running.ItcanbereadytorunassoonasitgetsCPUtime.
7) Arunningthreadcanbesuspended,whichtemporarilyhaltsitsactivity.
8) Asuspendedthreadcanthenbe resumed,allowingittopickupwhereitleft off.
9) Athreadcanbeblockedwhenwaitingforaresource.
10) At any time,a thread can beterminated, which haltsits execution immediately.
Onceterminated, a thread cannot be resumed.

ObtainingAThread’sState
Athreadcanexistinanumberofdifferentstates.Youcanobtainthecurrentstateofathread by
calling the getState( ) method defined by Thread. It is shown here:

Thread.StategetState()
It returns a value of type Thread.State that indicates the state of the thread at the time at
which the call was made. State is an enumeration defined by Thread.Here are the values
that can be returned by getState( ):

Value State
Athreadthathassuspendedexecutionbecauseitiswaiting to
BLOCKED acquire a lock.

NEW Athreadthathasnotbegunexecution.
Athreadthateitheriscurrentlyexecutingorwillexecute when it
RUNNABLE gains access to the CPU.

TERMINATED Athreadthathascompletedexecution.

Athreadthathassuspendedexecutionforaspecifiedperiod of
time, such as when it has called sleep( ). This state is also
TIMED_WAITING entered when a timeout version of wait( ) or join( ) is called.

A thread that has suspended execution because it is waiting


forsomeactiontooccur.Forexample,itiswaitingbecauseof a call
WAITING toa non-timeout version of wait( ) or join( ).

Given a Thread instance, you can use getState( ) to obtain the state of a thread. For
example,thefollowingsequencedeterminesifathreadcalledthrdisintheRUNNABLEstateatthe time
getState( ) is called:

Thread.Statets= thrd.getState();

if(ts==Thread.State.RUNNABLE)//...
It is important to understand that a thread’s state may change after the call to getState( ). Thus,
depending on the circumstances, the state obtained by calling getState( ) may not reflect the actual
state of the thread only a moment later. For this (and other) reasons, getState( ) is not intended to
provideameansofsynchronizingthreads.It’sprimarilyused fordebuggingorforprofilingathread’s run-
time characteristics.

12. DevelopaprogramforcreatingthreadsbyusingThreadclassandRunnableinterface.
(or)Whydoweneedbothstart()andrun()methodboth?canweachieveitwithonlyrun() method?

Answer:
We can call run() method if we want but then it would behave just like a normal method and we
would not be able to take the advantage of multithreading. When the run method gets called though
start()methodthenanewseparatethreadisbeingallocatedtotheexecutionofrunmethod,soifmore than one
thread calls start()methodthat means their run methodis being executedby separatethreads (these
threads run simultaneously).
Javadefinestwowaysinwhichthiscanbeaccomplished:
1) ByextendingtheThreadclass.
2) ByimplementtheRunnableinterface.

2.CreatingthreadbyusingThreadclass:
CreateanewclassthatextendsThread,andthencreateaninstanceofthatclass.Theextendingclass
mustoverridethe run()method,whichistheentrypointforthenewthread.Itmust also call start() to begin
execution of the new thread.

classmultithreadingextendsThread

{
publicvoidrun()

try

{
System.out.println("Thread"+Thread.currentThread().getId()+" is

running");

catch(Exceptione)

System.out.println("Exceptioniscaught");
}

}
}

publicclassmultithreadingdemo

publicstaticvoidmain(String[]args)
{

multithreadingm1=newmultithreading();
multithreading m2=new multithreading();
m1.start();
m2.start();
}

Output:

Thread21isrunning
Thread22isrunning
5. CreatingthreadbyusingRunnableinterface:

TheeasiestwaytocreateathreadistocreateaclassthatimplementstheRunnableinterface. To
implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
publicvoidrun()
Inside run( ), you will define the code that constitutes the new thread. It is important to
understandthatrun()cancallothermethods,useotherclasses,anddeclarevariables,justlikethe main
thread can. The only difference is that run( ) establishes the entry point for another, concurrent
thread of execution within your program. This thread will end when run( ) returns.

AfteryoucreateaclassthatimplementsRunnable,youwillinstantiateanobjectoftypeThread
fromwithinthatclass.Threaddefinesseveralconstructors.Theonethatwewilluseisshownhere:

Thread(RunnablethreadOb)

Thread(RunnablethreadOb,StringthreadName)
Thread(String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable


interface. This defines where executionof thethreadwill begin. The name ofthenew thread is
specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which
isdeclaredwithinThread.Inessence,start()executesacalltorun().Thestart()methodisshown here:

voidstart()

Hereisanexamplethatcreatesanewthreadandstartsitrunning:

classmultithreadingimplementsRunnable

publicvoidrun()

{
try

System.out.println("Thread"+Thread.currentThread().getId()+"is running");

catch(Exceptione)

System.out.println("Exceptioniscaught");
}

publicclassmultithreadingdemo
{

publicstaticvoidmain(String[]args)

multithreadingm1=newmultithreading();

Thread t1 = new Thread(m1);


multithreading m2=new multithreading();
Thread t2 = new Thread(m2);
t1.start();
t2.start();

Output:
Thread21isrunning
Thread22is running

6. Developajavaprogramthatprovide synchronizationfortwothreadsdepositandwithdraw in a
bank application.
(or)Whatisthreadsynchronization?Discusswithanexample. Answer:
Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethatthe
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization. Java provides unique, language-level support for it.

Thesynchronizationismainlyusedto
 Topreventthreadinterference.
 To prevent consistency problem.
Synchronizationcanbedoneintwoways:

3) UsingSynchronizedMethods
4) UsingsynchronizedStatementorsynchronizedblock

1) UsingSynchronizedMethods:

Synchronization is easy in Java, because all objects have their own implicit monitor associated with
them.Toenteranobject’smonitor,justcallamethodthathasbeenmodifiedwiththesynchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any
other synchronized method) on the same instance have to wait. To exit the monitor and

relinquish control of the object to the next waiting thread, the owner of the monitor simply returns
from the synchronized method.

Program:

classbank{
intamount=5000;

synchronizedvoidtransaction(intn,charc){

try

{
if(c=='d')

System.out.println("BeforedepositBalance="+amount); amount
=amount+n;
System.out.println("AfterdepositBalance="+amount);
}

elseif(c=='w'){

System.out.println("BeforewithdrawBalance="+amount);
amount = amount-n;
System.out.println("AfterwithdrawBalance="+amount);

Thread.sleep(400);

}
catch(Exceptione)

System.out.println(e);}

classdepositextendsThread
{

bank t;
deposit(bankx){
t=x;
}
public void run(){
t.transaction(4000,'d');
}
}

classwithdrawextendsThread{ bank
t;
withdraw(bankx){
t=x;
}
public void run(){
t.transaction(2000,'w');
}

publicclasstestsync{
publicstaticvoidmain(Stringargs[])
{ bank obj = new bank();
deposit t1=new deposit(obj);
withdrawt2=newwithdraw(obj);
t1.start();
t2.start();
}

Output:
Before deposit Balance =5000
After deposit Balance =9000
BeforewithdrawBalance=9000
After withdraw Balance =7000
2) ThesynchronizedStatement:(synchronizedblock)

While creating synchronized methods within classes that you create is an easy and effective means
ofachievingsynchronization,itwillnotworkinallcases.Tounderstandwhy,considerthefollowing.
Imagine that you want to synchronize access to objects of a class that was not designed for
multithreaded access. That is, the class does not use synchronized methods.

Further,thisclasswasnotcreatedbyyou,butbyathirdparty, andyoudonothaveaccessto the


sourcecode.Thus,youcan’tadd synchronizedto theappropriatemethodswithintheclass.How can
access to anobject of this class be synchronized? Fortunately, the solutionto this problem is quite
easy: Yousimply put calls to the methods defined by this class inside a synchronized block.

Thisisthegeneralformofthesynchronizedstatement:
synchronized(object) {
//statementstobesynchronized

Here, object is a reference to the object being synchronized. A synchronized block ensures that a
call to a method that is a member of object occurs only after the current thread has successfully
entered object’s monitor.

Program:

classbank{

intamount=5000;

voidtransaction(intn,charc){
try
{

if(c=='d')

System.out.println("BeforedepositBalance="+amount); amount
=amount+n;
System.out.println("AfterdepositBalance="+amount);
}

elseif(c=='w'){

System.out.println("BeforewithdrawBalance="+amount);
amount = amount-n;
System.out.println("AfterwithdrawBalance="+amount);

Thread.sleep(400);
}

catch(Exceptione){System.out.println(e);}

classdepositextendsThread{ b
ank t;
deposit(bankx){
t=x;
}

publicvoidrun(){
synchronized(t)
{

t.transaction(4000,'d');

}
}

classwithdrawextendsThread{
bank t;
withdraw(bankx){
t=x;
}
public void run(){
synchronized(t)
{ t.transaction(2000,'w');
}

publicclasstestsync{

publicstaticvoidmain(Stringargs[])
{ bank obj = new bank();
deposit t1=new deposit(obj);
withdrawt2=newwithdraw(obj);
t1.start();
t2.start();
}

Output:
Before deposit Balance =5000
After deposit Balance =9000
BeforewithdrawBalance=9000
After withdraw Balance =7000

7. Write a java program for inventory problem to illustrate the usage of thread synchronized
keywordandinterthreadcommunicationprocess.Theyhavethreeclassescalledconsumer,
producerand stock.
(Or)Explainaboutinterthreadcommunicationwithexampleprogram.

 Javaincludesan elegant interprocesscommunication mechanism viathewait( ),notify(),and


notifyAll( ) methods. Inter-thread communicationis all about allowing synchronized threads
to communicate with each other. These methods are implemented as final methods in Object,
soallclasseshavethem.Allthreemethodscanbecalledonlyfromwithinasynchronizedcontext.
wait()tellsthecallingthreadtogiveupthemonitorandgotosleepuntilsomeotherthread enters the same
monitor and calls notify( ).
notify()wakesupathreadthatcalledwait()onthesameobject.
notifyAll( ) wakes up all the threads that called wait() on the sameobject. Oneof the threads will be
granted access.

Consider the following sample program thatimplements a simple form of the producer/ consumer
problem.Itconsistsoffourclasses:Queue,thequeuethatyou’retryingtosynchronize;Producer,the
threaded object that is producing queue entries; Consumer, the threaded object that is consuming
queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

classQueue

intn;

booleanvalueSet= false;

synchronizedintget()
{
while(!valueSet)
try {
wait();

catch(InterruptedExceptione)
{

System.out.println("InterruptedExceptioncaught");

}
System.out.println("Got:"+n);
valueSet = false;
notify();
returnn;

synchronizedvoidput(intx)

{
while(valueSet)
try {
wait();

catch(InterruptedExceptione)
{

System.out.println("InterruptedExceptioncaught");

n= x;
valueSet = true;
System.out.println("Put:"+n);
notify();
}

classProducerextendsThread{ Que
ue q;
Producer(Queueq1){ q
= q1;
}
publicvoidrun()
{ int i = 0;
while(true) {
q.put(i++);
}
}

classConsumerextendsThread{ Que
ue q;
Consumer(Queueq1){ q
= q1;
}

publicvoidrun()
{ while(true) {
q.get();
}
}

publicclassPCFixed
{

publicstaticvoidmain(Stringargs[])

Queue q = new Queue();


Producer p=new Producer(q);
Consumerc=newConsumer(q);
p.start();
c.start();

System.out.println("PressControl-Ctostop.");
}

}
Output:

Put:1
Got:1

Put:2

Got:2

Put:3

Got:3

Put:4
Got:4

Put:5
Got:5

10.Explainaboutcreatingmultiplethreadsandthreadpriorities.

Theprogramcancreateasmanythreadsasitneeds. class

multithreading extends Thread

publicvoidrun()

try

System.out.println("Thread"+Thread.currentThread().getId()+"is running");

catch(Exceptione)

System.out.println("Exceptioniscaught");

}
}

publicclassmultithreadingdemo

publicstaticvoidmain(String[]args)

multithreadingm1=newmultithreading();

multithreadingm2=newmultithreading();

m1.start();

m2.start();

Output:

Thread21isrunning

Thread22isrunning

UsingisAlive()andjoin()

Oftenyouwillwantthemain threadtofinishlast.Thiscanbeaccomplishedbycallingsleep()withinmain(
),withalong enoughdelayto ensurethatallchildthreadsterminatepriortothemainthread.However,this
ishardlyasatisfactorysolution,anditalsoraisesalargerquestion:Howcanonethreadknowwhenanother thread
has ended? Fortunately, Thread provides a means by which you can answer this question.

Twowaysexisttodeterminewhetherathreadhasfinished.

3) First,youcancallisAlive()onthethread.Thismethodisdefinedby Thread,anditsgeneralformisshown here:


finalbooleanisAlive()

TheisAlive()methodreturnstrueifthethreaduponwhichitiscalledisstillrunning.Itreturnsfalse
otherwise.isAlive()isoccasionallyuseful.
4) Mostcommonlyusedmethodto waitforathreadtofinishiscalled join(),shownhere: final

void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.

classjointhreadextendsThread{ public

void run() {

try{

System.out.println(Thread.currentThread().getName());

Thread.sleep(100);

catch (InterruptedException e) {

System.out.println("Thread interrupted");

publicclassJoinExample{

publicstaticvoidmain(String[]args)

{ jointhread t1 = new jointhread();

jointhread t2 = new jointhread();

t1.start();

t2.start();

System.out.println("t1Alive-"+t1.isAlive());

System.out.println("t2Alive-"+t2.isAlive());

try{
t1.join();

t2.join();

catch (InterruptedException e) {

System.out.println("Thread interrupted");

System.out.println("t1Alive-"+t1.isAlive());

System.out.println("t2Alive-"+t2.isAlive());

System.out.println("Processing finished");

Output:

Thread-0
Thread-1
t1 Alive - true
t2 Alive - true
t1Alive-false
t2Alive-false
Processingfinished

THREADPRIORITIES:

 Thread priorities are used by the thread scheduler to decide when each thread should be allowed to
run. In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the
amount of CPU time that a thread gets often depends on several factors besides its priority. (For
example, how an operating system implements multitasking can affect the relative availability of CPU
time.)
 A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority
thread is runningand a higher-priority thread resumes (from sleeping or waiting on I/O,for example),
it will preempt the lower-priority thread.

Tosetathread’spriority,usethesetPriority()method,whichisamemberof Thread.

finalvoidsetPriority(intlevel)
Here, levelspecifies thenewpriority settingforthecallingthread.Thevalueof levelmust bewithin therange
MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to
default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final
variables within Thread.

Youcanobtainthecurrentprioritysettingbycallingthe getPriority()methodofThread,shownhere:

finalintgetPriority()

12. Explainaboutdeadlock.

 Deadlockoccurswhentwothreadshaveacirculardependencyonapairofsynchronizedobjects.
 Forexample,supposeonethreadentersthemonitoronobjectX andanotherthreadentersthemonitor on
object Y.
 If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the
thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to
accessX,itwouldhavetoreleaseitsownlockonYsothatthefirstthreadcouldcomplete.Deadlockis a difficult
error to debug for two reasons:
3) Ingeneral,itoccursonlyrarely,whenthetwothreadstime-sliceinjusttheright way.
4) Itmayinvolvemorethantwothreadsandtwosynchronizedobjects.

//OnlineJavaCompiler

//Usethiseditortowrite,compileandrunyourJavacodeonline

publicclassTestThread

static String r1 = "java";

staticStringr2="program";

public static void main(String args[])

{ ThreadDemo1T1=newThreadDemo1();

ThreadDemo2T2=newThreadDemo2();

T1.start();

T2.start();

}
staticclassThreadDemo1extendsThread

publicvoidrun()

synchronized(r1)

System.out.println("Thread1:Holdinglock1...");

System.out.println("Thread1:Waitingforlock2...");

synchronized(r2)

System.out.println("Thread1:Holdinglock1&2...");

staticclassThreadDemo2extendsThread

publicvoidrun()

synchronized(r2)

System.out.println("Thread2:Holdinglock2...");

System.out.println("Thread2:Waitingforlock1...");

synchronized(r1)

System.out.println("Thread2:Holdinglock1&2...");

}
}

}}

Output

Thread1:Holdinglock1...

Thread2:Holdinglock2...

Thread1:Waitingforlock2...

Thread2:Waitingforlock1...

As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the
firstconditions that you should check for.

13. Explainaboutsuspending,resuming,andstoppingthreads.

 stop()methodinThread–Thismethodterminatesthethreadexecution.
 suspend()methodin Thread–Ifyouwantto stop thethreadexecutionandstartitagainwhena certain event
occurs. ...
 resume()methodinThread–resume()methodworkswithsuspend()method.

 The mechanisms to suspend, stop, and resume threads differ between early versions of Java, such as
Java1.0,andmoremodernversions,beginningwithJava2.PriortoJava2,aprogramused suspend(),
resume(),andstop(),whicharemethodsdefinedbyThread,topause,restart,andstoptheexecution of a
thread. Although these methods seem to be a perfectly reasonable and convenient approach to
managing the execution of threads, they must not be used for new Java programs.

 Here’s why. The suspend( ) method of the Thread class was deprecated by Java 2 several years ago.
Thiswas donebecause suspend() cansometimescauseserioussystemfailures.Assumethatathread as
obtained locks on critical data structures. If that thread is suspended at that point, those locks are not
relinquished. Other threads that may be waiting for those resources can be deadlocked.
 Theresume() methodisalsodeprecated.Itdoesnotcauseproblems,butcannotbeusedwithoutthe
suspend() method as its counterpart. Thestop() methodofthe Thread class, too, wasdeprecated
byJava 2. This was done because this method can sometimes cause serious system failures.
 Assumethat a thread is writingto a critically important data structureand has completedonly part of
itschanges.Ifthatthreadisstoppedatthatpoint,thatdatastructuremightbeleftinacorruptedstate. The
trouble is that stop( ) causes any lock the calling thread holds to be released. Thus, the corrupted data
might be used by another thread that is waiting on the same lock.
 Becauseyoucan’tnowusethesuspend(),resume(),orstop()methodstocontrolathread,youmight be
thinking that no way exists to pause, restart, or terminate a thread.
 But, fortunately, this is not true. Instead, a thread must be designed so that the run( )
methodperiodically checks to determine whether that thread should suspend, resume, or stop its
ownexecution. This is accomplished by establishinga flagvariablethat indicates theexecution
stateofthe thread. As long as this flag is set to “running,” the run( ) method must continue to let the
thread execute.Ifthisvariableissetto“suspend,”thethreadmustpause.Ifitissetto“stop,”thethreadmust
terminate. Ofcourse,avarietyofwaysexistinwhichto writesuchcode,butthecentralthemewillbe the
same for all programs.
 Thefollowingexampleillustrateshowthe wait()andnotify()methodsthatareinheritedfrom Object can be
used to control the execution of a thread. Let us consider its operation. The NewThread class
containsabooleaninstancevariablenamedsuspendFlag,whichisusedtocontroltheexecutionofthe
thread.Itisinitializedtofalsebytheconstructor.Therun()methodcontainsasynchronizedstatement block
that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the
executionofthethread.Themysuspend()methodsetssuspendFlagtotrue.Themyresume()method sets
suspendFlag to false and invokes notify( ) to wakeup thethread. Finally, the main( ) method has been
modified to invoke the mysuspend( ) and myresume( ) methods.

classNewThreadimplementsRunnable

Stringname;

Thread t;

boolean suspendFlag;

NewThread(Stringthreadname)

name=threadname;

t = new Thread(this, name);

System.out.println("Newthread:"+t);

suspendFlag = false;

t.start();

publicvoidrun()

try

for(inti=3;i >0;i--)

System.out.println(name+":"+i);

Thread.sleep(200);

synchronized(this)

while(suspendFlag)

{
wait();

catch(InterruptedExceptione)

System.out.println(name+"interrupted.");

System.out.println(name+"exiting.");

voidmysuspend()

suspendFlag=true;

synchronizedvoidmyresume()

suspendFlag=false;

notify();

classSuspendResume

publicstaticvoidmain(Stringargs[])

NewThreadob1=newNewThread("One");

NewThreadob2=newNewThread("Two");

try

Thread.sleep(1000);

ob1.mysuspend();
System.out.println("SuspendingthreadOne");

Thread.sleep(1000);

ob1.myresume();

System.out.println("Resuming thread One");

ob2.mysuspend();

System.out.println("SuspendingthreadTwo");

Thread.sleep(1000);

ob2.myresume();

System.out.println("ResumingthreadTwo");

catch(InterruptedExceptione)

System.out.println("MainthreadInterrupted");

//waitforthreadstofinish try

System.out.println("Waitingforthreadstofinish."); ob1.t.join();

ob2.t.join();

catch(InterruptedExceptione)

System.out.println("MainthreadInterrupted");

System.out.println("Mainthreadexiting.");

Output:
Newthread:Thread[One,5,main]

Newthread:Thread[Two,5,main]

One: 3

Two:3

One:2

Two:2

One:1Two:1

One exiting.

Two exiting.

Suspending thread One

Resuming thread One

Suspending thread Two

Resuming thread Two

Waitingforthreadstofinish.

Main thread exiting.

14. Explainabouttypewrappersinjava.

Javausesprimitivetypes(alsocalledsimpletypes),suchasintordouble,toholdthebasicdatatypessupported
bythelanguage.Primitivetypes,ratherthanobjects,areusedforthesequantitiesforthesakeofperformance. Using
objects forthese values would add an unacceptable overhead to even the simplestof calculations. Thus, the
primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when you will need an object
representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the
standard data structures implemented by Java operate on objects, which means that you can’t use these data
structures to store primitive types. To handle these situations, Java provides type wrappers, which are classes
that encapsulate a primitive type within an object.

ThetypewrappersareDouble,Float,Long,Integer,Short,Byte,Character,andBoolean.Theseclassesoffera
widearrayofmethodsthatallowyoutofullyintegratetheprimitivetypesintoJava’sobjecthierarchy.

Character:

Character is a wrapper around a char. The constructor for Character is Character(char ch)

Here,chspecifiesthecharacterthatwillbewrappedbythe Characterobjectbeingcreated.
ToobtainthecharvaluecontainedinaCharacterobject,callcharValue(),shownhere:

charcharValue( )

Itreturnstheencapsulatedcharacter.

Boolean

Booleanisawrapperaroundbooleanvalues.Itdefinestheseconstructors:

Boolean(booleanboolValue)

Boolean(String boolString)

In thefirst version,boolValuemust beeithertrueor false.In thesecond version, ifboolStringcontainsthestring


“true”(inuppercaseorlowercase),thenthenew Booleanobjectwillbetrue.Otherwise,itwillbefalse. To

obtain a boolean value from a Boolean object, use booleanValue( ), shown here:

booleanbooleanValue()

Itreturnsthebooleanequivalentoftheinvokingobject.

TheNumericTypeWrappers

Byfar,themostcommonlyusedtypewrappersarethosethatrepresentnumericvalues.Theseare Byte,Short, Integer,


Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number
declaresmethodsthatreturnthevalueofanobjectineachofthedifferentnumberformats.Thesemethodsare shown
here:

byte byteValue( )

doubledoubleValue()

float floatValue( )

int intValue( )

longlongValue()

shortshortValue()
Forexample,doubleValue()returnsthevalueofanobjectasadouble,floatValue()returnsthevalueasafloat, and so
on. These methods are implemented by each of the numeric type wrappers.

Allofthenumerictypewrappersdefineconstructorsthatallowanobjecttobeconstructedfromagivenvalue, or a
string representation of that value. For example, here are the constructors defined for Integer:

Integer(int num)

Integer(Stringstr)

Ifstrdoesnotcontainavalidnumericvalue,thenaNumberFormatExceptionisthrown.Allofthetypewrappers
overridetoString().Itreturnsthehuman-readableformofthevaluecontainedwithinthewrapper.Thisallows
youtooutputthevaluebypassingatypewrapperobjectto println(),forexample,withouthavingtoconvertit
intoitsprimitivetype.Thefollowingprogramdemonstrateshowtouseanumerictypewrappertoencapsulate a value
and then extract that value.

//Demonstrateatypewrapper.

class Wrap {

publicstaticvoidmain(Stringargs[])

{ Integer iOb = new Integer(100);

inti= iOb.intValue();

System.out.println(i+""+iOb);//displays100 100

This program wraps the integer value 100 inside an Integer object called iOb. The program then obtains
thisvalue by calling intValue( ) and stores the result in i.

Theprocessofencapsulatingavaluewithinanobjectiscalled boxing.Thus,intheprogram, this line

boxes the value 100 into an Integer:

IntegeriOb=newInteger(100);

Theprocessofextractingavaluefromatypewrapperiscalled unboxing.Forexample,the program

unboxes the value in iOb with this statement:

inti= iOb.intValue();
Thesamegeneralprocedureusedbytheprecedingprogramtoboxandunboxvalueshasbeenemployedsince the
original version of Java. However, with the release of JDK 5, Java

fundamentallyimprovedonthisthroughtheadditionofautoboxing,describednext.

15. Explainaboutautoboxingandunboxing.

BeginningwithJDK5,Javaaddedtwoimportantfeatures:

autoboxingandauto-unboxing.

Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object.

Auto-unboxing is theprocessby which thevalueofa boxed object is automatically extracted (unboxed) froma
typewrapperwhenitsvalueisneeded.Thereisnoneedtocallamethodsuchas intValue()ordoubleValue().

The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms, removing
thetediumofmanuallyboxingandunboxingvalues.Italsohelpsprevent errors.Moreover,itisveryimportant
togenerics,whichoperatesonlyonobjects.Finally,autoboxingmakesworkingwiththeCollectionsFramework much
easier.

Withautoboxingitisnolongernecessarytomanuallyconstructanobjectinordertowrapaprimitivetype.You need
only assign that value to a type-wrapper reference. Java automatically constructs the object for you. For
example, here is the modern way to construct an Integer object that has the value 100:

IntegeriOb=100; //autoboxanint

Noticethatnoobjectisexplicitlycreatedthroughtheuseofnew.Javahandlesthisforyou,automatically.

Tounboxanobject,simplyassignthatobjectreferencetoaprimitive-typevariable.Forexample,tounboxiOb, you can


use this line:

inti=iOb; //auto-unbox

Javahandlesthedetailsforyou.

Hereistheprecedingprogramrewrittentouseautoboxing/unboxing:

//Demonstrateautoboxing/unboxing.

classAutoBox
{

publicstaticvoidmain(Stringargs[])

IntegeriOb=100;//autoboxanint int i

= iOb; // auto-unbox

System.out.println(i+""+iOb); //displays100 100

Autoboxing/UnboxingBooleanandCharacterValues

Javaalso supplieswrappersforbooleanandchar.TheseareBooleanandCharacter. Autoboxing/unboxing applies


to these wrappers, too. For example, consider the following program:

//Autoboxing/unboxingaBooleanandCharacter.

classAutoBox5

publicstaticvoidmain(Stringargs[])

Booleanb=true;

if(b)

System.out.println("bistrue");

Characterch='x'; //boxachar

charch2=ch; //unboxachar

System.out.println("ch2is"+ch2);

Theoutputisshownhere: b

is true

ch2isx
CS3391/OBJECTORIENTEDPROGRAMMING

Unit-III

Part-A

2. Whatisanexception?
Exceptionisanabnormalconditionwhichoccursduringtheexecutionofaprogramanddisruptsnormalflowof
theprogram.Thisexceptionmustbehandledproperly.Ifitisnothandled,programwillbeterminatedabruptly.

3. Howtheexceptionsarehandledinjava?ORExplainexceptionhandlingmechanisminjava?
Exceptionsinjavaarehandledusingtry,catchandfinallyblocks.

tryblock:Thecodeorsetofstatementswhicharetobemonitoredforexceptionarekeptinthisblock. catch block :

This block catches the exceptions occurred in the try block.

finallyblock:Thisblockisalwaysexecutedwhetherexceptionisoccurredinthetryblockornotandoccurred exception
is caught in the catch block or not.

4. Whatisthedifferencebetweenerrorandexceptioninjava?
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused by the
application itself. For example, NullPointerException occurs when an application tries to access null object.

5. Canwewriteonlytryblockwithoutcatchandfinallyblocks?
No,Itshowscompilationerror.Thetryblockmustbefollowedbyeithercatchorfinally block. You can

remove either catch block or finally block but not both.

5. Whatisunreachablecatchblockerror?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most
generalones.i.esub classes ofException must comefirst and superclasseslater.Ifyoukeep superclassesfirst and
sub classes later, compiler will show unreachable catch block error.

7. Describethehierarchyofexceptionsinjava?
Allexceptiontypesaresubclassesofthebuilt-inclassThrowable.Thus,Throwableisatthetopofthe exception class
hierarchy.

ImmediatelybelowThrowablearetwosubclassesthatpartitionexceptionsintotwodistinctbranches.

OnebranchisheadedbyException.Thisclassisusedforexceptionalconditionsthatuserprogramsshouldcatch. This is
also the class that you will subclass to create your own custom exception types. There is an important subclass
of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that
you write and include things such as division by zero and invalid array indexing.
TheotherbranchistoppedbyError,whichdefinesexceptionsthatarenotexpectedtobecaughtundernormal
circumstancesbyyourprogram.ExceptionsoftypeErrorareusedbytheJavarun-timesystemtoindicateerrors having
to do with the run-time environment, itself. Stack overflow is an example of such an error.

8. Whatareruntimeexceptionsinjava.Giveexample?
The exceptions which occur at run time are called as run time exceptions. These exceptions are unknown to
compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run time exceptions. These
exceptions are unchecked type of exceptions. For example, NumberFormatException, NullPointerException,
ClassCastException,

9. Whatarecheckedanduncheckedexceptionsinjava?
Checkedexceptionsaretheexceptionswhichareknowntocompiler.Theseexceptionsarecheckedatcompile time
only. Hence the name checked exceptions. These exceptions are also called compile time exceptions. Because,
these exceptions will be known during compile time.

Uncheckedexceptionsarethoseexceptionswhicharenotatallknowntocompiler.Theseexceptionsoccuronly at run
time. These exceptions are also called as run time exceptions. All sub classes of java.lang.RunTimeException
and java.lang.Error are unchecked exceptions.

10. WhatisRe-throwinganexceptioninjava?
Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can
re-throw that exception using throw keyword. It is called re-throwing an exception.

11. Whatistheuseofthrowskeywordinjava?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that
callers ofthe method can guard themselves against that exception. You do this by including a throws clausein
the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is
necessaryforallexceptions,exceptthoseoftypeErrororRuntimeException,oranyoftheirsubclasses.Allother
exceptionsthatamethodcanthrowmustbedeclaredinthethrowsclause.Iftheyarenot,acompile-timeerror will
result.

12. Whatisthedifferencebetweenfinal,finallyandfinalizeinjava? final


keyword :

finalisakeywordwhichisusedtomakeavariableoramethodoraclassas“unchangeable“.

finallyBlock:

finally is a block which is used for exception handling along with try and catch blocks. finally block is always
executed whether exception is raised or not and raised exception is handled or not. Most of time, this block is
used to close the resources like database connection, I/O resources etc.

finalize()Method:

finalize()methodisaprotectedmethodofjava.lang.Objectclass.Itisinheritedtoeveryclassyoucreateinjava. This
method is called by garbage collector thread before an object is removed from the memory. finalize() method
is used to perform some clean up operations on an object before it is removed from the memory.

13. Howdoyoucreatecustomizedexceptionsinjava?
In java, we can define our own exception classes as per our requirements. These exceptions are called user
defined exceptions in java OR Customized exceptions. User defined exceptions must extend any one of the
classes in the hierarchy of exceptions.

14. Whatisthedifferencebetweenthrow,throwsandthrowableinjava?
throw In Java :

throwis a keyword in java which is used to throwan exception manually.Usingthrowkeyword, you can throw
anexceptionfromanymethodorblock.But,thatexceptionmustbeoftypejava.lang.Throwableclassorit’ssub classes.
Below example shows how to throw an exception using throw keyword.

throwsInJava:

throws is also a keyword in java which is used in the method signature to indicate that this method may throw
mentionedexceptions.Thecallertosuchmethodsmusthandlethementionedexceptionseitherusingtry-catch blocks
or using throws keyword. Below is the syntax for using throws keyword.

ThrowableInJava:

Throwable is a super class for all types of errors and exceptions in java. This class is a member of
java.langpackage.Onlyinstancesofthisclassorit’ssubclassesarethrownbythejavavirtualmachineorbythe
throwstatement.Theonlyargumentofcatchblockmustbeofthistypeorit’ssubclasses.Ifyouwanttocreate your own
customized exceptions, then your class must extend this class. Click hereto see the hierarchy of exception
classes in java.

26. Whichclassisthesuperclassforalltypesoferrorsandexceptionsinjava?
java.lang.Throwableisthesuperclassforalltypesoferrorsandexceptionsinjava.

27. DefineProcess-basedmultitasking:(Multiprocessing)
A process is a program that is executing. Thus, process-based multitasking is the feature that allows your
computerto run twoor more programs concurrently.For example, process-based multitaskingenables you to
run the Java compiler at the same time that you are using a text editor or visiting a web site. In process-based
multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

28. DefineThread-basedmultitasking:(Multithreading)
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means
thatasingleprogramcanperformtwoormoretaskssimultaneously.Forinstance,atexteditorcanformattext at
thesame time that it is printing, as long as these two actions arebeing performed by two separate threads.
Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the
details.

29. Differentiatebetweenmultitaskingandmultithreading.
Sl.n Multitasking Multithreading
o.

1 Itisaprocessofexecutingmanyprocesses Itisaprocessofexecutingmultiplethreads(sub-
running simultaneously. process).

2 Processisprograminexecution.Theyare Threadisbasicallyalightweightsub-process.Itisa
Heavy weight. smallest unit of processing.
3 Inmultitaskingseparatememoryis allocated Threads(sub-process)aresharingcommon memory.
to each process.

4 Interprocesscommunicationisexpensive Interthreadcommunicationisinexpensive.

5 Contextswitchingfromoneprocessto Contextswitchingfromonethreadtoanotheris
another is costly. inexpensive.

30. DefineMultithreading.
Multithreadingenablestowriteefficientprogramsthatmakemaximumuseoftheprocessingpoweravailable in the
system. One important way multithreading achieves this is by keeping idle time to a minimum.

31. ListaretheStatesofthread.
 Athreadcanberunning.ItcanbereadytorunassoonasitgetsCPUtime.
 Arunningthreadcanbesuspended,whichtemporarilyhaltsitsactivity.
 Asuspendedthreadcanthenberesumed,allowingittopickupwhereitleft off.
 Athreadcanbeblockedwhenwaitingforaresource.
 Atanytime,a threadcanbe terminated,whichhaltsitsexecutionimmediately.Onceterminated, a
thread cannot be resumed.
32. HowcanyoucreatethreadinJava?
Javadefinestwowaysforcreatingthread.
1) ByextendingtheThreadclass.
2) ByimplementtheRunnableinterface.

33. Whatdoyoumeanbysynchronization?
Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethattheresource will
beused by only onethread at a time. Theprocess by which this is achieved is called synchronization. Java
provides unique, language-level support for it.

Synchronizationcanbedoneintwoways:

3) UsingSynchronizedMethods
4) UsingsynchronizedStatementorsynchronizedblock

34. Whatistheneedforsynchronization?
Thesynchronizationismainlyusedto

 Topreventthreadinterference.
 Topreventconsistencyproblem.

35. Whatismeantbymonitor?
A monitor isan object that isused as amutually exclusivelock. Only onethread can owna monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are
saidtobewaitingforthemonitor.Athreadthatownsamonitorcanreenterthesamemonitorifitsodesires.

36. Howwillyousetthepriorityofthethread?
Threadprioritiesareusedbythethreadschedulertodecidewheneachthreadshouldbeallowedto run. In
theory, higher-priority threads get more CPU time than lower-priority threads.

Tosetathread’spriority,usethesetPriority()method.
finalvoidsetPriority(intlevel)

Thevalueof level must bewithin therange MIN_PRIORITY and MAX_PRIORITY. Currently, these
valuesare1and10,respectively.Toreturnathreadtodefaultpriority,specify NORM_PRIORITY, which
is currently 5.

Part-B

23. Developajavaprogramforhandlingdividebyzeroexceptionwithmultiplecatches.
24. DevelopajavaprogramforhandlingArrayIndexOutOfBoundsExceptionexception
with finally block.

25. Developajavaprogramforexceptionhandlingwiththrowandthrowskeyword.
26. Explainnestedtry/catchwithexampleprogram.
27. Developajavaprogramwithmultiplecatchclauses.
28. DevelopajavaprogramwithmulticatchthatcanhandlebothArithmeticException and
IndexOutOfBoundsException.

29. Discussaboutexceptionhandlinginnestedtry/catch.
30. Explainabouttypesofexceptionwithanexample.
31. DevelopaJavaprogramtoimplementuserdefinedexceptionhandling.
32. Discussthelifecycleofthreadswithneatdiagram.
33. DevelopaprogramforcreatingthreadsbyusingThreadclassandRunnableinterface.
34. Whydoweneedbothstart()andrun()methodboth?canweachieveitwithonlyrun()method?
35. Writeajavaprogramthatsynchronizethreethreadsofthesameprogramanddisplaythecontent the text
supplied through these threads.
36. Developajavaprogramthatprovidesynchronizationfortwothreadsdepositandwithdrawinabank
application.
37. Definethread.Explainthestateofthreads.Statereasonforsynchronizationinthread. Write
simple concurrent programming to create, sleep and delete thread.
38. Whatisthreadsynchronization?Discusswithanexample.
39. Writeajavaprogramforinventoryproblemtoillustratetheusageofthreadsynchronizedkeyword and
interthread communication process. They have three classes called consumer, producerand stock.
40. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, second thread computes
thesquareofthenumberandprints.Ifthevalueisodd,the thirdthreadwillprintthevalueofcubeof the
number.
41. Developajavaapplicationprogramforgeneratingfourthreadstoperformthefollowingoperation.
v) GettingNnumbersasinput
vi) Printingevennumbers
vii) Printing odd numbers.
viii)Computingtheaverage
42. Explainaboutwrapperclasses.
43. Elaborateindetailaboutautoboxing.
44. DiscussaboutSuspending,Resuming,andStoppingThreads.

You might also like