Professional Documents
Culture Documents
(18CS45)
Module-IV
Course Outcome:
The student will be able to :
Explain the object-oriented concepts and JAVA.
Develop computer programs to solve real world problems in Java.
Develop simple GUI interfaces for a computer program to interact with users, and to
understand the event-based GUI handling principles using swings
CO-PO and CO-PSO Mapping
P P P P P P P
P P P P P P P P
Modules PO O O O S S S S
Course Outcomes Blooms Level O O O O O O O O
covered 5 1 1 1 O O O O
1 2 3 4 6 7 8 9
0 1 2 1 2 3 4
Explain Object-Oriented
CO1 Concepts in C++ and L2 1,2 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
JAVA.
Develop computer
programs for solution of
CO2 L2 2,3 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
real world problems in
Java.
Develop simple GUI
CO3 interfaces for L3 4,5 2 3 3 2 2 2 - - 2 2 - 2 2 - 2 -
interaction with users
Develop Graphical User
CO4 Interface (GUI) with use L3 5 2 3 3 3 2 2 - - 2 2 - 2 2 - 2 -
of Applets and Swings.
Text Book & Reference Book
Textbooks:
1. Sourav Sahay, Object Oriented Programming with C++ , 2nd Ed, Oxford University
Press,2006
2. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007.
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806
2. Herbert Schildt, The Complete Reference C++, 4th Edition, Tata McGraw Hill, 2003.
3. Stanley B.Lippmann, Josee Lajore, C++ Primer, 4th Edition, Pearson Education, 2005.
4. Rajkumar Buyya,S Thamarasi selvi, xingchen chu, Object oriented Programming with java,
Tata McGraw Hill education private limited.
5. Richard A Johnson, Introduction to Java Programming and OOAD, CENGAGE Learning.
6. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies
Content
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
Packages
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive
data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package
names.
Advantages of using a package in Java
• Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in our
code. Using packages, you can create such things in form of classes
inside a package and whenever you need to perform that same task,
just import that package and use the class.
• Better Organization: Again, in large java projects where we
have several hundreds of classes, it is always required to group the
similar types of classes in a meaningful package name so that you can
organize your project better and when you need something you can
quickly locate it and use it, which improves the efficiency.
• Name Conflicts: We can define two classes with the same
name in different packages so to avoid name collision, we can use
packages
Steps for Creating & accessing package in Java
Steps:
• Create a package with a .class file
• set the classpath from the directory from which you would like to access. It
may be in a different drive and directory. Let us call it as a target directory.
• Write a program and use the file from the package.
Let us create a package called forest and place a class called Tiger in it.
Access the package from a different drive and directory.
1st Step: Create a package (forest) and place Tiger.class in it.
• Let us assume C:\snr is the current directory where we would like to create
the package.
• C:\snr > notepad Tiger.java
Order of Package Statement
The above program coding wise is very simple but is important to know
the steps of package creation:
package forest;
import java.util.*;
public class Tiger
If exists, the package statement must be first one in the program. If exists, the
import statement must be the second one. Our class declaration is the third. Any
order changes, it is a compilation error.
When the code is ready, the next job is compilation. We must compile with
package notation. Package notation uses –d compiler option as follows.
C:\snr > javac -d . Tiger.java
• The –d compiler option creates a new folder called forest and places the
Tiger.class in it. The dot (.) is an operating system's environment variable that
indicates the current directory. It is an instruction to the OS to create a
directory called forest and place the Tiger.class in it.
Using User Defined Packages Java
After creating the package let us use it.
2nd step: Set the classpath from the target directory.
Let us assume D:\sumathi is the target directory. Let us access Tiger.class in forest
package from here.
From the target directory set the classpath following way.
D:\sumathi> set classpath=C:\snr;%classpath%;
classpath is another environment variable which gives the address of the forest
directory to the OS. %classpath% informs the OS to append the already existing
classpath to the current classpath that is right now set.
3rd Step: Now finally, write a program from the target directory
D:/sumathi and access the package.
• The import statement can be written at the beginning of the Java program,
using the keyword import.
Various ways to access the package from outside
the package in Java using import
There are three ways to access the package from outside the package.
❑ import package.*;
❑ import package.classname;
If you use package.* then all the classes and interfaces of this package will be
accessible but not sub packages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A
{
public void msg()
{System.out.println("Hello");}
Output: Hello
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}}
2) Using packagename.classname
If you import package.classname then only declared class of
this package will be accessible.
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name, then only declared class of this
package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:Hello
Access Protection
The access modifiers in java specify accessibility (scope) of a data member,
method, constructor or class.
There are 4 types of java access modifiers:
• private
• default
• protected
• public
private access modifier
The private access modifier is accessible only within class.
default access modifier
If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package.
Access Protection
protected access modifier
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
}
Package Test;
Public class class1 void fun2()
{ {
Public int a;
Int b; }
Private int c;
private void fun3()
{
}
public class class2
{
Void My_method()
{
class1 Obj=new class1()
Obj.a;//allowed
Obj.b//allowed
Obj.c;//error
Obj.fun1();//allowed
Obj.fun2();//allowed
Obj.fun3();//error
}
}
Interfaces
✓ An interface in java is a blueprint of a class. It has static final variables
and abstract methods.
✓ The interface in java is a mechanism to achieve abstraction. There
can be only abstract methods in the java interface that does not contain
method body. It is used to achieve abstraction and multiple inheritance in
Java.
✓ It cannot be instantiated just like abstract class.
✓ Interface fields are public, static and final by default, and methods are
public and abstract.
Interfaces
interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}
Understanding relationship between classes and interfaces
interface printable
{
void print();
}
class Pgm1 implements printable
{
public void print()
{
System.out.println("Hello");
}
}
Interfaces
class IntefacePgm1
{
public static void main(String args[])
{
Pgm1 obj = new Pgm1 ();
obj.print();
}
}
Output:
Hello
Example 2
//Implementation: by second user
//Interface declaration: by first user
Interface class Rectangle implements Drawable
{
Drawable public void draw()
{ {
void draw(); System.out.println("drawing rectangle");
} }
}
d.draw();
}
}
Output:
drawing circle
Multiple inheritance in Java by interface
✓ If a class implements multiple interfaces, or an interface
extends multiple interfaces i.e. known as multiple inheritance.
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Pgm2 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
Output:
Hello
Welcome
Multiple inheritance is not supported through class in Java, but it is
possible by interface, why?
interface Printable
{
void print();
}
interface Showable
{
void print();
}
class InterfacePgm1 implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
} ✓ As you can see in the example
class InterfaceDemo
program, Printable and
{
public static void main(String args[]) Showable interface have same
{
methods, but its
InterfacePgm1 obj = new
InterfacePgm1 (); obj.print(); implementation is provided by
}
} class InterfacePgm1, so there
Output: is no ambiguity.
Hello
Interface inheritance
A class implements interface, but one interface extends another
interface .
interface Printable
void print();
{
}
Hello Welcome
Program to implement Stack
}
else
{
Interfaces
top--;
}
System.out.println("Pop operation done !");
}
}
}
Interfaces
class MyPgm
{
stackDemo.pop();
stackDemo.pop();
}
}
Chapter 2: Multi Threaded Programming
Q) What is Thread? Explain two ways of creation of thread in Java with
example.
A thread is a path of execution within a process.
There are two ways to specify what code the thread should execute.
• The first is to create a subclass of Thread and override the run() method.
• The second method is to pass an object that implements Runnable (java.lang.
Runnable) to the Thread constructor.
The first way to specify what code a thread is to run, is to create a
subclass of Thread and override the run() method. The run() method is
what is executed by the thread after you call start(). Here is an example of
creating a Java Thread subclass:
• The extending class must override the run() method, which is the entry point for
the new thread.
• It must also call start() to begin execution of the new thread.
If the class extends the Thread class, the thread can be run by creating an instance
of the class and call its start() method:
Extend : Example 1
1. If a class extends a thread class, then it cannot extend any other class which
may be required to extend
2. If a class thread is extended, then all its functionalities get inherited. This is
an expensive operation.
Steps to create a thread by implementing Runnable interface,
• Create a class that implements the Runnable interface.
• After you create a class that implements Runnable, you will
instantiate an object of type Thread from within that class.
Differences between
class Multi3 implements Runnable
"extending" and
{
"implementing" Threads
public void run(){
System.out.println("thread is running...");
The major difference is that
}
when a class extends the
Thread class, you cannot
public static void main(String args[]){
extend any other class, but by
Multi3 m1=new Multi3();
implementing the Runnable
//Using the constructor Thread(Runnable r)
interface, it is possible to
Thread t1 =new Thread(m1);
extend from another class as
t1.start();
well, like: class MyClass
}
extends OtherClass
}
implements Runnable.
Example program -2
1.New
2.Runnable
3.Blocked
4.Waiting
5.Timed Waiting
6.Terminated
Q) Lifecycle and States of a Thread in Java
The diagram shown below represent various states of a thread at any instant of time.
New Thread: When a new thread is created, it is in the new state. The thread has
not yet started to run when thread is in this state. When a thread lies in the new
state, it’s code is yet to be run and hasn’t started to execute.
Declaration: public static final Thread. State NEW
Runnable State: A thread that is ready to run is moved to runnable state. In this
state, a thread might actually be running or it might be ready to run at any instant of
time. It is the responsibility of the thread scheduler to give the thread, time to run.
Declaration: public static final Thread. State RUNNABLE
Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the
following states:
• Blocked
• Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state.
It’s the responsibility of the thread scheduler to reactivate and schedule a
blocked/waiting thread. A thread in this state cannot continue its execution any further
until it is moved to runnable state. Any thread in these states does not consume any
CPU cycle. Once the thread wait state is over or it is, it’s state is changed to RUNNABLE
and it’s moved back to thread pool.
Declaration: public static final Thread. State BLOCKED
Declaration: public static final Thread. State WAITING
Timed Waiting: A thread lies in timed waiting state when it calls a method with a time-
out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep() or a conditional wait, it
is moved to a timed waiting state. Timed waiting threads and waiting threads cannot
use a processor, even if one is available.
Declaration: public static final Thread. State TIMED_WAITING
Terminated State: A thread terminates because of either of the following reasons:
• Because it exists normally. This happens when the code of thread has entirely
executed by the program.
• Because there occurred some unusual erroneous event, like segmentation fault or
an unhandled exception.
A thread that lies in a terminated state does no longer consumes any cycles of CPU.
A thread enters the TERMINATED state (sometimes called the dead state) when it
successfully completes its task or otherwise terminated due to any error or even it was
forcefully killed.
System.out.println(t.getState()); //Output :
NEW
}
}
Program for RUNNABLE state
A thread will be in this state after calling the start() method.
t.start();
When we are using multiple threads in our application, we’ll create the
threads and call the start() method on these threads. It’s the Java
Virtual Machine that calls the run method of this thread when the
resources and CPU are ready. Then the thread will execute the run()
method and later transition to terminated state.
• public final void join()- Waits indefinitely for this thread to die.
• public final void join(long millis)-Waits at most millis milliseconds for this thread to die. A
timeout of 0 means to wait forever.
• public final void join(long millis, int nanos)- Waits at most millis milliseconds plus nanos
nanoseconds for this thread to die.
Example program to demonstrate the use of isAlive():
All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor. These other threads are said to be waiting for the monitor.
A thread that owns a monitor can re-enter the same monitor if it so desires.
As Java implements synchronization through language elements, most of the
complexity associated with synchronization has been eliminated.
Two ways of synchronization:
We can synchronize code in two ways
1. Using synchronized methods
2. using synchronized statement/ Block
• When one thread is executing a synchronized method for an object, all other threads
that invoke synchronized methods for the same object block (suspend execution) until
the first thread is done with the object.
Syntax: synchronized return-type method-name (parameter list);
}
class MyThread2 extends Thread
class MyThread1 extends Thread {
{ Table t;
Table t; // //reference to object of class Table MyThread2(Table t)
MyThread1(Table t) {
{ this.t=t;
this.t=t; }
} public void run()
public void run() {
{ t.printTable(100);
t.printTable(5); }
} }
you can see both Threads are accessing Print Resource. One thread writes something
and then goes to sleep. If synchronization is not implemented here, i.e. if the resource is
not restricted for access by only 1 thread at a time, then the Second Thread will awake
and write something in middle of access by the 1st thread. So this will go on and on until
termination and result in Data Issues.
public class TestSynchronization2
{ Output:
public static void main(String args[])
5
{ 10
Table obj = new Table(); //only one object 15
MyThread1 t1=new MyThread1(obj); 20
MyThread2 t2=new MyThread2(obj); 25
t1.start(); 100
t2.start(); 200
} 300
} 400
500
2.using synchronized statement/Block
Synchronized block can be used to perform synchronization on any specific resource of
the method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5
lines, in such cases, we can use synchronized block.
Synchronized statements must specify the object that provides the intrinsic lock:
Synchronized block provides granular control over lock, as you can use
any lock to provide mutual exclusion to critical section code.
Synchronized method always lock either on current object or class level
lock, if its static synchronized method.
Producer Consumer Problem : Interthread Communication
Two or more threads communicate with each other by exchanging
the messages. This mechanism is called inter-thread communication.
The wait () and notify() methods are used to send particular thread to
sleep or to resume the thread from sleep mode respectively.
Bounded Buffer Problem
• The producer inserts data in the buffer and Consumer deletes the
data from the buffer.
Thread priorities
We can also set the priority of thread between 1 to 10. This priority
is known as custom priority or user defined priority.
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. These priorities are
defined as static final variables within Thread.
You can obtain the current priority setting by calling the getPriority(
) method of Thread, shown here:
final int getPriority( )
Example 1: Maximum Priority Thread