Oops
Oops
ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
COURSE OBJECTIVES:
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner
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.
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-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.
I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics:
Generic Programming – Generic classes – Generic Methods – Bounded Types – Restrictions
and Limitations. Strings: Basic String class, methods and String Buffer Class.
JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls:
Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text
Controls – ScrollPane. Layouts – FlowPane – HBox and VBox – BorderPane – StackPane –
GridPane. Menus – Basics – Menu – Menu bars – MenuItem.
COURSE OUTCOMES:
CO3:Make use of exception handling mechanisms and multithreaded model to solve real
world problems
CO4:Build Java applications with I/O packages, string classes, Collections and generics
concepts
CO5:Integrate the concepts of event handling and JavaFX components and controls for
developing GUI based applications
TEXT BOOKS:
1. Herbert Schildt, “Java: The Complete Reference”, 11 th Edition, McGraw Hill Education,
New Delhi, 2019
REFERENCE:
1. Cay S. Horstmann, “Core Java Fundamentals”, Volume 1, 11 th Edition, Prentice Hall, 2018.
CS3391 OBJECT ORIENTED PROGRAMMING
---------------------------------------------------------------------------------------------------------------
UNIT I INTRODUCTION TO OOP AND JAVA
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. Explain the features of object oriented programming.
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.
1) ABSTRACTION:
Abstraction is a process of showing only “relevant” data and “hide” unnecessary details of
an object from the user. For example, when you login to your bank account online, you enter
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.
• One way to think about encapsulation is as a protective wrapper that prevents the code
and data from being arbitrarily accessed by other code defined outside the wrapper. 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 :
Object is an instance of a class. Objects have states 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:
• Polymorphism refers to the ability of a variable, object or function to take on multiple
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
group of related activities. This helps reduce complexity by allowing the same interface
to be used to specify a general class of action.
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism. Method
overloading can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name in a
class that differs in signature.
Dynamic Polymorphism
• It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a
process in which a call to an overridden method is resolved at runtime rather, thats
why it is called runtime polymorphism
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
security mechanisms to protect the system against harm caused by stray programs. 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 an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behaviour. All code belong to some class. Classes
are in turn arranged in a hierarchy or package structure
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,
which allows to write programs that do many things simultaneously. Java’s easy-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). The goal of JVM is
“write once; run anywhere, anytime, forever.”
8) Interpreted :
Java enables the creation of cross-platform programs by compiling into an intermediate
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
bytecode is "close" to native code. The Java bytecode was carefully designed so that it
would be easy to translate directly into native machine code for very high performance
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/IP protocols. In fact, accessing a resource using a URL is not much different from
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
dynamically link code in a safe and expedient manner. This is crucial to the robustness
of the Java environment, in which small fragments of bytecode may be dynamically
updated on a running system.
Boolean Literals
Boolean literals are simple. There are only two logical values that a Boolean value can have,
true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, the Boolean
literals can only be assigned to variables declared as boolean or used in expressions with
Boolean operators.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can
be converted into integers and manipulated with the integer operators, such as the addition and
subtraction operators. A literal character is represented inside a pair of single quotes. All of the
visible ASCII characters can be directly entered inside the quotes, such as 'a', 'z', and '@'.
String Literals
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
"Hello World"
"two\nlines"
The outcome of these operations is a boolean value. The relational operators are most
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
that they operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true == false and !false == true. The following table shows the effect of each logical
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, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same type, which can’t be void.
Here is an example of the way that the ? is employed:
ratio = denom == 0 ? 0 : num / denom;
Operator Precedence
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
like operators in an expression. Parentheses are used to alter the precedence of an operation.
As you know from the previous chapter, the square brackets provide array indexing. The dot
operator is used to dereference objects.
Selection statements allow your program to choose different paths of execution based upon
the outcome of an expression or the state of a variable. Iteration statements enable program
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’s Selection Statements
Java supports two selection statements:
if and switch.
If:
Nested ifs
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
statement always refers to the nearest if statement that is within the same block as the else
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
else a = c; // associated with this else
}
else a = d;
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often
provides a better alternative than a large series of if-else-if statements. Here is the general form
of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Iteration Statements
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
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while
its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the next
line of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
do-while
The do-while loop always executes its body at least once, because its conditional expression
is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
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.
Here is a reworked version of the “tick” program that demonstrates the do-while loop.
It generates the same output as before.
For:
Jump Statements
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
a “civilized” form of goto.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop but stop processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue
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. That is, it causes program control to transfer back to the caller of the method. As such,
it is categorized as a jump statement.
6. Explain about class, object, method and constructors in java.
(or)
Explain about constructor overloading.
Class:
A class defines the structure and behaviour (data and code) that will be shared by a set
of objects. Each object of a given class contains the structure and behaviour defined by
the class
Object:
Object is an instance of a class. Objects have states and behaviours.
Method:
A method is 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:
A constructor is a block of code. Constructor is called when an instance of the object is
created, and memory is allocated for the object.
Constructor overloading is a technique that enables a single class to have more than one
constructor that varies by the list of arguments passed.
Program:
class Box
{
double width;
double height;
double depth;
Box()
{
width = 5;
height = 4;
depth = 3;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box(3, 6, 9);
double vol;
vol = b1.volume();
System.out.println("Volume of box1 is " + vol);
vol = b2.volume();
System.out.println("Volume of box2 is " + vol);
}
}
• Java’s access modifiers are public, private, and protected. Java also defines a
default access level.
No Modifier
Private Protected Public
(Default)
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes
• 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:
• Instance variables declared as static are, essentially, global variables. When objects
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:
• Methods declared as static have several restrictions:
➢ They can only directly call other static methods.
➢ They can only directly access static data.
➢ 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
declare a static block that gets executed exactly once, when the class is first loaded.
The following example shows a class that has a static method, some static variables,
and a static initialization block:
Demonstrate static variables, methods, and blocks.
class student
{
int a;
static int b;
student(){
b++;
}
static
{
System.out.println("First static block");
}
static
{
System.out.println("Second static block");
}
public void showData()
{
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
output:
First static block
Second static block
Value of a =0
Value of b =1
Value of a =0
Value of b =2
This is static method
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
program itself. You can then use the javadoc utility program (supplied with the JDK) to extract
the information and put it into an HTML file. Documentation comments make it convenient to
document your programs. You have almost certainly seen documentation that uses such
comments because that is the way the Java API ibrary was documented. Beginning with JDK
9, javadoc includes support for modules.
/**
* The AddNum program implements an application that
* simply adds two given integer numbers and Prints
* the output on the screen.
* @author John
* @version 1.0
* @since 30-06-2019
*/
/**
* This is the main method which makes use of addNum method.
* @param args Unused.
* @return Nothing.
*/
Compile:
Z:\>javac addnum.java
Html file creation:
Z:\>javadoc addnum.java
Html file will be created in the same directory.
Output
1 2 3 4
2) Object-oriented programming :
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. Define abstraction:
Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user. For example, when you login to your
Amazon account online, you enter your user_id and password and press login, what
happens when you press login, how the input data sent to amazon server, how it gets
verified is all abstracted away from the you.
3. Define encapsulation.
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.
4. What is classes and 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
the class, as if it were stamped out by a mold in the shape of the class. For this reason,
objects are sometimes referred to as instances of a class. Thus, a class is a logical
construct; an object has physical reality.
5. Define 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. Most
knowledge is made manageable by hierarchical (that is, top-down) classifications.
6. What is meant by polymorphism? Specify its type.
3) Protected: protected members can be accessed by the same package and its
derived classes.
14. State the situation where static members(static variable,static method, and static
are used.
There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally, a class member must be accessed
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.
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.
Instance variables declared as static are, essentially, global variables. When objects
of its class are declared, no copy of a static variable is made. Instead, all instances of
the class share the same static variable.
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. Develop a program by creating an 'Employee' class having the following methods
and print the final salary.
'getInfo()' which takes the salary, number of hours of work per day of
employee as parameter.
'AddSal()' which adds Rs.100 to salary of the employee if it is less than Rs.5000.
'AddWork()' which adds Rs.50 to salary of employee if the number of hours of work
per day is more than 6 hours.
12. Suppose you have a Piggie Bank with an initial amount of Rs.500 and you have to add
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 -
having a parameter which is the amount that will be added to Piggie Bank Create object
of the 'AddAmount' class and display the final amount in Piggie Bank.
15. Develop a java program that take 20 integer inputs from user and print the
following: number of positive numbers
number of negative
numbers number of odd
numbers number of even
numbers number of 0.
16. Create a class named 'Programming'. While creating an object of the class, if nothing
is passed to it, then the message "I like programming languages" should be printed. 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. Write a java program to find whether the number is odd or even numbers in an array.
18. Write a java program to perform the following functions using classes, objects,
constructors and destructors where essential.
i)Get as input the marks of 5 students in 5 subjects
ii) Calculate the total and average
iii)Print the formatted results on the screen
19. Develop a mini project for Mark sheet Preparation system using Java concepts.
20. Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that Integer.
21. Write a Java Program that reads a line of integers, and then displays each integer, and
the sum of all the integers
Method Overloading is 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.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. Thus, overloaded
methods must differ in the type and/or number of their parameters. While overloaded methods
may have different return types, the return type alone is insufficient to distinguish two versions
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:
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a= " + a);
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box()
{
width = -1;
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
Output:
class Box
{
double width;
double height;
double depth;
Box(Box ob)
{
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class OverloadCons2
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of mybox1
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
class Test
{
int a;
Test(int i)
{
a = i; }
Test increment( )
{
Test temp = new Test(a+10);
return temp;
}
}
class testdemo
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.increment();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.increment();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
class Outer {
int x = 100;
void test() {
Inner in= new Inner();
in.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer out = new Outer();
out.test();
}
}
Output from this application is shown 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
class Outer and invokes its test( ) method. That method creates an instance of class Inner
and the display( ) method is called.
It is important to realize that an instance of Inner can be created only within the scope
of class Outer. The Java compiler generates an error message if any code outside of class
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.
• Inheritance is the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
• Inheritance allows the creation of hierarchical classifications.
• Using inheritance, you can create a general class that defines behavior common to a set
of related items. This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
Superclass: A class that is inherited is called a superclass.
Subclass: The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a superclass. It inherits all of the members defined by the superclass and
adds its own, unique elements.
Inheritance Basics:
• To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.
• Being a superclass for a subclass does not mean that the superclass cannot be used by
itself. Further, a subclass can be a superclass for another subclass.
The general form of a class declaration that inherits a superclass is shown here:
You can only specify one superclass for any subclass that you create. Java does not support the
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.
2) Multilevel inheritance: refers to a sub and super class relationship where a class extends
the subclass. For example class C extends class B and class B extends class A.
3) Hierarchical inheritance: refers to a sub and super class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class A.
4) Multiple Inheritance: refers to the concept of one class extending more than one classes,
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.
Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
Protected Member:
The private members of a class cannot be directly accessed outside the class. Only methods of
that class can access the private members directly. Sometimes it may be necessary for a
subclass to access a private member of a superclass. If you make a private member public, then
anyone can access that member. So, if a member of a superclass needs to be accessed in a
subclass and yet still prevent its direct access outside the class, you must declare that
member protected.
Following table describes the 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:
When a class inherits another class, it is known as a single inheritance.
Example: A class Shapes is superclass and derive the class : Rectangle
class shape
{
protected double length;
protected double breadth;
shape (double l, double b)
{
length = l;
breadth = b;
}
}
class rectangle extends shape
{
rectangle(double l,double b)
{
super(l,b);
}
double area()
{
return length*breadth;
}
}
class shapedemo1
{
public static void main(String args[])
{
rectangle r=new rectangle(5,6);
System.out.println("Area of rectangle : " +r.area());
}
}
Output:
Area of rectangle : 30.0
2) Hierarchical inheritance:
When more than one classes inherit a same class then this is called hierarchical inheritance.
Shape
Rectangle
Triangle
Example: A class Shapes is superclass and derive the two classes : Rectangle and Triangle
class shape
{
protected double length;
protected double breadth;
shape (double l, double b)
{
length = l;
breadth = b;
}
}
class rectangle extends shape
{
rectangle(double l,double b)
{
super(l,b);
}
double area()
{
return length*breadth;
}
}
Output:
Area of triangle : 6.0
Area of rectangle : 30.0
3) MULTILEVEL INHERITANCE:
Consider the following program. In it, the subclass BoxWeight is used as a superclass to create
the subclass called Shipment. Shipment inherits all of the traits of BoxWeight and Box, and
adds a field called cost, which holds the cost of shipping such a parcel.
class Box
{
private double width;
private double height;
private double depth;
class shipmentdemo {
public static void main(String args[]) {
Shipment shipment1 =new Shipment(10, 20, 15, 10, 3.41);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
}
}
Output:
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.
This example illustrates one other important point: super( ) always refers to the constructor in
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) MULTIPLE INHERITANCE
Java does not support Multiple inheritances
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
super has two general forms.
1) The first calls the superclass’ constructor.
2) The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
A subclass can call a constructor defined by its superclass by use of the following
form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass. super( )
must always be the first statement executed inside a subclass’ constructor.
Example:
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
return width * height * depth;
}
}
class BoxWeight extends Box
{
double weight;
BoxWeight(double w, double h, double d, double m)
{
super(w,h,d);
weight = m;
}
}
class DemoBoxWeight
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); double
vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
}
}
Output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
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:
Using super to overcome name hiding.
class A
{
int i;
}
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
Although the instance variable i in B hides the i in A, super allows access to the i defined
in the superclass. As you will see, super can also be used to call methods that are hidden by
a subclass.
Types of Polymorphism
Example program:
class addition
{
void add(int a,int b)
{
System.out.println("Sum = "+ (a+b));
}
void add(int a,int b,int c)
{
System.out.println("Sum = "+(a+b+c));
}
}
class demo
{
public static void main(String args[])
{
addition a1=new addition();
addition a2=new addition();
a1.add(4,7);
a3.add(50,30,60);
}
}
2) DYNAMIC POLYMORPHISM :
METHOD OVERRIDING:
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.
• A superclass reference variable can refer to a subclass object.
Overridden methods are another way that Java implements the “one interface,
multiple methods” aspect of polymorphism.
class shape
{
double dim1length;
double breadth;
shape(double a, double b) {
length = a;
breadth = b;
}
double area() {
System.out.println("Area for shape is undefined.");
return 0;
}
}
class Rectangle extends shape {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
return (length * breadth);
}
}
class shapedemo {
public static void main(String args[]) {
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("Area is " + s2.area());
s2 = t;
System.out.println("Area of triangle is " + s2.area());
s2 = r;
System.out.println("Area of rectangle is " + s2.area());
}
}
output:
An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed.
Example:
abstract class shape
{
….
}
An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
abstract void area(double x, double y);
program:
class shapedemo
{
public static void main(String args[])
{
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
shape s2;
s2 = r;
System.out.println("Area is " + s2.area());
s2 = t;
System.out.println("Area is " + s2.area());
}
}
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,
specify final as a modifier at the start of its declaration. Methods declared as final cannot be
overridden. The following fragment illustrates final:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
final class A {
//...
}
// The following class is illegal.
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can
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.
Advantage of Java Package:
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
You can define classes inside a package that are not accessible by code outside that package. You can
also define class members that are exposed only to other members of the same package. This allows
your classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the
world.
Defining a 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
class names are put into the default package, which has no name. While the default package is fine for
short, sample programs, it is inadequate for real applications. Most of the time, you will define a
package for your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage:
package MyPackage;
More than one file can include the same package statement. The package statement simply specifies
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;
public class dis
{
public void display()
{
System.out.println("This is a simple package");
}
}
IMPORTING PACKAGES:
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:
import pkg1:
import pack.dis;
class demo
{
public static void main( String args[])
{
dis d=new dis();
d.display();
}
}
File name: demo.java
Compile:
Z:\>javac demo.java
Run:
Z:\>java demo
Output:
This is a simple package
13. What is meant by interface? How it is declared and implemented in java. Give example.
• An interfaces can have methods and variables but the methods declared in interface contain
only method signature, not body.
• An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction.
➢ You cannot instantiate an interface.
➢ An interface does not contain any constructors.
➢ All of the methods in an interface are abstract.
➢ An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
➢ An interface is not extended by a class; it is implemented by a class.
➢ An interface can extend multiple interfaces.
interface A
{
void method1();
void method2();
}
interface B extends A
{
void method3();
}
class inter implements B
{
public void method1() {
System.out.println("Implement method1().");
}
public void method2() {
System.out.println("Implement method2().");
}
public void method3() {
System.out.println("Implement method3().");
}
}
class interdemo{
public static void main(String arg[]) {
inter ob = new inter();
ob.method1();
ob.method2();
ob.method3();
}
}
Multiple inheritance (extends) is not allowed. Interfaces are not classes, however, and a class can
implement more than one interface.
interface Inter1
{
public void test(int i);
}
interface Inter2
{
public void test(String s);
}
Syntax:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Access specifier The members of a class can be The members of an interface are always
private, public or protected. public.
Methods The methods of a class are The methods in an interface are purely
defined to perform a specific abstract.
action.
BASIS FOR
CLASS INTERFACE
COMPARISON
Constructor A class can have constructors to An interface can never have a constructor
initialize the variables. as there is hardly any variable to
initialize.
The process of deriving a new class from an existing class is inheritance. A class that is inherited
is called a superclass and the class that does the inheriting is called a subclass.
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.
18. What are the difference between static variable and instance variable?
Instance variables Static (class) variables
Class variables also known as static variables are
Instance variables are declared in a class, but
declared with the static keyword in a class, but
outside a method, constructor or any block.
outside a method, constructor or a block.
Instance variables are created when an object is
Static variables are created when the program starts
created with the use of the keyword 'new' and
and destroyed when the program stops.
destroyed when the object is destroyed.
Instance variables can be accessed directly by
Static variables can be accessed by calling with the
calling the variable name inside the class.
class nameClassName.VariableName.
However, within static methods (when instance
variables are given accessibility), they should
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 variable per class, regardless of how many
object's state that must be present throughout objects are created from it.
the class.
Part- B
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. Define inner classes. How to access object state using inner classes. Give an example.
17. Explain nested interface with example program.
18. What is an interface? Show that how interface can be extended.
19. What is meant by interface? How it is declared and implemented in java. Give
example.
20. Write a Java Program to create an abstract class named Shape that contains two integers
and an empty method named printArea() and Circumference(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
Each one of the classes contains the method to printArea () and Circumference (). That prints
the area and circumference of the given shape.
21. Create a java class shape with constructor to initialize the one parameter
“dimension”. Now create three subclasses of shape with the following methods.
i) “Circle” with method to calculate the area and circumference of the circle with dimension
as radius.
ii) “Square” with method to calculate the area and length of diagonal of square.
iii)“Sphere” with method to calculate the volume and surface area.
CS3391 OBJECT ORIENTED PROGRAMMING
catch,
throw,
throws,
finally.
• Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch this exception (using catch)
and handle it in some rational manner. System-generated exceptions are automatically thrown by
the Java run-time system.
• To manually throw an exception, use the keyword throw. Any exception that is thrown out of a
method must be specified as such by a throws clause. Any code that absolutely must be executed
after a try block completes is put in a finally block.
EXCEPTION HIERARCHY :
• All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions into two distinct
branches.
• One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch. 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.
• The other branch is topped by Error, which defines exceptions that are not expected to be caught
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.
Although the default exception handler provided by the Java run-time system is useful for debugging,
you will usually want to handle an exception yourself.
Program:
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack. If an inner try
statement does not have a catch handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the
Java run-time system will handle the exception. Here is an example that uses nested try statements:
Output:
Divide by 0: java.lang.ArithmeticException: / by zero
Output when a=1:
a=1
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java
NestTry One Two
Output when a=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, if a method opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. The finally keyword is designed to
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 is thrown, the finally block will execute even if no catch statement matches the
exception.
An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
1) BUILT-IN EXCEPTIONS:
Inside the standard package java.lang, Java defines several exception classes. The most general of
exceptions are the subclasses of the standard type RuntimeException. These exceptions
need not be included in any method's throws list.
i) Checked Exception
Checked exceptions are checked at compile-time. The classes which directly inherit Throwable class
except RuntimeException and Error are known as checked exceptions.
e.g. IOException, SQLException etc. Checked exceptions are checked at compile- time.
class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = 0;
System.out.println("a = " + a); int b =
42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
finally
{
System.out.println(" Finally block");
}
}
Output:
C:\>java MultipleCatches a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
Finally block
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, all exceptions, including those that you create, have the methods defined by Throwable
available to them.
Exception defines four constructors. Two support chained exceptions. The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify a description
of the exception.
Program:
Output:
• Thread is the smallest unit of dispatchable code. This means that a single program can perform
two or more tasks simultaneously. For instance, a text editor can format text at the same time
that it is printing, as long as these two actions are being performed by two separate threads.
• Threads are lighter weight. They share the same address space and cooperatively share the
same heavyweight process. Interthread communication is inexpensive, and context switching
from one thread to the next is lower in cost.
• Multithreading enables to write efficient programs that make maximum use of the
processing power available in the system. Multithreading keep the idle time to a minimum.
Threads exist in several states.
1) A thread can be running. It can be ready to run as soon as it gets CPU time.
2) A running thread can be suspended, which temporarily halts its activity.
3) A suspended thread can then be resumed, allowing it to pick up where it left off.
4) A thread can be blocked when waiting for a resource.
5) At any time, a thread can be terminated, which halts its execution immediately. Once
terminated, a thread cannot be resumed.
Thread.State getState( )
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
Given a Thread instance, you can use getState( ) to obtain the state of a thread. For
example, the following sequence determines if a thread called thrd is in the RUNNABLE state at the
time getState( ) is called:
Thread.State ts = 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
provide a means of synchronizing threads. It’s primarily used for debugging or for profiling a thread’s
run-time characteristics.
6. Develop a program for creating threads by using Thread class and Runnable interface.
(or) Why do we need both start() and run() method both? can we achieve it with only run()
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() method then a new separate thread is being allocated to the execution of run method, so if more
than one thread calls start() method that means their run method is being executed by separate threads
(these threads run simultaneously).
Java defines two ways in which this can be accomplished:
1) By extending the Thread class.
2) By implement the Runnable interface.
{
multithreading m1=new multithreading();
multithreading m2=new multithreading();
m1.start();
m2.start();
}
Output:
Thread 21 is running
Thread 22 is running
Thread(Runnable threadOb)
Thread(Runnable threadOb, String threadName)
Thread(String threadName)
void start( )
{
System.out.println ("Thread " + Thread.currentThread().getId() + " is
running");
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}
public class multithreadingdemo
{
public static void main(String[] args)
{
multithreading m1=new multithreading();
Thread t1 = new Thread(m1);
multithreading m2=new multithreading();
Thread t2 = new Thread(m2);
t1.start();
t2.start();
}
}
Output:
Thread 21 is running
Thread 22 is running
3. Develop a java program that provide synchronization for two threads deposit and withdraw
in a bank application.
(or) What is thread synchronization? Discuss with an example.
Answer:
When two or more threads need access to a shared resource, they need some way to ensure that the
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.
Synchronization is easy in Java, because all objects have their own implicit monitor associated with
them. To enter an object’s monitor, just call a method that has been modified with the synchronized
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:
class bank{
int amount=5000;
amount =amount+n;
System.out.println("After deposit Balance ="+amount);
}
else if(c=='w') {
System.out.println("Before withdraw Balance ="+amount);
amount = amount-n;
System.out.println("After withdraw Balance ="+amount);
}
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);}
}
}
class deposit extends Thread
{
bank t;
deposit(bank x){
t=x;
}
public void run(){
t.transaction(4000,'d');
}
}
t=x;
}
public void run(){
t.transaction(2000,'w');
}
}
Output:
Before deposit Balance =5000
After deposit Balance =9000
Before withdraw Balance =9000
After withdraw Balance =7000
2)The synchronized Statement: (synchronized block)
While creating synchronized methods within classes that you create is an easy and effective means
of achieving synchronization, it will not work in all cases. To understand why, consider the following.
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, this class was not created by you, but by a third party, and you do not have access to the
source code. Thus, you can’t add synchronized to the appropriate methods within the class. How
can access to an object of this class be synchronized? Fortunately, the solution to this problem is
quite easy: You simply put calls to the methods defined by this class inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
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:
class bank{
int amount=5000;
void transaction(int n,char c ){
try
{
if (c=='d')
{
System.out.println("Before deposit Balance ="+amount);
amount =amount+n;
System.out.println("After deposit Balance ="+amount);
}
else if(c=='w') {
System.out.println("Before withdraw Balance ="+amount);
amount = amount-n;
System.out.println("After withdraw Balance ="+amount);
}
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);}
}
bank t;
deposit(bank x){
t=x;
}
public void run(){
synchronized(t)
{
t.transaction(4000,'d');
}
}
}
class withdraw extends Thread{
bank t;
withdraw(bank x){
t=x;
}
public void run(){
synchronized(t){
t.transaction(2000,'w');
}
}
}
t1.start();
t2.start();
}
Output:
4. Write a java program for inventory problem to illustrate the usage of thread synchronized
keyword and interthread communication process. They have three classes called consumer,
producer and stock.
(Or) Explain about interthread communication with example program.
• Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods. Inter-thread communication is all about allowing synchronized threads
to communicate with each other. These methods are implemented as final methods in Object,
so all classes have them. All three methods can be called only from within a synchronized context.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will
be granted access.
Consider the following sample program that implements a simple form of the producer/ consumer
problem. It consists of four classes: Queue, the queue that you’re trying to synchronize; 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.
class Queue
{
int n;
boolean valueSet = false;
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
}
n = x;
valueSet = true;
Queue q;
Producer(Queue q1) {
q = q1;
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
{
Queue q = new Queue();
Producer p=new Producer(q);
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
try
running");
catch (Exception e)
}
}
m1.start();
m2.start();
Output:
Thread 21 is running
Thread 22 is running
Often you will want the main thread to finish last. This can be accomplished by calling sleep( ) within main(
), with a long enough delay to ensure that all child threads terminate prior to the main thread. However, this
is hardly a satisfactory solution, and it also raises a larger question: How can one thread know when another
thread has ended? Fortunately, Thread provides a means by which you can answer this question.
1) First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown
here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. isAlive( ) is occasionally useful.
2) Most commonly used method to wait for a thread to finish is called join( ), shown here:
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.
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(100);
catch (InterruptedException e) {
System.out.println("Thread interrupted");
t1.start();
t2.start();
try {
t1.join();
t2.join();
catch (InterruptedException e) {
System.out.println("Thread interrupted");
System.out.println("Processing finished");
Output:
Thread-0
Thread-1
t1 Alive - true
t2 Alive - true
t1 Alive - false
t2 Alive - false
Processing finished
THREAD PRIORITIES:
• 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 running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example),
it will preempt the lower-priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:
• Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects.
• For example, suppose one thread enters the monitor on object X and another thread enters the monitor
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
access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is
a difficult error to debug for two reasons:
1) In general, it occurs only rarely, when the two threads time-slice in just the right way.
2) It may involve more than two threads and two synchronized objects.
// Use this editor to write, compile and run your Java code online
T1.start();
T2.start();
}
static class ThreadDemo1 extends Thread
synchronized (r1)
synchronized (r2)
synchronized (r2)
synchronized (r1)
}
}
}}
Output
As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the first
conditions that you should check for.
• The mechanisms to suspend, stop, and resume threads differ between early versions of Java, such as
Java 1.0, and more modern versions, beginning with Java 2. Prior to Java 2, a program used suspend( ),
resume( ), and stop( ), which are methods defined by Thread, to pause, restart, and stop the execution
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.
This was done because suspend( ) can sometimes cause serious system failures. Assume that a thread
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.
• The resume( ) method is also deprecated. It does not cause problems, but cannot be used without the
suspend( ) method as its counterpart. The stop( ) method of the Thread class, too, was deprecated by
Java 2. This was done because this method can sometimes cause serious system failures.
• Assume that a thread is writing to a critically important data structure and has completed only part of
its changes. If that thread is stopped at that point, that data structure might be left in a corrupted state.
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.
• Because you can’t now use the suspend( ), resume( ), or stop( ) methods to control a thread, you might
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( ) method
periodically checks to determine whether that thread should suspend, resume, or stop its own
execution. This is accomplished by establishing a flag variable that indicates the execution state of the
thread. As long as this flag is set to “running,” the run( ) method must continue to let the thread
execute. If this variable is set to “suspend,” the thread must pause. If it is set to “stop,” the thread must
terminate. Of course, a variety of ways exist in which to write such code, but the central theme will be
the same for all programs.
• The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object
can be used to control the execution of a thread. Let us consider its operation. The NewThread class
contains a boolean instance variable named suspendFlag, which is used to control the execution of the
thread. It is initialized to false by the constructor. The run( ) method contains a synchronized statement
block that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the
execution of the thread. The mysuspend( ) method sets suspendFlag to true. The myresume( ) method
sets suspendFlag to false and invokes notify( ) to wake up the thread. Finally, the main( ) method has
been modified to invoke the mysuspend( ) and myresume( ) methods.
String name;
Thread t;
boolean suspendFlag;
NewThread(String threadname)
name = threadname;
suspendFlag = false;
t.start();
try
Thread.sleep(200);
synchronized(this)
while(suspendFlag)
{
wait();
catch (InterruptedException e)
void mysuspend()
suspendFlag = true;
suspendFlag = false;
notify();
class SuspendResume
try
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
ob2.mysuspend();
Thread.sleep(1000);
ob2.myresume();
catch (InterruptedException e)
try
ob1.t.join();
ob2.t.join();
catch (InterruptedException e)
Output:
New thread: Thread[One,5,main]
One: 3
Two: 3
One: 2
Two: 2
One: 1Two: 1
One exiting.
Two exiting.
Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported
by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance.
Using objects for these values would add an unacceptable overhead to even the simplest of 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.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a
wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.
Character:
Character is a wrapper around a char. The constructor for Character is Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being created.
To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( )
Boolean
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString contains the string
“true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
By far, the most commonly used type wrappers are those that represent numeric values. These are Byte, Short,
Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number
declares methods that return the value of an object in each of the different number formats. These methods are
shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the value as a float,
and so on. These methods are implemented by each of the numeric type wrappers.
All of the numeric type wrappers define constructors that allow an object to be constructed from a given value,
or a string representation of that value. For example, here are the constructors defined for Integer:
Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of the type wrappers
override toString( ). It returns the human-readable form of the value contained within the wrapper. This allows
you to output the value by passing a type wrapper object to println( ), for example, without having to convert it
into its primitive type.The following program demonstrates how to use a numeric type wrapper to encapsulate
a value and then extract that value.
class Wrap {
int i = iOb.intValue();
This program wraps the integer value 100 inside an Integer object called iOb. The program then obtains this
value by calling intValue( ) and stores the result in i.
The process of encapsulating a value within an object is called boxing. Thus, in the program,
The process of extracting a value from a type wrapper is called unboxing. For example, the
int i = iOb.intValue();
The same general procedure used by the preceding program to box and unbox values has been employed since
the original version of Java. However, with the release of JDK 5, Java
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 the process by which the value of a boxed object is automatically extracted (unboxed) from a
type wrapper when its value is needed. There is no need to call a method such as intValue( ) or doubleValue( ).
The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms, removing
the tedium of manually boxing and unboxing values. It also helps prevent errors. Moreover, it is very important
to generics, which operates only on objects. Finally, autoboxing makes working with the Collections Framework
much easier.
With autoboxing it is no longer necessary to manually construct an object in order to wrap a primitive type. 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:
Notice that no object is explicitly created through the use of new. Java handles this for you, automatically.
To unbox an object, simply assign that object reference to a primitive-type variable. For example, to unbox iOb,
you can use this line:
// Demonstrate autoboxing/unboxing.
class AutoBox
{
Java also supplies wrappers for boolean and char. These are Boolean and Character. Autoboxing/unboxing
applies to these wrappers, too. For example, consider the following program:
class AutoBox5
Boolean b = true;
if(b)
System.out.println("b is true");
b is true
ch2 is x
CS3391/OBJECT ORIENTED PROGRAMMING
Unit-III
Part-A
1. What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of
the program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.
2. How the exceptions are handled in java? OR Explain exception handling mechanism in java?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not and occurred
exception is caught in the catch block or not.
4. Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally block.
You can remove either catch block or finally block but not both.
When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most
general ones. i.e sub classes of Exception must come first and super classes later. If you keep super classes first
and sub classes later, compiler will show unreachable catch block error.
Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.
One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.
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.
The other branch is topped by Error, which defines exceptions that are not expected to be caught 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.
Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions occur only
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.
11. What is the difference between final, finally and finalize in java?
final keyword :
finally Block :
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() method is a protected method of java.lang.Object class. It is inherited to every class you create in java.
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. What is the difference between throw, throws and throwable in java?
throw In Java :
throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can throw
an exception from any method or block. But, that exception must be of type java.lang.Throwable class or it’s sub
classes. Below example shows how to throw an exception using throw keyword.
throws In Java :
throws is also a keyword in java which is used in the method signature to indicate that this method may throw
mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-catch
blocks or using throws keyword. Below is the syntax for using throws keyword.
Throwable In Java :
Throwable is a super class for all types of errors and exceptions in java. This class is a member of
java.langpackage. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by the
throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to create
your own customized exceptions, then your class must extend this class. Click here to see the hierarchy of
exception classes in java.
15. Which class is the super class for all types of errors and exceptions in java?
java.lang.Throwable is the super class for all types of errors and exceptions in java.
5 Context switching from one process to Context switching from one thread to another is
another is costly. inexpensive.
The value of level must be within the range 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.
Part-B
1. Develop a java program for handling divide by zero exception with multiple catches.
2. Develop a java program for handling ArrayIndexOutOfBoundsException exception
with finally block.
3. Develop a java program for exception handling with throw and throws keyword.
4. Explain nested try/catch with example program.
5. Develop a java program with multiple catch clauses.
6. Develop a java program with multicatch that can handle both ArithmeticException
and IndexOutOfBoundsException.
catch,
throw,
throws,
finally.
• Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch this exception (using catch)
and handle it in some rational manner. System-generated exceptions are automatically thrown by
the Java run-time system.
• To manually throw an exception, use the keyword throw. Any exception that is thrown out of a
method must be specified as such by a throws clause. Any code that absolutely must be executed
after a try block completes is put in a finally block.
EXCEPTION HIERARCHY :
• All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions into two distinct
branches.
• One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch. 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.
• The other branch is topped by Error, which defines exceptions that are not expected to be caught
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.
Although the default exception handler provided by the Java run-time system is useful for debugging,
you will usually want to handle an exception yourself.
Program:
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack. If an inner try
statement does not have a catch handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the
Java run-time system will handle the exception. Here is an example that uses nested try statements:
Output:
Divide by 0: java.lang.ArithmeticException: / by zero
Output when a=1:
a=1
Divide by 0: java.lang.ArithmeticException: / by zero C:\>java
NestTry One Two
Output when a=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, if a method opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. The finally keyword is designed to
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 is thrown, the finally block will execute even if no catch statement matches the
exception.
An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.
3) BUILT-IN EXCEPTIONS:
Inside the standard package java.lang, Java defines several exception classes. The most general of
exceptions are the subclasses of the standard type RuntimeException. These exceptions
need not be included in any method's throws list.
Program:
class MultipleCatches
{
public static void main(String args[])
{
try
{
int a = 0;
System.out.println("a = " + a); int b =
42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
finally
{
System.out.println(" Finally block");
}
}
Output:
C:\>java MultipleCatches a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
Finally block
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, all exceptions, including those that you create, have the methods defined by Throwable
available to them.
Exception defines four constructors. Two support chained exceptions. The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify a description
of the exception.
Program:
Output:
• Thread is the smallest unit of dispatchable code. This means that a single program can perform
two or more tasks simultaneously. For instance, a text editor can format text at the same time
that it is printing, as long as these two actions are being performed by two separate threads.
• Threads are lighter weight. They share the same address space and cooperatively share the
same heavyweight process. Interthread communication is inexpensive, and context switching
from one thread to the next is lower in cost.
• Multithreading enables to write efficient programs that make maximum use of the
processing power available in the system. Multithreading keep the idle time to a minimum.
Threads exist in several states.
6) A thread can be running. It can be ready to run as soon as it gets CPU time.
7) A running thread can be suspended, which temporarily halts its activity.
8) A suspended thread can then be resumed, allowing it to pick up where it left off.
9) A thread can be blocked when waiting for a resource.
10) At any time, a thread can be terminated, which halts its execution immediately. Once
terminated, a thread cannot be resumed.
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
Given a Thread instance, you can use getState( ) to obtain the state of a thread. For
example, the following sequence determines if a thread called thrd is in the RUNNABLE state at the
time getState( ) is called:
Thread.State ts = 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
provide a means of synchronizing threads. It’s primarily used for debugging or for profiling a thread’s
run-time characteristics.
12. Develop a program for creating threads by using Thread class and Runnable interface.
(or) Why do we need both start() and run() method both? can we achieve it with only run()
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() method then a new separate thread is being allocated to the execution of run method, so if more
than one thread calls start() method that means their run method is being executed by separate threads
(these threads run simultaneously).
Java defines two ways in which this can be accomplished:
1) By extending the Thread class.
2) By implement the Runnable interface.
{
public static void main(String[] args)
{
m2.start();
}
}
Output:
Thread 21 is running
Thread 22 is running
5. Creating thread by using Runnable interface:
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just like the
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.
After you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb)
Thread(Runnable threadOb, String threadName)
Thread(String threadName)
{
try
{
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}
public class multithreadingdemo
{
public static void main(String[] args)
{
multithreading m1=new multithreading();
Thread t1 = new Thread(m1);
multithreading m2=new multithreading();
Thread t2 = new Thread(m2);
t1.start();
t2.start();
}
Output:
Thread 21 is running
Thread 22 is running
6. Develop a java program that provide synchronization for two threads deposit and withdraw
in a bank application.
(or) What is thread synchronization? Discuss with an example.
Answer:
When two or more threads need access to a shared resource, they need some way to ensure that the
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.
Synchronization is easy in Java, because all objects have their own implicit monitor associated with
them. To enter an object’s monitor, just call a method that has been modified with the synchronized
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:
class bank{
int amount=5000;
synchronized void transaction(int n,char c ){
try
{
if (c=='d')
{
System.out.println("Before deposit Balance ="+amount);
amount =amount+n;
}
public void run(){
t.transaction(4000,'d');
}
}
class withdraw extends Thread{
bank t;
withdraw(bank x){
t=x;
}
public void run(){
t.transaction(2000,'w');
}
}
Output:
Before deposit Balance =5000
After deposit Balance =9000
Before withdraw Balance =9000
After withdraw Balance =7000
2)The synchronized Statement: (synchronized block)
While creating synchronized methods within classes that you create is an easy and effective means
of achieving synchronization, it will not work in all cases. To understand why, consider the following.
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, this class was not created by you, but by a third party, and you do not have access to the
source code. Thus, you can’t add synchronized to the appropriate methods within the class. How
can access to an object of this class be synchronized? Fortunately, the solution to this problem is
quite easy: You simply put calls to the methods defined by this class inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
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:
class bank{
int amount=5000;
catch(Exception e){System.out.println(e);}
}
}
deposit(bank x){
t=x;
}
t.transaction(4000,'d');
}
}
t2.start();
}
}
Output:
Before deposit Balance =5000
After deposit Balance =9000
Before withdraw Balance =9000
After withdraw Balance =7000
7. Write a java program for inventory problem to illustrate the usage of thread synchronized
keyword and interthread communication process. They have three classes called consumer,
producer and stock.
(Or) Explain about interthread communication with example program.
• Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods. Inter-thread communication is all about allowing synchronized threads
to communicate with each other. These methods are implemented as final methods in Object,
so all classes have them. All three methods can be called only from within a synchronized context.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will
be granted access.
Consider the following sample program that implements a simple form of the producer/ consumer
problem. It consists of four classes: Queue, the queue that you’re trying to synchronize; 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.
class Queue
{
int n;
boolean valueSet = false;
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
}
n = x;
valueSet = true;
Queue q;
Producer(Queue q1) {
q = q1;
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
{
Queue q = new Queue();
Producer p=new Producer(q);
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
try
running");
catch (Exception e)
}
}
m1.start();
m2.start();
Output:
Thread 21 is running
Thread 22 is running
Often you will want the main thread to finish last. This can be accomplished by calling sleep( ) within main(
), with a long enough delay to ensure that all child threads terminate prior to the main thread. However, this
is hardly a satisfactory solution, and it also raises a larger question: How can one thread know when another
thread has ended? Fortunately, Thread provides a means by which you can answer this question.
3) First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown
here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise. isAlive( ) is occasionally useful.
4) Most commonly used method to wait for a thread to finish is called join( ), shown here:
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.
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(100);
catch (InterruptedException e) {
System.out.println("Thread interrupted");
t1.start();
t2.start();
try {
t1.join();
t2.join();
catch (InterruptedException e) {
System.out.println("Thread interrupted");
System.out.println("Processing finished");
Output:
Thread-0
Thread-1
t1 Alive - true
t2 Alive - true
t1 Alive - false
t2 Alive - false
Processing finished
THREAD PRIORITIES:
• 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 running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example),
it will preempt the lower-priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:
• Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects.
• For example, suppose one thread enters the monitor on object X and another thread enters the monitor
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
access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is
a difficult error to debug for two reasons:
3) In general, it occurs only rarely, when the two threads time-slice in just the right way.
4) It may involve more than two threads and two synchronized objects.
// Use this editor to write, compile and run your Java code online
T1.start();
T2.start();
}
static class ThreadDemo1 extends Thread
synchronized (r1)
synchronized (r2)
synchronized (r2)
synchronized (r1)
}
}
}}
Output
As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the first
conditions that you should check for.
• The mechanisms to suspend, stop, and resume threads differ between early versions of Java, such as
Java 1.0, and more modern versions, beginning with Java 2. Prior to Java 2, a program used suspend( ),
resume( ), and stop( ), which are methods defined by Thread, to pause, restart, and stop the execution
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.
This was done because suspend( ) can sometimes cause serious system failures. Assume that a thread
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.
• The resume( ) method is also deprecated. It does not cause problems, but cannot be used without the
suspend( ) method as its counterpart. The stop( ) method of the Thread class, too, was deprecated by
Java 2. This was done because this method can sometimes cause serious system failures.
• Assume that a thread is writing to a critically important data structure and has completed only part of
its changes. If that thread is stopped at that point, that data structure might be left in a corrupted state.
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.
• Because you can’t now use the suspend( ), resume( ), or stop( ) methods to control a thread, you might
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( ) method
periodically checks to determine whether that thread should suspend, resume, or stop its own
execution. This is accomplished by establishing a flag variable that indicates the execution state of the
thread. As long as this flag is set to “running,” the run( ) method must continue to let the thread
execute. If this variable is set to “suspend,” the thread must pause. If it is set to “stop,” the thread must
terminate. Of course, a variety of ways exist in which to write such code, but the central theme will be
the same for all programs.
• The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object
can be used to control the execution of a thread. Let us consider its operation. The NewThread class
contains a boolean instance variable named suspendFlag, which is used to control the execution of the
thread. It is initialized to false by the constructor. The run( ) method contains a synchronized statement
block that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the
execution of the thread. The mysuspend( ) method sets suspendFlag to true. The myresume( ) method
sets suspendFlag to false and invokes notify( ) to wake up the thread. Finally, the main( ) method has
been modified to invoke the mysuspend( ) and myresume( ) methods.
String name;
Thread t;
boolean suspendFlag;
NewThread(String threadname)
name = threadname;
suspendFlag = false;
t.start();
try
Thread.sleep(200);
synchronized(this)
while(suspendFlag)
{
wait();
catch (InterruptedException e)
void mysuspend()
suspendFlag = true;
suspendFlag = false;
notify();
class SuspendResume
try
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
ob2.mysuspend();
Thread.sleep(1000);
ob2.myresume();
catch (InterruptedException e)
try
ob1.t.join();
ob2.t.join();
catch (InterruptedException e)
Output:
New thread: Thread[One,5,main]
One: 3
Two: 3
One: 2
Two: 2
One: 1Two: 1
One exiting.
Two exiting.
Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported
by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance.
Using objects for these values would add an unacceptable overhead to even the simplest of 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.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a
wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.
Character:
Character is a wrapper around a char. The constructor for Character is Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being created.
To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( )
Boolean
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In the second version, if boolString contains the string
“true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
By far, the most commonly used type wrappers are those that represent numeric values. These are Byte, Short,
Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number
declares methods that return the value of an object in each of the different number formats. These methods are
shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the value as a float,
and so on. These methods are implemented by each of the numeric type wrappers.
All of the numeric type wrappers define constructors that allow an object to be constructed from a given value,
or a string representation of that value. For example, here are the constructors defined for Integer:
Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of the type wrappers
override toString( ). It returns the human-readable form of the value contained within the wrapper. This allows
you to output the value by passing a type wrapper object to println( ), for example, without having to convert it
into its primitive type.The following program demonstrates how to use a numeric type wrapper to encapsulate
a value and then extract that value.
class Wrap {
int i = iOb.intValue();
This program wraps the integer value 100 inside an Integer object called iOb. The program then obtains this
value by calling intValue( ) and stores the result in i.
The process of encapsulating a value within an object is called boxing. Thus, in the program,
The process of extracting a value from a type wrapper is called unboxing. For example, the
int i = iOb.intValue();
The same general procedure used by the preceding program to box and unbox values has been employed since
the original version of Java. However, with the release of JDK 5, Java
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 the process by which the value of a boxed object is automatically extracted (unboxed) from a
type wrapper when its value is needed. There is no need to call a method such as intValue( ) or doubleValue( ).
The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms, removing
the tedium of manually boxing and unboxing values. It also helps prevent errors. Moreover, it is very important
to generics, which operates only on objects. Finally, autoboxing makes working with the Collections Framework
much easier.
With autoboxing it is no longer necessary to manually construct an object in order to wrap a primitive type. 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:
Notice that no object is explicitly created through the use of new. Java handles this for you, automatically.
To unbox an object, simply assign that object reference to a primitive-type variable. For example, to unbox iOb,
you can use this line:
// Demonstrate autoboxing/unboxing.
class AutoBox
{
Java also supplies wrappers for boolean and char. These are Boolean and Character. Autoboxing/unboxing
applies to these wrappers, too. For example, consider the following program:
class AutoBox5
Boolean b = true;
if(b)
System.out.println("b is true");
b is true
ch2 is x
CS3391/OBJECT ORIENTED PROGRAMMING
Unit-III
Part-A
2. What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of
the program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.
3. How the exceptions are handled in java? OR Explain exception handling mechanism in java?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not and occurred
exception is caught in the catch block or not.
5. Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either catch or finally block.
You can remove either catch block or finally block but not both.
When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most
general ones. i.e sub classes of Exception must come first and super classes later. If you keep super classes first
and sub classes later, compiler will show unreachable catch block error.
Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.
One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.
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.
The other branch is topped by Error, which defines exceptions that are not expected to be caught 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.
Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions occur only
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.
12. What is the difference between final, finally and finalize in java?
final keyword :
finally Block :
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() method is a protected method of java.lang.Object class. It is inherited to every class you create in java.
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.
14. What is the difference between throw, throws and throwable in java?
throw In Java :
throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can throw
an exception from any method or block. But, that exception must be of type java.lang.Throwable class or it’s sub
classes. Below example shows how to throw an exception using throw keyword.
throws In Java :
throws is also a keyword in java which is used in the method signature to indicate that this method may throw
mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-catch
blocks or using throws keyword. Below is the syntax for using throws keyword.
Throwable In Java :
Throwable is a super class for all types of errors and exceptions in java. This class is a member of
java.langpackage. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by the
throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to create
your own customized exceptions, then your class must extend this class. Click here to see the hierarchy of
exception classes in java.
26. Which class is the super class for all types of errors and exceptions in java?
java.lang.Throwable is the super class for all types of errors and exceptions in java.
5 Context switching from one process to Context switching from one thread to another is
another is costly. inexpensive.
The value of level must be within the range 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.
Part-B
23. Develop a java program for handling divide by zero exception with multiple catches.
24. Develop a java program for handling ArrayIndexOutOfBoundsException exception
with finally block.
25. Develop a java program for exception handling with throw and throws keyword.
26. Explain nested try/catch with example program.
27. Develop a java program with multiple catch clauses.
28. Develop a java program with multicatch that can handle both ArithmeticException
and IndexOutOfBoundsException.