Download as pdf or txt
Download as pdf or txt
You are on page 1of 1373

PROGRAMMING IN JAVA

Prof. Debasis Samanta


Computer Science and Engineering
IIT Kharagpur
INDEX

S.No. Topic Page No.


WEEK- 1
1 Introduction 1
2 Java Programming Environment 24
3 Java Tools and Resources 41
4 Demonstration – 1 69
5 Java Applet Programming 85
WEEK- 2

6 Demonstration – II 108
7 Encapsulation 129
8 Demonstration – III 151
9 Java Programming Insights 172
10 Demonstration –IV 194
WEEK- 3
11 Java Scope Rule 217
12 Demonstration – V 235
13 Inheritance 261
14 Demonstration – VI 289
15 Information Hiding 313

WEEK- 4

16 Demonstration – VII 334


17 Packages – I 359
18 Packages – II 379
19 Demonstration – VIII 400
20 Interfaces – I 426
WEEK- 5
21 Interfaces – II 448
22 Demonstration – IX 469
23 Exception Handling – I 495
24 Exception Handling – II 515
25 Exception Handling – III 532
WEEK- 6
26 Demonstration – X 552
27 Multithreading – I 569
28 Multithreading – II 594
29 Demonstration – XI 620
30 I – O Stream – I 641
WEEK- 7
31 I – O Stream – II 655
32 I-O Stream – III 677
33 Demonstration – XII 695
34 Applet Programming – I 720
35 Applet Programming – II 740
WEEK- 8

36 Applet Programming – III 763


37 Demonstration – XIII 719
38 Demonstration – XIV 814
39 A W T Programming-I 831
40 A W T Programming-II 871
WEEK- 9
41 Demonstration -XV 896
42 A W T Programming – III 921
43 Swing Programming - I 960
44 Swing Programming - II 1000
45 Demonstration –XVI 1038
WEEK- 10

46 Demonstration – XVII 1063


47 Demonstration – XVIII 1081
48 Java Networking 1100
49 Demonstration-XIX 1141
50 JDBC – I 1161
WEEK- 11
51 JDBC – II 1183
52 JDBC – III 1212
53 Demonstration – XX 1232
54 Demonstration – XXI 1255
55 Demonstration – XXII 1274
WEEK- 12

56 Case Study – I 1289


57 Case Study – II 1305
58 Case Study – III 1325
59 Case Study – IV 1339
60 Case Study – V 1353
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 01
Introduction

First of all I wish like to welcome you all to the course. So, this is the first lecture. In this
first lecture I will try to cover the Basic Concept of Java Programming. Now this course
is being offered with a huge effort, I would like to introduce the team who are involved.
So myself, Debasis Samanta from IIT Kharagpur and then Tauheed Ahmed is a Research
Scholar in our institution and then another Research Scholar is Niranjan Sinhababu.

So, they are basically will act as a TA and then will support me, and then also they will
be always available for any queries that you can have right. So, you are feel free to ask
any questions there is a discussion forum, so that we can write attend your questions and
then give the answer as within a shortest possible time. And also we are always available
and you can contact us using our email address anytime; whatever it is required for you.

(Refer Slide Time: 01:35)

Now, this course needs few reference materials. So, there is a very good book on
programming with Java the title is called Complete Reference Java 2; as on today 10th
edition is available and it is published from the Tata Mc-Graw Hill Indian edition. In
addition to this there is a one another book is available publish from the Prentice Hall of

1
India written by me: this is the Object Oriented Programming with C++ and Java. The
second book is very useful for the beginners because it is written in a very simple and
easy way so that you can understand as quick as possible.

Other than these two books I advise you to look into the web page; that is the link it is
given here. And this link will give you a lot of materials and then the programs which
will be covered in this course, so that you can access it and you can use the quotes for
your practice. So, in addition to the code also some explanation and then why, and then
frequently asked questions all these things is also included in this link. So, this is a very
good link and you should use this link while you are attending this course.

(Refer Slide Time: 03:02)

Now, I just want to tell about the overview of the course, this course is paid over the 60
lectures. And here we can see the week wise planning of the course; that mean what are
the topics that will be covered in a particular week that is planned in a well manner. In
addition to this lecture schedules time to time we will cover the demonstration; that
means, you will see that if this is the code and you see how to run this code, and if you
run this code why this code is giving this output for this input or why this code needs a
special attention, so that you can learn many detail things about the programming. So,
lectures as well as the demonstrations is very useful, and then I think it is very helpful for
you to learn the course very easily.

2
And at the end of the course basically the last week, the week 12 we will cover a project
right. And then we will discuss about that how a software can be developed using the
experience that you have gathered, right. So, I hope we the running skill that you will
earn from this course will helpful for you to develop a projects; obviously, this is a mini
project that can be covered in 5 lecture hours actually. So, you will get a full flavor of the
programming and then, it will boost your confidence to develop any software of your
own.

Now let us come to the Concept of Java Programming. Just give a brief history of Java
programming. So, Java programming is now little bit matured, maybe say I can say 23
years old or so. But the first time it was introduced the 1991, there is a team they are
called the Green Team. Green Team from the sun micro system lab, Sun system lab is
very famous for developing hardware and software, and they have many contributions in
the field of information and technology.

Now, from this green team the pioneer is James Gosling and his colleagues Mike
Sheridan and Patrick Naughton. They first time introduce the concept of object oriented
programming. And they give the name of the programming has Greentalk initially; as it
is from the green team so they call it as a Greentalk. And then Java initially was designed
for a small embedded system and suitable for many electronic appliances like set of
boxes and then fees and all these things, but it was too advanced technology for the
digital cable television industry at that time in fact.

3
So, later on they developed a more improved version of the concept and they gave the
name is called Oak. And this is basically under a green project proposed by the green
team. And then later the same concept has been included in a very famous the giant in
software industries call the Netscape. So, Netscape is basically very famous for
networking, network related programming. So, they adapted this Oak technology in their
own work.

Later on, the Oak actually they gave initially the name Oak, because Oak is very famous
and is basically nationality in many European countries like Canada, USA, UK fine
Germany right. So, they later on was searching that the name should be very suitable as
the programming favor it is. In fact, they have an idea about that this programming really
is very cool, lively, dynamic, revolutionary and easy to spell and fun to say. So, they
were searching many names replacing Oak. Then in 1995 the Gosling introduced the
name Java. In fact, Java is an island of Indonesia, where best coffee of the world is
produced.

In fact, Gosling was very fond of coffee, that is why he choose the name Java for this
programming setup. In fact, the Java is so, popular that in 1995 the Time Magazine
awarded the Java as one of the best product. And then, with this popularity and then
maturity in 1996 this is the Sun Micro system first times, introduced a full set of
programming environment, they call it as JDK- Java Development Kit it was released in
January 23 1996. So, this gives you a brief history of the Java and why the name of the
programming is Java.

4
(Refer Slide Time: 08:47)

Now, the developer in fact, claim that the Java programming is very simple it is portable;
that means, you can use it any environment and, it is very secure and it is high performed
high performance, the multithreaded, interpreted, platform independent, dynamic
architecturally neural, object oriented and finally, it is a robust. So, basically these are
the different what is call the features, or you can say the parameters or specifications that
Java programming has its. And this is a really a unique programming environment that is
why it is a best programming language so far in fact.

(Refer Slide Time: 09:38)

5
In fact, so far the popularity score is concerned, here is the graph I have given you can
see the graph here. And in this graph we can see the score, that the different
programming language has so, for their popularities are concerned.

And as you see out of any programming language Java stands on the top. Java has the
highest popularity score compared to any other programming languages. There are
similar programming languages for object oriented programming like C++, C star
whatever it is, but Java is one unique of its own. In fact, Java has consistently been more
popular, than any other programming language that I have listed here around the year.
And so, I can say that Java has worldwide popularity.

Java is really very good for parallel and distributed program development and, the Java is
basically is a basic programming environments suitable for android mobile operating
system android platform. And you know, android programming is now increasing its
demand, because of the huge development of mobile communication, and mobile
technology. And platform independence, we will discuss in details about how Java is
platform; that means, it can run in any machine in any software in any operating system
and then more precisely Java is very much reliable and high speed and then very good
and accurate programming environment.

(Refer Slide Time: 11:30)

So, this is why Java is now very popular. Now, I will just discuss about how Java is
different from the other programming environment.

6
(Refer Slide Time: 11:38)

Now, in any programming environment, we know the concept that is used is that it
basically take an input and then produce an output. In order to do these things it basically
use an architecture and that architecture is popularly called von Neumann architecture.
So, in this von Neumann architecture the program is loaded into this memory. And then
from this program is then executed by the CPU it is called the control unit as well as the
arithmetic and logic unit this is basically mainly for the; this part is basically for the
execution.

So, this is the architecture that is used. So, it is not a new things so, this is the old known
things and starting from the inception of computer, this is the architecture the von
Neumann architecture being followed.

Sir, [FL].

[FL].

It clear that a (Refer Time: 12:43) may be like this (Refer Time: 12:44).

[FL] ok.

[FL]

[FL] fine.

7
(Refer Time: 12:59) thank you sir.

So basically the idea about the programming is that we can handle the different types of
input and, also we should produce output suitable for the different.Here basically we
have discuss the what are the different types of the input that a program should take care.
And then the output also the program should produce.

(Refer Slide Time: 13:29)

So, this is the ideal about it. And now, in order to have this kind of flavor; that means, to
deal with the different input and then the different outputs using the conventional
programming or whatever the programming, what are the different practices are
available. So, I just want to quickly give a brief overview of the different the
programming practices that it is there.

So, programming is of three types actually: the first is called the program whenever it is
written in machine level. So, it is shown in the machine level programming. And then the
program can be written in assembly level and the program can be written in high level
language. So, machine level language actually the code if you see it is stored in the
binary form, in terms of 1 and 0s, whereas, the program if you write in an assembly
language it is in the form of some new mini codes like add MOV sub like this. So, these
are the basically codes for different operations. And third generation language or it is call
the high level programming language is basically more or similar to English look like.

8
So, definitely the third high level programming language is most suitable for many
programmer, because it is easy to write their own program in contrast to the machine
level and then assembly level. Now, if you write a program in assembly language, then it
does not record to do anymore processing it will straightway can run your program.
However, if you write a program in assembly language, then we need to translate this
program into machine level language. And there is a program is known for this is called
the assembler. So, assembler will convert or rather we can say translate a program
written in machine level assembly level language to machine level language.

On the other high level programming language also need to be translated into machine
level language. So, far this translation there are two modes available one is the compiler
another interpreter. So, compiler will translate the entire program at one go and produce
the machine level code whereas, interpreter will run one statement at a time.

It will basically translate one statement and then run it then next statement and run it and
on the way if they find any error in the program. So, the exhibition will hold or it will
just bypass that statement and then proceed to the next statement so these are. But on the
other hand compiler will check that the program is written correctly, then only it will
produce the machine level code. So, this is a concept that is being used. So, for the
programming different programming language is concerned, I mention these thing
because you will be able to understand that how it basically makes a sense so that the
comparable to other programming languages.

9
(Refer Slide Time: 16:23)

Before going to these things I just want to say few I mean generation of language. In
fact, the machine level programming is it is the first generation of programming
language. Later on the second generation programming language is basically with
assembly language programming, those are basically suitable for microprocessor level
programming. And then next level programming is called the third generation
programming language. There are different programming languages like C, C++, C
sharp, Java, the visual BASIC, FORTRAN all these are basically belongs to this third
generation programming language.

Now, third generation programming language needs a skill from the programmer that
how to solve a problem. Now recently there is another high level programming is called
the fourth generation programming popularly called the 4 GL. And these basically does
not require so, much programming afford from the user the programmer should tell what
to do. So, the third generation language if it is how to do, then the fourth generation
language is what to do. And example of fourth generation language is SQL structured
query language that we used to delete the database.

So, in this course we will also use this 4 GL; that means, Java can interact from its 3 GL
flavor to the 4 GL things.

10
(Refer Slide Time: 18:06)

So, there are different programming languages paradigm of course, Java belongs to third
generation programming languages. Now let us see; what are the principles that the
different high level programming languages follows.

(Refer Slide Time: 18:13)

Now, whatever the principles are there, they can be broadly classified into two broad
categories one is called the function oriented programming and, then another is called the
object oriented programming. In the concept of function oriented programming, the
entire program is decomposed into last set of small functions.

11
So, in this program I can see that we see that there are last these are the basically
function. So, these are the different functions. So, you can decompose the entire program
into a small set of a last set of functions you can need so; that means, it is fragmented.
And all these functions basically shared a data which are common to all functions. So,
this is called the global data.

So, this is the global data and any functions can use this data, either they can read as an
input from this global data process. And then after processing they can store the result
into this global data. So, it is the idea about that there is a set of functions. And all
functions can share some data which is stored in a common pool. Now, this is the
concept of function oriented programming that is mean writing the program as a function
for example, C programming language is based on this concept.

(Refer Slide Time: 19:43)

On the other hand, there is another concept is called the object oriented programming
concept; here the program is concept in the form of a set of objects. So, as an example
here we can see these are the one object, these are the one object. So, writing a program
is nothing but writing a set of objects whereas, in terms of functional programming we
have to write a set of functions so, here we have to write a set of objects. And here you
can see one another interesting difference is that, there is no global database as it was
there in function oriented programming. So, there is no global database, then whatever
the data it the programs required all these data will be stored within each objects.

12
So, they are basically data are distributed among the different objects and then is a
localized. So, that is fine. So, data is there and the objects are there, then the
programming task is basically carried out by communicating among the different objects.
So, if we want to solve a problem, then this object will communicate to other objects and
by this communication the program can be solved. So, there is a now obviously, it is
interesting to learn that how this object communication help us to solve our problem.

(Refer Slide Time: 21:13)

So, this is the two concept the function oriented programming and then object oriented
programming. And obviously, there are many I mean good points and bad points of the
both programming, I have listed brief summary about the different facilities that the
functionality programming and then object oriented programming provide us.

So, first of all the program that is organized in function oriented programming by means
of function whereas, in object oriented programming by means of objects, here
importance is given to the function whereas, in object oriented programming importance
is given to the objects. Function oriented programming in fact follow the approach is
called the top down approach, whereas the object oriented programming follows the
bottom of the approach. And there are many other such that the function oriented can do,
whereas the object oriented cannot and vice versa.

13
(Refer Slide Time: 22:13)

So, all these things we will discuss in details, while we will discuss about the
programming and you will be able to learn that time only. And then I will discuss about
what is the peculiarity or the specialty that the Java programming has, it is called the
Java programming modelling or the Java programming paradigms.

(Refer Slide Time: 22:25)

So, there and mainly four Java programming paradigms, these are the paradigms for any
object oriented programming concept actually. So, the four paradigms are encapsulation,

14
inheritance, information hiding, and polymorphism. So, quickly learn about all though
you will learn all these things in details while discuss these topics individually, but today
I just want to give an overview of the four different paradigms one by one.

(Refer Slide Time: 22:50)

So, first of all is the encapsulation, as I already told that the object oriented programming
based on the concept of objects that means we had to develop the objects. So, how the
objects can be developed? So object is basically developed by means of defining classes.

And then defining a class concept in object oriented programming is called


encapsulation. So, here it is called encapsulation because in a class we have to
encapsulate two things, both the data as well as how to manipulate the data, it is just like
a function. Function basically, know how to manipulate data. So, both data and the
function are punch together and then put into a class and this class basically is
responsible for building objects. So, this concept is called encapsulation in Java.

15
(Refer Slide Time: 23:47)

Now, I can give few examples so, that you can understand say book is basically set of
objects; that means, the all books belongs to a particular class. And then the books has
the different data to define it, such as title who is the authors of the book, the accession
number, cost, borrower date of issue like this one. And the different methods that is
required in order to process a book, I like issue whether if it is late return then fine, then
return open a book, close a book, whatever it is there so, these are the methods. Now, all
these methods are there to define a class of what is called the book.

Now, another example say borrower, borrower is also set of objects they are the different
leaders actually. And the a borrower has the different fields or the data actually, they are
called member elements like name, roll number, address, marks and then they can
borrow any books what about the books they borrow it is basically name of those books.
Now other than these data, they are also has some methods like request that mean with
this method they can send a request to book. So, that this book should be suit to him
renew a book, enroll for the library and if you want to exit from the library so, that that
exist methods are there.

So, these are the different methods are there. Now, all these data and methods basically
defined a class here for example, class book and then class borrower. And all these
methods and then member elements the data basically put together and define the classes

16
for example, the classes as an encapsulation, as well as the borrower crosses as an
encapsulation.

(Refer Slide Time: 25:34)

Once the classes are develop; we can create a number of objects. And then they can
communicate it. For example, if a book can send a message that you have already issued
a book which is already not return, within a billing it so, you have to impose fine like this
only. So, this basically objects can send, the message to different objects and then
accordingly the task can we carried out.

(Refer Slide Time: 26:03)

17
For example IP information system will be developed based on this concept. Now, I will
come to the discussion of inheritance in Java. The concept of inheritance is basically if
you have a class how you can derive another class; that means, we can existing class how
one can build many other classes are there.

(Refer Slide Time: 26:22)

So, this concept is basically the concept of inheritance, here for an example a book is
already defined class, but the thing is that book has many categories. For example, a
book can be of textbook type, if it is a textbox when in addition to all the common data
and method that is there in the book, it may have some extra some features. So, those
extra features if we include in addition to the previous features, then it is called the
inheritance. Likewise textbook we can also inherit to another category of book is called
the reference. This means that from the book class which is the base class, we can
develop few more subclass call the derived class.

18
(Refer Slide Time: 27:04)

And so, this way the inheritance is basically help us to build from one class to another
class and the very last software. Now, I will come to the discussion about information
hiding. So, information hiding the concept is that, how we can make some methods or
data that it should not be easily accessible to anybody. So, there are many concept of
information hiding is known and, they are basically hide some data or method from the
public accessible or restricted access.

(Refer Slide Time: 27:36)

19
So, this is the idea and then polymorphism is a very important concept, here the concept
is that with the same name, but it can execute a different operations.

So, this concept is called the polymorphism it look same. So, that it is very simple and
user friendly, but it will do the its acts according to its own what is called the context.
For example, if we use a print one operation. So, definitely printing and image and
printing a document, should not use the same operation rather, it will use the different
way to print different way, different task, different operations to print actually. So, to a
user print method will appear that printing an image or printing a document, but inside
its the different stories should be there.

(Refer Slide Time: 28:27)

So, this is the concept of polymorphism as an another example you can see, if we write
say add x and y. So, add is a method this basically add two numbers, similarly the same
add method also we can define it in a polymorphic way so, that it can concatenate two
string. Likewise add image and document we can use, but the operation will be different,
but if these operation will basically print an image paste an image to a document.

Similarly at the same method in a polymorphic way can be used to merge two documents
together. So, here we can see the add methods has a different polymorphism. The name
is same, but they are argument that is called the input is different and, their function is
different their task is different this concept is called the polymorphism concept.

20
And so, just I am almost in finishing this lectures today, before going to these things, we
will just have an idea about that what the Java programming can do for us.

(Refer Slide Time: 29:33)

In fact, Java programming can do a lot for us, what about the task that Java programming
can support a programmer can be divided into three broad categories. The first the
category is called Java core programming using the Java programming, we can develop
many software’s those are basically very large software maybe system software or may
be an application software.

So, Java Core is basically useful for developing system software as well as application
software and to do these things the multithreading, the interfaces, the input output
handling, Java beans, packages, exception handling all that the key issues are to be plan
for that. So, if you learn all these concept, then we are fit for writing application software
using Java core concept.

Next is Java Applet. As you know different operating systems give you even the mobile
also, they give you lot of what is called the user interface. It is called the graphical user
interface, or interface with speech interface with registers, touch whatever it is there.
Now so, Java applet programming is basically suitable for developing such kind of
interface and here, we use Java multimedia Java script and then windows toolkit and
Java swing.

21
So, these are the basic concept that we have to learn, before use before going to develop
our own system and their user interface in the form of GUI like. Then the third part is the
most advanced part of this Java programming, here basically the Java can be used for
internet programming. So, as a task of internet programming we can do networking,
developing different network protocol for communication. The distributed programming
this is basically the client server model. So, that program can be run distributed across
the different machines, remotely distributed throughout the different geographically
distributed space. And then database connectivity; that means, Java can be used to
connect any database which is stored in a server database.

So, from your program you can pass some comments so that comment will remotely go
to the server which is connected through net. And then you will be able to access the data
in the remote server, or you can load some data into their server. So, it is called the
JDBC Java database connectivity. And then Java JSP also scripting for programming,
this is for developing the browser program different web pages that can be developed
using JSP also we use nowadays Java script.

However, Java script is totally different and needs a different what is called the study and
learning, other than this Java programming. Java script is basically maintained by
Netscape nowadays ok, with this I just want to say few things.

(Refer Slide Time: 32:50)

22
So, right so we have not introduction about the basic concept of Java programming. Then
it is very interesting to learn about how the Java can be used to develop the programs so
that it can runs in any operating system in any architecture any hardware. And then it is
also very interesting to learn how a browser like say internet Explorer the Mozilla the
Chrome all these things can works in our mobile or in our computer. So, all these things
we will be discussed in our next class.

Thank you.

23
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 02
Java Programming Environment

So, in this lecture, we are going to learn about how we can write our own program and
then the same program can be executed in our machine. So, today we will discuss the
different steps of programming in Java in a very simple way. So, if you do not have any
idea, it is not difficult, you will be able to follow it. Now, let us see how we can write our
first Java program.

(Refer Slide Time: 00:45)

Now, before going to write the first Java program I just tell about how we usually write a
program for example, in C. So, if you know C programming then it is good that you will
be able to follow it. So, here is basically the idea it is given here how a C programming
will look like that. So, it has basically (Refer Time: 01:03) preprocessing statement at
right, say include. So, here is basically the include and then it basically the main. So, the
main function as you know the C programming is basically functionoriented
programming.

So, there should be one function called the main function. So, this program is written in
the C programming and you can see that this program will basically if you run it then it

24
will print a message called “Hello, World!”. Now, let us see how the same right task can
be executed by writing a Java program. Now, a Java program will typically look like
this. Now, you can see the difference between the two programs: one program is in C
and another is in Java.

So, it is ‘include’ in C, but here it is ‘import’ in Java. And here you write the main, here
also we write the main like this, but with a peculiar that if syntax. The peculiar syntax is
like this public static void which is not required there only int or some void can be there
in C. So, here is the special thing we learn about the meaning of these things which are
required in Java. The print statement is there in C to print a message. Here in Java to do
the same thing we need this kind of syntax – System.out.println(“ ”) and then within this
double quote the message that needs to be printed.

So, essentially the two programs will do the same thing, but they are written in a
different syntax and different language construct. So, this is the idea about that and this is
your first program and one more thing that I should mention here is that Java as it is
objectoriented programming. So, we have to develop an object. An object is basically
developed by means of defining a class. So, here this is the name of the class that
basically we will be used to run; I mean, run this program as an object. So, the name of
the class here is called HelloWorldApp this is the name you can give a 1, a 2 like this
one also. But there are few things that you have to follow it before giving the particular
name and whatever it.

Now, we have to learn about how we can run a program in Java to print a message and
this is a typical look of this program, you may find it a little bit difficult. So, that what
are the different syntax and everything, but as the time pass and then you will discuss
many things. So, all these things will be easy for you and then you will be able to
accustom to this concept. So, you should not be worried about that. Now, after running
this and another important thing is that as a case sensitive, both the programming
language as you know or if you know already C programming then you know that C is a
case sensitive and Java is also a case sensitive. Case sensitive means for example, where
the System is filled it like this. So, the first character is capital S and it matters.

So, if you write this program which system as small letters all characters in small capital,
small letters then it is not the same thing as it should be. And here, for example, the name

25
of the class is HelloWorld and you see the some is capital letters some is small letters
this means that they are distinguishable. So, if you write all in small letters this means
that it defines a new class and like this. So, these are basically the case sensitive and Java
is a case sensitive programming language. Then while you typing the program then you
should consider whether they have the right letters have been chosen or not.

(Refer Slide Time: 05:31)

Now, here again, there are few more differences about the C programming versus Java
programming and regarding the paradigms that we use, by this paradigm, the two
program languages are totally different. And, also C programming is not the platform
independent whereas, Java programming is the platform independent. And few things
you can note it from this table that many things which support C programming but does
not support Java programming. This may be a little bit surprising, but is not the surprise
actually Java developer wants to make the programming as simple as possible, as easy
for the programmer is it possible.

So, that is why the many critical and then complex issues which basically leads to a lot
of errors have been carefully ignored in Java programming setting. So, that is why there
are many things which are not supported by Java programmer and in addition to this
there are few things also which is not possible in functionoriented programming like C,
but it is possible in Java programming. For example, inheritance a concept we have
discussed in the last lectures. It is basically not possible in C whereas, it is possible in

26
Java. A pointer is one great deal of errors and then is learning capabilities actually so, it
usually very difficult to cope with this concept.

So, Java developer has ignored this there that means there is no business of pointer in
Java programming; few things are very much essential. So far the distributed
programming and then internet applications they are called multithreading and interfaces
those things are there. And, to make the robust and most reliable programming the Java
introduced the concept which is new of its kind. In fact, is called the exception handling
which is not there in C programming language, but it is readily available in Java
programming. And, database connectivity usually C does not support database
connectivity, but with Java, we will be able to connect the database. All these are the
basically facility over the C programming and that is we can enjoy from the Java
programming environment.

(Refer Slide Time: 07:42)

Now, so we have discussed the first program that we can write in java programming, we
have an idea about it. Now, let us see how we can type this program, what setting should
we have to do that. Now, you can use any editor, there is a text editor like say Notepad or
MSWord or Edit command in Unix whatever it is there. In Unix there is some other
command editor also there like vi, emacs and gedit. So, you can use any editor and then
type any text like your java program that we have discussed in a few slides back
HelloWorldApp you can write it.

27
(Refer Slide Time: 08:29)

So, writing the program using editor is not a big thing to discuss and once you write this
program you have to save this program. So, you should save this program in a particular
directory and that can be used using any command in Unix or any prompt common
prompt from the windows. So, that you can make a directory and all the program that
you have developed using editor can be safe there.

(Refer Slide Time: 08:51)

And while you save this program then particular care, ok, I mean task should be taken
into consideration is that naming of the program.

28
(Refer Slide Time: 09:06)

The name of the program should be the same as the name of the class that you have
defined. For example: in the ongoing example the name of the class that we have given
HelloWorldApp. So, the name of the program; that means, this program should be saved
as a HelloWorldApp and one more important thing that you should know is that
extension. For example, in case of C program the extension should be ‘.c’ whereas, in
case of java the extension of the program should be . java; that means, the program in
java should be saved as ‘.java’ file.

(Refer Slide Time: 09:44)

29
So, and then the directory that you can see; here after saving you will be able to see this
kind of program has been safe in your current working directory.

(Refer Slide Time: 09:54)

So, once so this is basically the task of editing; that means how you can type your
program using an editor like gedit editor or Notepad or MSWord. Now, I will come to
the discussion of how you can compile this program that means translate this program.
As you know the java file is basically is a highlevel program that means a program
written in a highlevel language. So, this program in order to execute it should be
translated into a machine level code binary code form.

Now, I will discuss how this can be I mean compiled or translated. Now, for this
translation there is a program provided by the Java developer and the name of the
program or you can say the command is called java c javac it is called the javac; it is a
basically short form of java compiler. So, you can use javac as a command and then type
this javac followed by the name of the java file. For example, javac HelloWorldApp .
java. So, if you run this and if there is no error in your program then java will compile
this program successfully.

30
(Refer Slide Time: 11:12)

So, this is a command that you can use from your command prompt, Windows or from
your Unix terminal the program. And, once the program is successfully compiled this .
java file will be converted into one file having the same name as the name of the java file
earlier, but the extension is different. The name of the file with executable code is called
. class. So that means, HelloWorldApp . java will be translated into a code a file is
called HelloWorldApp . class.

(Refer Slide Time: 11:58)

31
So, this is basically the task that the compilation we will do for you and then running that
mean execution. So, the class file that you have already created you can execute the same
file from the same directory if you type the command from the directory. So, the class
file which belongs to the directory say you are working directory and then from the
directory, if you run this command, like the then it will run the program.

And, here you see while you run this program you do not have to specify them . class,
just simply name of the file without any extension it will run your program. And, if there
is no error during runtime also sometimes an error is there then this program will
produce the output on the screen or it will be store the output. So, we learn about how to
edit a program, then how to compile it and how to execute the program ok.

(Refer Slide Time: 12:58)

So, the concept is pretty simple and it needs few I mean practice to cope with this.

32
(Refer Slide Time: 13:02)

So, in our one demonstration, we will give you enough program so, that you can practice
on your own. Now, before going to our next discussion I just want to highlights a few
things about. I several times told about that programming is a platform independent
whereas, C programming is not; what it does mean actually. So, here the meaning can be
understood here. For example, this is the program that you have written using any editor
Notepad like and then the name of the program is HelloWorld java. And, this program is
translated by a compiler called javac this one.

Then platform independent it does means that the same file that you have developed
should be executed in one machine we say Windows 32, in another machine we say
Windows 64 or in another machine say Solaris or is a MacOS or like that. So that means,
the program which is compiled successfully should be executable in any operating
system whether it is Windows or it is Unix or it is MacOS, then it is called the platform
independents. So, that concept is basically possible here. This means that the file that we
built by compiling that means . class file is basically one sort of thing which any
machine can understand it ok.

If it is not platform independent this means that compiler will compile one code which
basically only one particular machine can understand it. So, C compiler is basically the
different C compilers are there or the translating the program into the different machines
that is why it is totally platform related. That means the same machine which basically

33
compiles for this machine cannot be executable into another machine. Maybe high-level
language program same, but the ultimate executable thing is basically different.

So, that is why the C programming cannot provide us the platform-independent concept,
but here is basically because of the concept of . class. Now, here again, question is that
what is the special thing in the . class.

(Refer Slide Time: 15:32)

So, that that idea is basically the concept of . class is basically one code which basically
any machine can understand; that means, this executable code is basically developed
targeting a virtual machine. Now, regarding this concept, we will discuss in details
whenever you will discuss the platform independent issue in a more detail manner. Now,
is a programming language and mainly it is an object-oriented programming language.
Like there is another object-oriented programming language before came into the market
that time another programming is also very popular; it is called the C++.

The programming is basically is an extension of C, C is a function-oriented whereas, C+


+ is object-oriented, but the two programming language all through object-oriented
programming has radically many different features are there. So, let us quickly see what
are the difference between the two programming environment C or C++ and Java. Now
first of all so far the program building and software development is a concern they follow
the complete different task; the task that that is followed in C, C++ is shown here. So,
here if you write a program that is you call the program file, source file it is and the

34
source file has certain preprocessing; that means, it will link and if it is any library and
everything.

So, they first undergo through preprocessing and then finally, pre proposed things will be
compiled. And, then after the compilation, it produces the assembly code. Assembly
code is basically the program in numeric at, sharp like this one. Then the assembler will
be there which will basically translate the assembly code into the assembler ok, using
assembler into the machine level. And here these assembler is basically different
assemblers are there in the different what is called the architectures. Similarly, the
different compiler because of the different machine, different architecture, different
operating system follow the different assembly code.

And then different hardware, the microprocessor follow the different machine level code
from the same assembly language programming actually. So, the assembler will convert
a high-level program written in .c or . cpp for C++ and then finally, produce an object
file. And, sometimes these object file may take some help of some libraries or build in
the program. So, this is a built-in program that needs to be linked and finally, the
executable file will be created. So, this is the way the conventional C or C++
programming work for us; that means, from writing from program to executing a
program. Now, let us see the same thing how it works in the system, environment; it is in
fact pretty simple.

It is not so complex task rather it basically these are java file program written in java .
java file and then there is a compiler. This compiler is the same compiler, what about the
machine you use (Refer Time: 18:57) not an issue. This compiler will translate into .
class file, . class file in technology it is called the program not in binary form or not in
machine level code rather it is in the form of code it is called the byte code. It looks like
1 0 0 0 1 1 like this one machine level code, but its formats its syntax is totally different.

So, this is the byte code, byte code is now we can say is executive code; then in order to
run these byte codes we need one interpreter. So, basically, this is one it is called the
interpreter, an interpreter and interpreter as you know interpreter basically take one code,
run it then go to the next run it like this one. So, it is an interpretative mode, it is not that
the way compiler and then the executive code finally, is produced for this machine and
then it will execute. Now, here you can think that here in C or C++ everything is

35
basically the compilation whereas, in the case of two things are there both interpretations
as well as a compilation are there.

So, it halfway compiles the program into byte code and then the next halfway it basically
execute the byte code into the corresponding machine. So, here the idea about that this
bytecode that will be produced is targeting a hypothetical machine irrespective of the
architecture it is there. And, the interpreter for every architecture there is a corresponding
interpreter. So, these interpreters know that if this is a byte code then how to work with
this and then that way the machine independence is maintained here in case of the
environment.

So, this is the idea about the execution of the two different programming concepts, for
example, C C++ and apart from this thing there are few more differences are there. So,
far the two programming languages both are object-oriented programming languages C+
+ and Java, I will quickly summarize the different concept it is here.

(Refer Slide Time: 21:28)

So, C++ and both are object-oriented programming, but they are a target are not (Refer
Time: 21:38) same. For example, C++ usually preferable for developing very large
software such as library management system, employee management system, then a
passenger railway reservation system like this. Whereas this can be used to develop all
these kind of systems of course, but in addition to this is a very special programming

36
language which is suitable for developing particularly communication or internet
application related software development.

For example, if you want to develop networking technology, to develop many protocols
in networking then you should use instead of C++. For internet programming; that
means, how the browser work, how the remote desktop can work; all these things are
best suitable. You if you want to develop the web page, the web page is a very common
things nowadays many organization they maintain their web pages including any
information and then many services.

So, web services, for example, the bank, and everything. So, the webpage you can
develop and then web browser also; that means, it will browse any webpage if it is
available on the internet or www. So, these are the programming that you can do using
programming better and in C++ sometimes they are not possible or infeasible.

(Refer Slide Time: 23:19)

So, these are the difference in the task that the two programming languages are there.
Now, I will just feature wise I will tell about how the two programming languages are
different. Now, here I have mention a few important things which are possible in C++
and which are not possible in and vice versa. Now so, for the encapsulation is concerned
we have discussed that is an object-oriented programming and encapsulation is a
programming feature. So, both C++ and provides the encapsulation and that means, they
allow us to develop our class file. Polymorphism if you see both C++ and provides a

37
polymorphism and binding; that means, how the different a data can be bind to the
different functions or methods.

There is a concept called the binding and there are two types of binding; the static and
dynamic both kind of binding is possible in as well as in C++. And, then inheritance here
is a bit different in C++ and Java. C++ supports are both single as well as multiple,
multiple is a very complex inheritance mechanism. On the other hand, does not support
multiple inheritances, supports only single inheritance. And, then operator overloading
this is another important things; that means, that different operator, for example, the
plus-plus can be used for adding two numbers, plus can be used for adding two
documents like this; this is a polymer print concept actually.

So, operator overloading is a concept of polymorphism. C++ allows operator


overloading whereas, Java does not allow operator overloading. And, then template
classes these basically C++ allow template class; that means, one template means is basic
class can be developed which basically not suitable for creating an object, but it is a
template only. But Java does not give any facilities to create a template class. There are
few more things like a pointer. Pointer is not possible in Java whereas, a pointer is
possible in C++. And, interface and packages Java is a very good one features regarding
this whereas, in C++ does not have.

Now, here we can see many things; many things for example, here in C++ whereas, Java
they do not have and few things, of course, Java has where the C++ does not have. Now
here obviously, I told you that what is the reason behind this. The reason is that Java we
want to develop a user-friendly one programming environment. In order to make a user
programming user-friendly environment the Java developer (Refer Time: 26:22) down
many complicated features which basically associated with a lot of errors; a lot of errors
in the program list to the program which is not a robust program or reliable program. So,
eliminating some features which are very complex and erroneous so, we can make a
reliable and robust Java programming; that is the beauty of the Java programming and
that that is why Java become a great programming language is here.

38
(Refer Slide Time: 26:50)

And another difference this is obviously there another see difference is there C++ again
is an object-oriented programming, but it is not platform independent. That means
different compiler is required to translate the C++ code into the different programming
languages whereas, Java is a platform independent programming language this means
that that. So, Java code will create a byte code and then byte code will be interpreted in a
different programming environment. And this way the platform independent; that means,
the same code can be executed wherever you want to run it.

But here the different compiler is required to run your same program in the different
programming environment. So, this is the idea about the two programming languages C+
+ and Java and the basic difference between them ok. So, we have learned in this lecture
the idea about the programming the different steps of programming in Java and how Java
programming is different from the C++ or C programming or other functional
programming concept.

39
(Refer Slide Time: 28:05)

Now, so far we have discussed a very simple program which includes only one class. In
our example, we have considered one class namely HelloWorldApp.java, but is it
possible that a program can consist of more than one classes. And, if it consists more
than one classes whether the same techniques for compiling and executing is there or not
or we have to follow the different concepts. And, also how a browser can execute a Java
program; those are the interesting things in Java. So, all these things we will cover in our
next lecture.

Thank you very much.

40
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 03
Java Tools and Resources

So, we have learned about a very basic things about the Java in the last two lectures.
Now, we will see exactly what are the tools and resources that you should have in your
own custody so that you can develop your own program brand your own program, test
your own program and all these things. So, today’s lecture includes what are the Tools
and Resources that you can think. So, that you can use in and then you can prepare your
programming environment.

(Refer Slide Time: 00:53)

So, Java programming tools first I would like to discuss about it. Now, one very
interesting thing about is that everything is free; that means, Java tools those are freely
available, you can download it from the net and then you can use it.

So, what the thing it is required is that you should have your own machine a laptop,
whether it is windows it is Macintosh or it is Solaris absolutely it is not an issue you just
have it. And then you can download the program from the different links. So, I will tell
you the different links that is available, and then we can use it. So, basically the JDK;
once I told you the JDK is called the Java development kit. This is the basic building

41
what is called the blocks, or basic building tools basically we can load it. And once you
load it you can install it.

So, JDK can be load directly from the Java source, JavaSoft you just simply in the
Google give you the index JDK. And then you can find lot of links and there are free
links all that means they are freely downloadable. And so, far the JDK is concerned there
are many versions one is called the SDK version and JDK version.

I should not suggest you to download the SDK, SDK is for the advanced programmer it
is called the super development kit, who there are many features unnecessarily make
your system slow so, better not to use it. And so, far the JDK is concerned which was
introduced in 1996 first time, after that lot of versions are available till time. The latest
version that you can have 11, but for beginners the basic programmers right you should
use the JDK version 8, JDK version eight is most versatile most matured and then it is
easy to use. So, I should suggest you to download the JDK version 8 in your machine
and then install the same in your machine.

(Refer Slide Time: 02:54)

So, this will completes the Java software for your working that is all. Now, next let us
see what the things there in your JDK tool. JDK is a basically a bundle; that means, it
contains many programs. Now, here I have listed the programs those are there in JDK, I
can say the JDK or SDK there are both are the things are same so, there in fact seven
programs.

42
I have already discussed about one program; that means, to how to translate a dot Java
file into dot class file it is called the javac. So, javac is there it is basically Java compiler,
then Java one another command we have used to run the program it is called the Java
interpreter. So, these are the two programs very used frequently used in that is there in
bundle in JDK. Other than this for some large program software development where we
have to have a documentation; that means, different documentation for large software is
required and there is a tools available for that is called the Javadoc using Javadoc you
can do very quiet and comfortable documentation in your own program so that the
program written by you can understand by any other programmer, who wants to extend
your program all these things. So, in a team work if you want to do develop a program
Java doc definitely suitable and you should know it.

Then appletviewer is very another program and appletviewer is basically to run the Java
applet. Regarding Java applet we will discuss about it is just like a browser program. So,
it basically run html file actually which contains some Java code in it. So, appletviewer is
to basically running Java applet a special kind of Java program, which is basically
suitable for window programming, or is a graphical user interface program development.

Then the Java debugger. So, if you have very large set of classes in your program,
sometimes it is not giving the desired output. Then you may have to debug; that means,
find the error where it is there. So, for this debugging the JDK provides you a very
efficient and then handy tool set it is called the JDK this is for the Java develop Java
debugger for fixing errors in the program. And then Java disassembler it is called the
javap that is basically dissembling, if you want to make the program if it is very complex
and large program into several components. So, javap will basically allow you to
dissembling your program into small program sets and then it is also a tool that you can
use it and then do it.

And then javah is the one another facilities included in a JDK. And it basically help us to
create an interface between Java and other programming particularly C routine or C++
routine, here basically javah is used suppose some part of the program you want to
develop in C. And then another program part you want to develop in Java. And then both
the things are needs to be interfaced together. So, that they can work together so, in that
case you can use javah is a facilities that is bundle there in JDK.

43
(Refer Slide Time: 06:24)

There are few more resources that you should consult while you learn this [FL]
programming and, also attend this course and one is a very important link it is called the
very popularly it is called the javatpoint is a tutorial point. So, it has very large set of
examples and than illustrations and, then only the missing is that they do not discuss
about the theory or any concept.

They have just simply programs a sea of programs we can say, that you can download
from this run in your environment and by the way you can learn a lot of course, but
without knowing theory and then principle and concept learning on the program is not
suitable. So, this is not so suitable for the beginners of course, but you can at least have
some hands on of some programming from this source. So, it is a javatpoint and Java
another few I mean documentation that you can download from the sum Java website
itself.

So, there are many documents very vast document of course, sometimes if you are to
learn this program in a small means say maybe in 3 months or 2 months, then learning all
those things is really not suitable. And this documentation is of course, good and is
preferable for the advanced programmer.

So, if you are not an advanced programmer, then all this program should not be utilized
at the moment. Later on whenever you learn some basic things, then you can use it then
as a run as a more advanced step.

44
(Refer Slide Time: 08:06)

And there are few more resources that is also available which you can consult, that is
again from the sun Java website itself this is a very authenticated document actually
there is no error in the documentation. So, is a error free documentation and then very
professionally maintain the documentation, this is from the Java dot sun dot com is from
the sun original websites. And there is another sun developer network is also available
for many other resources.

This is also from the sun Microsystems official website, where the documentation
regarding many packages. Actually Java also the JDK includes many other packages,
those packages are called API. Now regarding this packages this package is basically a
library. So, if you want to know about this libraries and what are the classes are there in
the libraries and what are the functions methods or operation that all classes we will do
for you, then the API documentation. Those API documentation also you can have it
from Java dot sun dot com website. So, these are the very two important links that you
can have it.

45
(Refer Slide Time: 09:18)

Now, I was talking about in API and is a full form is application programming interface.
Now, Java is great because of this the APIs, the Java API is basically is a very big one
voluminous resources. And in fact, there are I mean nine packages and each packages
consist of huge number of classes and their definitions and then their use.

So, all this classes you can use in your program; that means, is basically programmers
supports. So, there are nine packages are there and then all packages are basically
categorized to sub different task. Now for example, there is one packet package called
applet. So, this package usually called java.applet. So, this package is basically suitable
for writing applet in writing applet manual programming in applets.

So, applets as I already told you applet is for designing graphical user interface,
graphical user interface means button then checkbox call window, then text field area all
these things. So, this is basically the applet packages will help you to create the graphical
user interface very easily, without knowing details about how they are doing it is just like
a magic if you run know that ok. This is the one class that you should use to create your
own button and then use it and then run it like this one.

Now, so Java applet is the one right is for applet programming and regarding applet
programming applet programming is a very past concept of course, and we will learn
shortly. And then there is another package the name of the package is called Java dot

46
AWT it is called the Java abstract windowing toolkit. So, abstract windowing toolkit is
basically another extension or is a basically support to develop GUI programs.

Then another package regarding input output handling, you can recall the different way
the input can be considered, input from the mouse, input from the microphone, input
from the document, input from the handwritten, gesture whatever it is there so, input
from an image input from network so, how to deal with so, many versions of input. So,
there is a package .io package java.io which basically help you to take the input from
many sources and then use in your program process it and then produce output according
to the requirement.

So, java.io is basically suitable. java.lang is a another package which is basically


frequently used package; that means, one program which always required one package
that is a java.lang package, you cannot write any program without java.lang package. As
this package is very important and essential and in all program it is required. So, it is not
required to be explicitly imported that mean it will automatically included in your
program, even if you do not input. However, other packages if you want to use it, then
before using they should be imported in your program.

I will tell you how to import a package in your program or a particular class which
belongs to a particular package in your program. So, that the concept; that means, a
particular facility is that that can be imported in your program whereas, java.lang is a
default package that can be imported automatically, and it basically give you the basic
programming facilities that you can have if you have this java.lang package.

47
(Refer Slide Time: 13:13)

So, out of nine packages we have discussed 5 there are; few more important packages are
there few more packages like Java dot net, net is basically the package suitable for
network programming. Networking is a very important one features in Java
programming. So, we can have the Java dot net package to develop our network protocol
network programming, socket programming like this and java.util; util it is basically one
advanced one programming which basically gives you many what is called the built in
data structure.

As you know data structure is a very important concept for programming; that means,
you have to store the data in an efficient way, how you can store the data in an efficient
way data structure tells about it. The many data structure like stack ,queue, linked list
and vector all these things are readily defined in the package java.util one important
dictionary data structure is called dictionary; that means, you can maintain a dictionary
for any language to any language or dictionary for medical vocabulary or whatever it is
there.

So, the dictionary data structure is already there, data structure means how to define the
structure and then what are the operation already defined in that package. So, you just
know about, that what are the facilities available and then you can plug in your program
and then use it.

48
Then the one advanced packages those are there in Java latter on it is included, early in
earlier version it was not Java version 5 onwards this package is used it is called the
swing, swing just like AWT. But it is more interesting and more lovely things there in
Java programming, Java swing basically another extension of AWT abstract windowing
toolkit for supporting GUI development.

And for Java database connectivity there is one package it is called the java.SQL. So,
this using this package, you will be able to connect to a remote server database from your
application. So, these are the different packages, which are available in Java
environment. And if you once install JDK with all programs that we have already
discussed like javac, javap, and javaap, javah all these things in addition to this all this
API also will be install automatically.

(Refer Slide Time: 15:47)

So, in JDK is basically contains everything. Now, we told about the free software that is
available all this softwares are free; however, as the Java is very popular and then many
software developer many software engineering firm, they develop the program in a large
scale, large scale to support the program many and sophisticated programming
environment is all already available in the market. However, it is not free costly. There
are few software development environment it is called IDE the full form is integrated
development environment.

49
So, there are lot of IDEs are available for example, from sun microsystem itself one IDE
is available, but it is not free of cost is for the commercial purpose only called the Sun’s
Java workshop. It is very good one environment which can help you to develop your
program very easily and in a user friendly manner. Mojo is the one good I mean comma
popular one software development environment, it is from the penumbra software is a
company basically suitable for creating Java applets.

Similarly, Jumba is from Aimtech and IBM it is also one environment suitable for Java
applet programming. And the best I ever seen is called a semantic cafe, it is a very well
known very popular and very sophisticated one programming environment it is called the
semantic cafe. So, if you can afford you can purchase a semantic cafe right and then
install in your machine, this software include everything your JDK the API the other
programs and what is not. So, it will help you a lot debugging, testing, maintaining
everything put together is a very nice programming and environment semantic cafe, but
it is not free commercially the cost is too much actually individually level it is very
difficult to afford.

(Refer Slide Time: 17:59)

So, these are the tools I should say the third party tools for Java programming
environment. And there are few tools also available for browsing the software; that
means, as you know the Java is suitable for internet programming and internet

50
programming means lot of webpage programming ja JSP Java script or Java browser
related programming.

So, there are lot of browsers are also required, earlier when Java was introduced initially
all browsers like internet explorer, then all these things are supporting. Now-a-days all
this browsers stop supporting Java browsing, there are some security issue that is why.
So, all browsers cannot support your Java program to browse it directly actually, but the
other way it can browsed and it can be executed. There are many security reason that is
why the different browser has stopped running the Java program remotely actually.

And initially hot Java actually was introduced as a very beginning when the Java was
introduced for the browsing purpose only, but the hot Java is also still available and you
can use it, but hot Java is not so popular like Mozilla, Safari or Internet Explorer is
popular Netscape Navigator also available as a browser it is windows NT environment or
some other Unix environment net score navigator is available. This also supports Java in
a full phase.

So, these are the browsers that you can think about it, but while you learn Java
programming you usually use applet viewer as a Java browsing. So, for learning and
practicing the applet viewer is fine, but whenever you have to deploy the program, the
shape and different technology different concept needs to be followed. That will be
discussed later on, but here till time we will not discuss about any other browser
whenever we have to run Java applets or Java program we will follow applet viewer as a
applet browser.

51
(Refer Slide Time: 19:57)

There are few more important resources available I am not sure whether it is available in
a free version or not. There are obviously, a free is software available not in the full
functionality for enable net bean. Net bean is very famous for building very large
software it is just an IDE integrated developing environment.

It is free if it is available; obviously, not all features cannot be available, but it is at least
some essential features you can have it so, it is an IDE. So, at least some IDE freely if it
is available, then it is net bean you can install and then run your Java program using this
net beans. And one editor I should mention it which is very good one editor and very
sophisticated and versatile editor it is called the Notepad++.

Because you have to run the program, you have to save the program and those for typing
the program all those things should be as fast as possible. So, that efficiently you can do
it. So, Notepad++ is highly recommendable. So, that you can download it Notepad+
+again is a free software. So, you can download freely and install in your machine and
then use as a default editor. You can make the editor as a default this one. Now so, we
have learn about the Java language Java tools and Java resources that you should hold,
before you just warm up yourself into the Java programming environment and become a
Java programmer.

52
(Refer Slide Time: 21:31)

Now, I am I just want to mention about few things, which is basically in Java commonly
occur. So, sometimes you have to face all this thing again and again. So, these are called
the subset of the language subset. In fact, a rich subset of the language, it is not possible
to cover in one slide or in 5 minutes discussion it require in fact, the full discussion and
we will learn all this subsets of the Java language one by one.

So, there are many built in data types, like Boolean, integer floating all these things,
there are many system functions like println printf and all this thing. For example, in our
program we have face that System.out.println() this kind of things are there. So, many
frequent and then common things are there. So, this slides includes the many common
things those are there in your Java programming Java programming, or while you writing
Java program you have to use it. Obviously, for the first time programmer all those
things little bit looks like very difficult to understand, but once you are practiced it and
then involved it. So, you will be slowly habituated all this term.

So, these are the subsets and I just want to skip this subset discussion, because it will be
learned slowly, but consistently we will learn it, ok.

53
(Refer Slide Time: 21:50)

So, these are the basically standard data types, if you know C programming then you
definitely know that what is a data types like, they are called the built in data type or
primitive data type like Boolean. Boolean is a data type by which we can declare one
variable, which record only 1 bit to store. And then byte: byte is a new data type which is
there in Java in C++ also it is there, and there char is also there in C programming in
Java and short is there. In addition to this there are few more data types like int, long,
float, double if you know C programming then you can see that. These are the few data
type which is there in Java also there in C.

And actually if you know C programming then learning C++ programming is very
easier. And if you know C++ programming, then learning Java program is also very
easier. Anyway, but if you do not know C++ programming absolutely it is not an issue,
but there are many things are very common. So, for the syntax the commands and all
these things, those are there in C programming also there in Java programming. So, it is
an added advantage for the C programmer to cope with the Java programming
environment.

Now so, far the data type is concerned all these data type that we have discussed call the
built in data type, or simply they are called primitive. Because those are the data type
already developed by the compiler, compiler can understand automatically you do not
have to bother about anything about all this data type. Other than built in data type that is

54
more interesting to learn and you should learn it more skillfully so, that you have you are
an expert in Java programming is called a reference data type.

Reference data type basically define your own data type our own type of data. As I told
you object is also one type of data. So, the reference type it is called, or is called the
abstract data type, or customer defined data type.

(Refer Slide Time: 24:47)

So, regarding reference data type we will discuss in details in this course we learn about
what are the reference data types are there, and how it can be developed, how it can be
used how it can be manipulated modified everything right now. So, far the Java character
sheet; that means, if you want to write a program, which character you should use which
character you should not use.

Now, if you see the keyboard the qwerty keyboard that is there, lot of characters are
there, but all keys you should not press to type your program. There are definite sets
uppercase letters A to Z they are permissible the lowercase letter any a to z you can use
in your program writing, any digits 0 to 9 you can use and in addition to this A to Z and
the numbers, you can use some special character sets which is listed there in this table.
So, these are the characters that you can use, other than this characters. If you use any
other characters, then your compilation will be erroneous that there will be a error while
the program is complied.

55
(Refer Slide Time: 25:47)

Now, I can define; that means, naming of variables or class or methods, it should follow
certain rule. The same rule that is followed in C program also C language, also
applicable in java. That means, the name should be given to a programmer a program
elements like variable, constant, class methods etcetera. The names may consist letters
digits and underscore with no space in between.

That is very important and then blank and comma are not allowed, while you are naming
a variable, or identifier or any type. The first character must be an alphabet or
underscore. If you start a variable name or class with say number it sometimes gives an
error, I mean it easily give an error in some compiler definitely advanced features it may
not give, but it is usually not advisable to follow, then and I write an and name of the
variable can be of any length there is no limit.

But again, unnecessary giving very large name to a variable or type is not a good. So,
you should give very short name, but meaningful name. And I and one more thing that
you should take into account is that the Java programming language is case sensitive.
This means that if you declare a variable name as small x and then same variable other
variable name as capital X, they are basically two different variable name.

56
(Refer Slide Time: 27:24)

So, the case sensitive means the capital letter and small letter matters a lot and here is a
free example right. The how you can declare the different type of variable for example,
int a b we declare the two variable name as a and b. And, then b is initialized 0 like this 1
and then the system brought print is a system one statement by which we can print one
message.

And whatever you want to print you should enclose in a sin double quote, if you type
anything double quote it will print (Refer Time: 27:54) bottom on the screen. Then if you
want to print anything else, then you have to write plus, then what are the other things.
So, if you to the sum is the value of C then the syntax is like this one. So, all this things
we will discuss whenever we will discuss the program it is there.

57
(Refer Slide Time: 18:15)

Now, I will quickly come to the discussion about array is a one very important structure
in java. And array is basically instead of only one variable value or elements, we have to
store a number of elements into a location or chunk or memory, then it is called the array
is a basically finite set of is a collection of finite set of elements of same type; that
means, integer or integer, character or character, float or float.

Now, we will quickly discuss about how an array can be declared in Java. And then once
you declare an array. Then it is also your responsibility to allocate the memory for the
array. So, how you can allocate the memory for an array and then how you can load the
values into the array.

58
(Refer Slide Time: 28:55)

So, those are the things that you can quickly learn about it. So, if you to declare an array
say x, then the syntax it is there int x within square brackets. And then termination
symbol is semicolon that you have to meet it. So, that is also alternative int square
bracket x also the same way people can use it; that means, x is an array of integers.

Then one you declare an integer array, then you have to allocate the memory, for the
allocation there is a operator it is called the new operator is called the memory allocator
operator. So, you have to use the new and the syntax is like. So, if you new and then
type; that means, what type of data you want to store and then this is the size and then
this basically is the location where it is stored.

Basically the x is an array, this basically allocate the memory for storing 100 integers
right. So, this is a way that the integer can be stored into an array of size 100.

59
(Refer Slide Time: 30:07)

So, this is the way and then one shortcut also in one go you can define it like this,

int x []=new int this; that means, the memory allocation as well as defining an array can
be done in one go. So, this is a shortcut syntax for this. So, this is a syntax that you
should use to declare an array of any size whatever you want.

(Refer Slide Time: 30:26)

So, this way you can create an array. And once you can create an array that array can be
used using for loop while loop like this one.

60
(Refer Slide Time: 30:34)

And here is also alternative way array can be declared memory can be allocated and then
value can be stored at the same time.

So, this is a simple syntax that you can follow for example, here an array of x will be
declared which will store; that means, size of the array is four integers. And then the
element that will be stored, there is 12, 13, 9 and 15 out of which 12 is a first element
and one more thing that I you should note that just like in see the array index start from
0. So, that mean first array location is 0 x 0 and then x 1 x 2 and x 3. So, total index is
from 0 to 3 in this case that means four elements.

61
(Refer Slide Time: 31:18)

And array can be used for many purpose, we have to maintain a large pool of data. And
then, that data can be used either for in searching some other element deleting some
elements sorting searching.

(Refer Slide Time: 31:30)

And then traversal and others there so array in Java can be done the way I have already
told you here, here is a simple few steps further.

62
(Refer Slide Time: 31:44)

So, that you can follow it, and then I will discuss about that array that we have discussed
is one dimensional array Java can help you to have any dimensional array. Here I am
going to discuss about how the two dimensional array can be declared in Java. For
example, say name of the array is same myArray this are your array that you want to
develop you want to maintain and this is a two dimensional.

So, for the two dimensional you have to use the two square bracket. So, this completes
declaring an array of 2 D and then this basically allocate the memory. So, myArray new
int here two dimensional and then for each dimension what is the size, for the first
dimension 3 and then this is the 4. So, this means that it will declare an array of 3 row 3
rows and 4 column so, 3 cross 4 the name of the array is myArray.

Alternatively this is also the one way syntax that can be used to declare, define and then
allocate the memory at one point.

63
(Refer Slide Time: 32:59)

So, this is the way that two dimensional array can be declared likewise 2 D array the 3 D
array also can be used. Now, again 2 D array initialization can be done by using for loop.
The way first you have to two loops here you have to use it.

Otherwise if it is a small array, then you can use this kind of syntax for the singular one
dimensional array, we have used it in the same way. If you do it like this you will see the
Java; Java system will automatically store this in the first row and then this in the second
row like this one, if the array is like this. Otherwise you can just make it more structure
within brackets, within brackets like 1, 2, 3 this 4, 5, 6 this one.

If 1 2 3 and is a blank then that element will be null and other element will be stored this
way. So, this is more compact one way, that the array can be initialize 2 D, but this is
only meaning for small arrays, but not good for the large arrays, large array we have to
use the loop structure to initialize the elements.

64
(Refer Slide Time: 34:00)

And then the 2 D array with variable size also we can declare here for example, in this
row only 2 column in this row 3 4 column in this row 3 column. So, that is a variable
sized array also can declared and here is a quick syntax for variable sized array
declaration here, basically the concept it is there. So, we can declare the 2 D array like
this.

The declaration here row size is declared because the number of rows is defined here, but
column size is not declared here, that that can be decided here using this one. So, for
each row once it is declared using this one and then for each column can declare by
rolling 1 for i is equal to 0 to i less than row size for each row. We have to run this and
then these are basically name of the array, then this is the size that you want to do for
example, here 2 3 4 you can mention it and then column size. So, this way you can build
the array of any variable sized.

65
(Refer Slide Time: 35:09)

Now, likewise the 3 D array also possible to maintain in Java also 3 D array is bit
complex, we have a demonstration about 3 D array so, that we can understand here. So, a
3 D array typically just look like. So, if it is a 2 D array so, is a collection of 2 D array is
basically 3 D array; that means, for each this page we can say and there is a collection of
page.

So, each elements in one page can be accessed by the number of rows and column. So, i j
and then each page will be denoted by k. So, is k is basically this is k equals to 0 k equals
to 1 and this is equals to k equals to n if the n number of pages are there. And similarly
for each page using just two dimensional concept you can access this one.

So, here is an example, this example you can follow it slowly with your own space, you
can understand that this example basically how a 3 D array can be declared and its
memory can be allocated. And finally, the different elements in it can be loaded. So, this
the whole program you can check it slowly with your own time. And then you can also
try to run it then you can understand how it’s there.

And here you can say for 2 D array we will need 2 loops for 3 D array we need in fact, 3
loops for. For example, in this case we use 3 for loops one loop for i for row variation,
another loop for j for column variation for each row there are variation of each column.
And then for each there is a column page variation.

66
So, this is an example so, that you can understand and you can practice it. So, we have
learned about the basic few things particularly Java tools and resources and then the
basic Java language subsets. And in the subsets only we have certain idea about Java
arrays.

(Refer Slide Time: 37:09)

The array can be of 2 D and 3 D array like and done now next; obviously, more few
more things also on the queue.

(Refer Slide Time: 37:12)

67
That whether Java supports writing recursive program, probably you know the recursive
program and if you know C programming. C programming is very good for writing
recursive programs and recursive programs is basically an easy way to write very
complex and difficult programming structure. Now java in fact, supports recursive
program, then it is interesting to learn how we can write recursive program in Java. And
then other features the input output in the Java and everything.

So, in the next lectures, we will discuss about all this advanced features in java, but
before that I will discuss about applet programming. So, a quick overview of the applet
programming once it is known to us. Then we can have a basic idea about the Java
programming flavors.

Thank you very much.

68
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 04
Demonstration – 1

So, we have learned about how to run Java programs and then the different resources
which are required to support your Java programming. So, today we have a quick demo
about setting our environment suitable for Java programming. We in addition to this we
shall discuss a few more things also.

(Refer Slide Time: 00:40)

So, you should configure your machine right if you use a laptop or any PC so, that you
can run your programs from your project directory. So, we should advise you to build a
directory so, that you can store all the programs that you will develop. And, then we will
also learn about how a program can be edited and the different steps towards the
execution of your program. Finally, we shall have some simple demonstration of simple
small programs so, that you can understand how to deal with a basic Java programming
features.

Let us have some demo, I understand that so, yes. So, in the theoretical discussion, I have
mentioned that you should install JDK version 8. I hope you have already downloaded

69
the JDK 8 and installed in your system. Now, suppose you have installed your JDK
software in program files.

(Refer Slide Time: 02:21)

So, we will see exactly we have installed in our own machine in program files directory
the JDK system, you can see we have installed our programs I mean JDK in program
files directory; the name of the directory here is JDK. And, this is the version where we
have installed the JDK version 8 ok.

(Refer Slide Time: 02:39)

70
Once the installation is successful you have to set the path of your program directory;
that means, the main directory where the all the Java tools, Java codes, Java commands
are installed. So, we have to do it I am giving you the step by step.

(Refer Slide Time: 03:04)

(Refer Slide Time: 03:10)

71
(Refer Slide Time: 03:14)

First you have to go to properties and then you go to advanced settings and the
environment variables and then you have to set the Java home, the variable name
JavaHome then the variable value for the Java home should be set at the C://Program
Files/Java/JDK 1.8.0_171, this is basically the program which you have installed. So,
you have to set this variable name Java home with this value.

(Refer Slide Time: 03:39)

And then you have to set the path. So, the path that you should set using this name that
JAVA HOME then under the JAVA HOME the bin because the bin is basically the

72
executable of all the Java course, Java systems is there. So, this is the setting of the parts
and then finally, you have to set the classpath. So, you can set the classpath variable by
C://Program Files/Java/JDK 1.8.0_171/bin. So, this is basically your executable or the
common files where it will be is it will it is stored. So, you have to set the paths: one the
paths and then system variables are configured this way, it will help you to run your
program from any directory.

(Refer Slide Time: 04:40)

So for example, in this case, we have created one directory. The name of the directory is
NPTEL Java > all final > week 1 > code> demonstration 1. So, today we have created a
directory we [ca/can] can call it as a project directory, the name of the directory is
demonstration 1. You can according to your own understanding you can create your
project directory anywhere in your machine, in your system, in any drive. And, then once
you do it you will be able to now create your program, compile your program and
executive your program.

Now, I told you the Notepad++ is a very good editor which you can consider to write
your program. Now, I am just opening this Notepad++ software so, that you can see.

73
(Refer Slide Time: 05:27)

So, here is basically opening the software Notepad++ So, this is the window of the
Notepad++. So, it is basically text editor you can type anything whatever the things you
can type from the keyboard. So, this is the simple editor anybody can use it ok, our
objective is to write a Java program; I am writing a Java program.

(Refer Slide Time: 05:53)

So, let us start Java program is like this you just ok.

74
(Refer Slide Time: 05:56)

See the Java program that I am going to write it, I will not write it here through
keyboard; I have already written for you I am just opening this file. So, I am opening the
programs in the first Java program. So, this is the first program that we are going to have
a demo. So, this is the program whose name is the, it is class name is rather
FirstJavaProgram. So, this program is now supposed you have typed it from your
keyboard then our next task is to save this program. So, there is a save menu and you can
go save menu save as so, let the FirstJavaProgram is saved.

So, this so, the program is saved and after saving you can go to your directory where you
can see the program is already saved here. For example, here FirstJava FirstProgram.java
is saved here ok. Once the program is written and saved successfully our next task is to
compile it.

75
(Refer Slide Time: 07:02)

For this compiler, we have to go to the command prompt. So, you have to go to the
command prompt from your Windows system if it is there and if we use the Unix system
then you have to open a terminal so that you can use it to type the command. Now, in
order to compile your program the command that is required is javac and then you have
to give the full name of the file. The file that we have used to save our first program is
FirstJavaProgram.java. So, we have to give the name of the file in the same way as the
name of the class you have given and it is a case sensitive so, be careful about that.

So, this is the example where javac we have invoked the compiler to compile the
program FirstJavaProgram.java. Now, let us compile it ok. So, as there is no error, no
message in the command from this means that this program has successfully compiled.
Once on the successful compilation, you can see in the same directory one file is created,
the name of the file is the same as the name of the Java file except the extension is .class.
So, here you can see the byte code file which has been created is FirstJavaProgram.class.

So, one this program is successful on compilation now we are ready to run it, to run this
program the command that we said to use it java. So, Java first program
FirstJavaProgram and then .class you can use the .class or even if you use the class also
no issue so it will run. So, here, for example, the class file name is FirstJavaProgram. So,
just simply type java and the name of the class file, namely FirstJavaProgram here. So,
this is the program that has been executed and as you see this program is basically used

76
only one statement namely System.out.println() and within this println() is basically
typed the “Congratulations your first, just open or just browse.

(Refer Slide Time: 09:16)

So, this is the message that it will display “Congratulations your first Java program run
successfully. Now, we can see that output also gives the same thing. This is basically the
steps that you have to edit your program, compile your program using javac and then run
your program using Java command. So, these are the few steps that you should consider
and now say, suppose there is a mistake in this program.

For example, you have given the name of the class file FirstJavaProgram1, but you saved
this program as a FirstJavaProgram.java saved this program as a FirstJavaProgram.java
right. So, yes this is the program that we have created, but the see the name of the class
file that we have created is FirstJavaProgram 1, but the name of the file that we have
saved it FirstJavaProgram.java. The two things are not the same; this means that in this
case compilation should not be successful.

Now, let us run the program the same javac FirstJavaProgram.java and then run it. No,
you have to no your program, no class file is what.

Student: Different from the class file name.

So, how it is compiled successfully?

77
Student: Compilation will be done. The compilation will be successful.

Now, let us see run the program. So, to run the program java FirstJavaProgram right now
what is going on here, how the compilation will be successful. Why we have saved the
program as JavaProgram1.class.

Student: Yes.

Yes, now here we can see we have saved the program file as the name FirstJavaProgram,
but the name of the class that is there in the program is FirstJavaProgram1. So, there is
no match, if there is no match that means mismatch then the compilation will not be
successful. So, for example, in this case, we could not compile the program successfully.
So, here you should note that the name of the class file should be same as the name of
the Java file. Then, in that case, the program will be compiled successfully and if it is
successfully compiled then you will get some execute some if the execution will be
possible.

Now, let us see I have another simple demonstration of another program. So, HelloWorld
yes so, this program and I am writing. So, I am writing another program. Let us give the
name of the program is helloworld.java program. So, HelloWorld this is the program and
it has only one statement, it is very similar to the FirstJavaProgram.

(Refer Slide Time: 12:45)

78
I will combine it so, javac this program has been saved as helloworld.java. So, here the
name of the file Java file is helloworld, all in small letters helloworld.java. So, program
compilation is successful then we will be able to run it. So, running the program using
Java right so, java helloworld . right yeah; so it gives Hello, World. Now, in the same
program I am adding one more statement System out . println() System.out.println(). So,
here instead of “Hello, World” I am typing “Hi”. So, here the two messages: the first
message “Hello, World” and the second message “Hi” will be printed.

I am again compiling and then again execution. So, you see Hello, World and then Hi.
So, you can understand about, if you want to print some message on the screen the
statement that is required in Java program is System.out.println(). And, whatever you
write within double quote is basically print will display on the screen (Refer Time:
14:18); that means, as if whatever it is written there. So, Hi for example, again Hi . . .
within the double quote and the same thing Hi . . . right Hi . . . ok; now if you save it
again run it so, it is like this.

Now, if you want to print two messages in one println() statement so, we usually use plus
symbol so, Hi plus no no Hi ++ Debasis ok. So, now here basically in one line, it will
print Hello, World then the next line Hi and then Debasis will be printed you can see ok.
So, now you have hope you have understood that is a very simple statement and the
simple program indeed. So, how you can run the simple program? This is a good starting
point for you actually ok. Now, let us consider another program, this program is basically
we have discussed how to define an array and then how to initialize an array and how to
use the element which is stored in an array.

79
(Refer Slide Time: 15:32)

So, this is the one program that we have written here the name of the program is
TestArray, where capital T and then capital you should note it. So, this is the name of the
program your Java program and the and this program should be saved as TestArray.java.
So, this program has been saved as a TestArray.java in the directory, the current project
directory the test right. So, this is the program TestArray.java we have stored it.

Now, let us look at the program state statement by statement, we have to understand this
program what we have done it now ok. So, this is the name of the class the TestArray,
this is the name of the program and then public static void main String args. It is as usual
there the standard syntax that you have to follow; you will understand the meaning of
this statement later on.

Now, next is basically we have declared an array type of integer. So, int a within square
bracket and then it is basically initialization memory allocation and then declaration all
the three things have been done together. So, this is the statement int an array symbol
equals then within second brackets 10 20 30 40 50 so; that means, the array a is of now
size 5. And, this array contents 5 elements which are stored in a 0 location 10 a 1
location 20 a 2 location 30 a 3 location 40 and a 4 location 50. So, this array is stored and
then the next one for loop, this for loop basically we will print the elements which are
stored in the array. So, this loop will roll starting from i equals to 0 because the array
index is from 0 and then it will loop till value of i less than a.length().

80
So, a.length() is basically what is the size of the array a. So, a.length() is the specific one
function that you can use and that will return the size of the array. So, in that case,
a.length() is 5 and then the next is basically an implementation of the loop variable i ++
and within this loop System.out.println(). So, it will print one element in the array at a
time and then go to the next loop and so on. So, this will print the array. So, instead of
println() if we type print it basically will print all the elements in one line. So, ln and
print the difference is that is basically in one line or in a different line.

Now, let us have the ln I will discuss simple print as an alternative to println() later on.
Now, once the array is array elements are printed our next step is to calculate the average
value of all the elements which are stored there in the array. So, we have declared one
variable called the sum and it declared as a float and then the average has also a float
variable. So, we declared two variables; one is the sum and the another is average and
sum is initialized a 0 at the time of declaration.

Now, so the next loop is to find the sum of all the elements and finally, it will basically
calculate the average is basically sum divided by the total number of elements stored in
the array that is the size of the array. And finally, there is a System.out.println() and it
will print the average value with this statement that average equals the average value.

Now, let us run this program using javac TestArray.java is the program file name ok, run
it run ok. So, this program is successfully compiled, now we are going to run this
program right. So, here you see the first few lines 10 20 30 40 50 is an outcome of the
first for loop, it basically it display all the elements which are stored there. And, the next
for loop calculate the sum of all the elements the stored in the array and finally, calculate
the average which is printed within the System.out.println() average equals to 30.0 in this
case.

Now, I will just want to do some changes here in the first for loop, I am writing system
out println() instead of println() simple print and then let us see what will happen right
run. So, it is little bit not easy to difficult I can put some single space. So, I can go to the
print again print a.i ++ and then within double quote plus double quote blank space. So,
if we give a space so, the display will be quite comfortably visible.

So, we make the print statement like this. So now, here we can see how the output is
displayable on the screen. I can make a little bit different output at the end of the right

81
System.out.println() at the first for loop, at the end of the first for loop brackets you
know here right here, here you can type right one System.out.println().
System.out.println() just only brackets double quote right nothing ok.

I have so this semi colon so, I just see so in the first for loop it will print all the numbers
in one row, then at the end of the for loop it will go to the next line and then in the next
for loop it will calculate sum and then print at the next line. So now, you see the display
is more comfortably presentable so, that you can see about it, yes now you can
understand. So, this is the matter of simple how you can configure your printing on the
display. So, using System.out.println(); regarding this System.out we will learn a lot
when we will discuss this method in details.

(Refer Slide Time: 22:34)

So, let us come to another one example. In this example, we will consider here the
3DArray. Now, let us give the name of this program as a 3DArray as the file and you
should save this program as a 3DArray.java. So, this program if you see the name of the
program file is 3DArray here public static void main String args it is as usual ok. And,
now we have declared here. So, here we declared an array of type integer and we gave
the name of the array as my3DArray. As it is a 3DArray so, it should have 3 square
brackets as it is shown here and then this array will be declared and then memory
allocation for this memory allocation, we use the keyword new; new is basically the
memory allocated.

82
So, it will allocate the memory for the array and here you see 3 4 5 are the 3 dimensions.
So, the first dimension is for the number of pages, the second is for the number of rows
and the second next last dimension 5 is the number of columns. So, if it is a 2D array
then is a 4 5, if it is a 3D array then 3 4 5 like so, 3 dimensions. So, it is basically is a
collection of 3 2 dimensional array 3 2 dimensional arrays where each 2-dimensional
array of size 4 rows and 5 columns. So, here basically if we print it then it will print as a
3 2 dimensional arrays actually.

Anyway now, just let us see how we can initialize, there are you can read the total
number of elements which can be stored in this array is 60. So, 60 array typing from the
keyboard sometimes is very difficult anyway. So, we are just using one for 3 for loops to
initialize this array. Now, to initialize this array I use one I mean is the nested for loop I
should say, here see the nested for loop. This loop will roll for 3 loops actually the
innermost loop with k = 0, k < 5, k ++.

The innermost loop is basically 2 read the elements in an in a row for each column in
that row. Then the next the outer most loop the for i j equals to 0, it j less than 4, it
basically we will try to read for all the rows in 1 2 dimensional array. And then finally,
the outermost loop is basically read each 3-dimensional array, each 2-dimensional array
in 3D arrays.

And, here the statement my3DArray i j k for any values of i j k will be stored as is a
product of i star j star k star. So, this way we will we initialize the array and then finally,
the next 3 loops again to print the array. Now, so the statement that we have considered
to print the array is basically again 3 loops same as the loading the array, initialization of
the array in the same way; only we have used that System.out.print() my3DArray the
value it will print. And then finally, the last statement to give to the cursor into the next
line. So, this is the program which basically declared a 3DArray initialized the elements
into that array and finally, print the elements in that array. So, now let us run this
program, but before going to run we should compile it so, javac right yes. So, the
program compilation is successful; now run the program using java ok.

Now, here you see the output. So, I told you that 3DArray can be displayed 3DArray is
basically I have to display the 3DArray in the 2D a plot. So, that is why we did it by 3 2
dimensional arrays. So, the first 2-dimensional array is for the first we can you can call it

83
as a phase. So, 1st phase and then the 2nd 2-dimensional array for the 2nd phase and then
the 3rd 2-dimensional array for the third phase and, you can see in each phase there are
how many rows.

Student: What was the.

What is the 4 cost?

Student: 5 (Refer Time: 28:02).

4 rows and 5 columns so 4 rows and 5 columns, in each 2-dimensional array there are 4
rows and 5 columns. So, this is the way we can handle the 3D array. Now, as you have
already learned 3D array simply learning the 2D array also similar. So, in that case, it
you just do the same program only you have to use 2 for loops for initialization and 2 for
loop for printing all the elements. So, it is given as an exercise for you, you can try just
repeat the same thing, declare a 2D array, initialize it using some i star j like and then
display the elements ok. So, you can practice it so, that you can learn it.

So, today is our demonstration is up to this and in the next lecture we will discuss about
the applet programming. And, followed by this discussion, we shall have a
demonstration on applet programming.

Thank you.

84
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 05
Java Applet Programming

So, we have run few programs and then how they can be composed in Java environment.
So, initially you may find it difficult to cope with this, but you should not write lose your
(Refer Time: 00:34) actually right, you have to be patience. And of course, if you have
any difficulties while you are learning then you should I mean post your questions that
difficulties and doubt. So, that you can at least you can understand.

Now, we have learn about some simple programs in fact, in Java there are two types of
programming’s is there they are called Java application and one is called Java applet. So,
in today’s lecture we will just have an idea about is not the details running details
running will takes more time so, a very simple overview of Java Applet Programming.

(Refer Slide Time: 01:32)

So, far the Java applet programming is concerned so, basically yeah so, Java
programming for applet. So, the idea about as I told you there are two types of
programming, the application which you have already learnt. And then applications are
most simplest simple programs actually those are basically in for example, C C++
python that you have already tested maybe, but the applet is a little bit a

85
[difficu/difficult] different type of programs. And then Java is a unique program
language which is basically suppose to do that.

So, the name applet actually whenever you want to mention something small so, it is
basically late. So, small application is called Java applet. So, it is basically Java applet is
nothing, but a small program in Java and but more specifically these are small program is
for writing graphical user interface related program.

(Refer Slide Time: 02:28)

Now, so applet is basically a view also and then how we can create a view using Java
that is the concept Java applet programming. And typically a Java applet will look like
this and if you see the Java applet here is just look like a window. So, an applet is
nothing but an window.

As the window is basically the one bar is call the title bar. And then there is a name of
the windows and then these basically display area of the windows. So, this is the idea
about an applet and then applet this is very simple version of an applet that I have shown
you and here you can include image, then multimedia document text link what is not. So,
this basically the display area, where we can include many components, that is required
there in case of GI or windows programming.

86
(Refer Slide Time: 03:40)

And then another example of applet if you can see it so, you know it this is basically look
of a calculator it is also an applet. And although things are basically close pattern
minimize pattern, then maximum pattern all these things are there. And then these applet
contains a number of components for example, these are the component is called the
button and then level and this is the one component is called the area, where it will
display something. So, it is called a text field area and like this. So, this is an another
example of applet that is there so, we will see exactly how using Java we can create our
own applet.

(Refer Slide Time: 04:23)

87
Now, so let us write a program for a simple applet, I want to write one applet, which
basically we will display one message hello world we have already learn how a hello all
can be displayed on the screen right in the window, command window, command
prompt. But, here it will display through an applet; that means, on window and within
the window the string will be there. Now, here is a very small look of the program and
here actually the where command can the placed. So, it is a basically command about the
program.

So, that you usually whenever write program put as many commands as possible so, that
you can understand later on or anybody can understand your program so, the command
and these are the two essential import I told you that Java has lot of packages. If you
want to use some package or packages, then they should be imported first. So, the import
command here is basically to import all the packages that you want to use in your
program. For Java applet programming the two packages are very essential one is called
the java.applet and another is called java.awt. So, here you can see how one can import
the two packages Java dot applet and java.awt.

And if I write again after name of the packages, then java.applet or java.awt a particular
name it is actually a particular class, in Java dot applet there are many classes, but I want
to use only one particular class so, I can mention dot applet. Similarly, in awt I want to
mention only one package class call the graphic so, I use it. So, this way I can import
package here we have used imported two packages and dot applet and then dot awt and
two classes in that packages applet class and then graphics class.

So, this is about import statement, then there will be the class definition as I told you
here is also the class definition, here the name of the class that I have discussed is here.
The name of the class means this is the program that we are going to write; that means,
here is a applet program having name hello world, but here one thing we have used it
that extends see it is always a standard syntax, if you write an applet, then applet class
that you are writing that mean this one should extend one package class call applet.

So, this is the standard syntax that you have to do it. So, this is basically defining the new
class of your applet programs. Now, you can find the difference between in case of
simple application we use, simple class hello world a p p and then within this right, but
here we have to do it. And then these basically the closing and matching second braces

88
indicating that whatever the code that you want to include, the code indicates the what
are the data and the methods that you want to include that should be enclosed within the
closing and beginning brackets.

Now, in this in this program we have only one what is called the function who have
declared is called a method of course not function so method. So, the name of the
method is paint, I have declared here one method public void paint I will discuss about
what is the meaning of this later on you just simply take it that ok, this is the syntax that
you have to follow while you writing the paint methods. So, paint and then this argument
also you have to mention. So, here we declare one method called the paint method and
this method in order to display on screen use this kind of syntax: g.drawstring(). So,
this method is basically declare in graphics class; that means, this method is already
known, you can just simply use it and this method will basically print a string on an
applet.

And then this location indicates that where in the applet it will print is basically 150 150
means in the Cartesian location coordinate x location and y location. So, that if the applet
is a 1000 by 1000 right, if it is a 1000 cross 1000 pixel, then is 150 and 150. So, here the
g dot string will be displayed so, this is a concept here. So, this is basically simple one
applet you can write that will display one string hello world on the applet.

Now, let us see how to run these applet how to of course, editing is editor come editor
say Notepad ++ and then how this can be edit in shape and then compile and finally, it
can be executed.

89
(Refer Slide Time: 09:43)

Now, the name of the applet should be same, as the convention that we have already
used while you are saving this program as the same as the name of the class here, the
name of the class is hello world. So, name of the file where you should save this program
is helloworld.java.

(Refer Slide Time: 10:15)

So, you can save this program as hello world dot Java file and; obviously, in your
working directory you can save it and then compilation, we have used Javac compiler to
compile Java application the same is also valid for here, to compile a Java applet you use

90
the Javac command. So, and then you write Javac the name of the file that, you want to
compile hello world dot Java in this case. So, it will compile these Java file into class
file.

(Refer Slide Time: 10:43)

So, it will create a class file, the name of the class file will be same as the name of the
file in Java except the extension dot class. It is a same as in case of application that we
have learned.

(Refer Slide Time: 10:55)

91
Now, I will come to the discussion of running I mean how to execute this class file. Here
is the difference from the application to the applet running, in case of applet, in case of
application we use Java command is basically interpreter which basically executive your
program, but in this case Java we cannot use it, whether we can use applet viewer instead
of Java we should use applet viewer.

But applet viewer can run only an HTML file, this means that the class file that you have
created should be stored in an HTML file. Now, here is a typical look of an HTML file I
do not know whether you know about the HTML file and then HTML tags and
everything. But, if you do not know absolutely it is not is a matter of concern, you will
learn it shortly once you learn many other applets and then run it then. There is a basic
syntax that you should follow basic structure that you should follow in order to embed
your class file into an HTML file.

And here is basically the HTML file look like. So, this is the beginning of the tag this is
the ending of the tag as HTML construct is there, these are body; that means, this is a
body of the HTML and here is the syntax that you should follow to MBT or dot class
file. So, applet code and then hello world dot class, this is the file that you have created I
mean compiled by writing your Java applet program.

And this is the concept that how large the applet you want to display. So, it is 300 300
indicates that if your total screen size is 1000 by 1000, then out of this 1000 by 1000 on
the portion 300 by 300 will take to view your applet, I mean display your applet on your
computer screen. So, 300 by 300 is the size of the applets that will be displayed.

So, you have to write an HTML file and then write this code in the HTML file and save
this program. Now, while you are saving this program, you can give a name of the file
for this HTML, the name of that HTML file can be anything name of the file can be
anything, but the extension should be HTML. So, here basically this is the applet
embedded in an HTML file and then let us give the same name as the program file name
that is means hello world, but in this case I have given the name for example, hello Java.
So, in this case the name of the program is given as hello Java dot HTML.

92
(Refer Slide Time: 13:28)

Now, you can note that the name of the class is hello world, but I have given the
different name it is ok, even you can give x.HTML, a b c dot HTML team dot HTML
any name. So, here it is not necessary to maintain the same name as the file name and
then class name not necessary, you can make any name, but the extension should be dot
html. So, that HTML can be browsed by any browser. So, once you save this program as
an HTML file, then you are ready to run this program; then you are ready to run this
program.

(Refer Slide Time: 14:38)

93
I told you in order to run this program, you should use applet viewer. So, use the applet
viewer as a command and then you just run the program as an applet viewer.

(Refer Slide Time: 14:51)

So, here is the command is that applet viewer and then this is the name of the file that
you have created say for example, hello Java dot HTML.

So, here for example, hello world these are name of the HTML file. So, if you write it
then this file will be executed on execution, you can see the output on execution you can
see the output.

(Refer Slide Time: 15:26)

94
The output will look like this. So, hello world this is the string that it will print here and
this is the 300 cross 300 size and, this is a location (150, 150) of the point, where it will
start painting the text. So, you have learn about how a simple applet can be created and
then the same can be executed.

So, I should advise you to test the kind of applet programming as a first experience how
to write the program. And there are many more things are involved while you are writing
applet programming, I will just try to give I mention few important things here, many
more things will be discussed, when will discuss applet in details. So, writing an applet
needs lot of many other I mean exposure to many more things. So, it will take it is own
time and we will learn it slowly, before going to learn many more details about the
applet, I just want to have a brief overview about how what are the structure of an applet
in general.

(Refer Slide Time: 16:48)

So, typically the structure that we have learnt so, far is basically writing a program in
Java syntax. So, essentially while you are dealing with applet programming so, three
things are there. So, the first thing is your program that you should write following some
Java syntax and, then program will look like this.

And then second thing that you have to embed the program using an HTML file which
look like this form. So, these are the two things are obvious state that you have to follow.
And then running this kind of things using an applet viewer and this will look like this

95
output. So, these are the three things. So, far the Java applet programming is concerned
the basic steps that you should follow.

(Refer Slide Time: 17:52)

Now, apart from this basic steps there are many more things involved, while you have to
develop your Java applet. And then basically the how a complete Java program Java
applet you look like this. Is basically many more things are involved there I just want to
highlight the important things that is there. So, while you write a Java applets the first
thing that you should write the input, as I told you in our program that we have
experienced now. So, there basically import Java dot applet dot applet class and then
Java dot awt dot graphic class these are the things like. So, it is there import section you
have to mention what are the things that you have to import it.

And I wants the input is there then main body of the applet class, as a main body first we
have to start with the naming of the applet so, that name you have to give one name of
your own. And these are the things that you have to always fix public class always you
have to give it, there is no other thing that you can write if you do not write then there
will be compilation error. So, without any hesitation you just right that public class and
then give the name of your class and, then your class should extends the applet so, this is
also another extends.

So, this is your own and this is the standard that you have to follow always and, then
what about the code that you want to use in your program, you should write within the

96
starting and then closing brackets. So, these are the second part I can say. And then
within this part they are may required some variable to declare. So, if you need some
variable that is required in your applet programming, then you define all these things
here. And then the different methods that is required to build your applet should mention
their. So, there are all together four parts, that you have to think about while you are
writing applet in java.

So, regarding the different parts we will discuss one by one, but in todays lecture we will
try to discuss about basic things and mainly what are the different methods that can be
there, here I want to mention again one thing is that any method should not be included
there, there are certain free defined methods, you can only use them. However, the
methods you can fill them that mean methods are fixed, but they are body you can write
with some codes that is required for your applet.

(Refer Slide Time: 20:29)

So, these are the things are there now, let see what are the different methods are there in
this applet programming obviously, the method that we have discussed already with our
own applets, has only one method the name of the method is paint. So, this method is
there you cannot change the name of this method, in any way you cannot write any other
method of your own name there. So, this is a fix method that you have to use it the paint
with. Other than this paint method there are few more methods are there, which needs to

97
be written in your program Java applet the methods are called here for example, we have
listed the three methods one is init, another is start and then stop.

(Refer Slide Time: 21:02)

And there is another 2 methods are there, we will discuss about destroy and then paint.

(Refer Slide Time: 21:19)

So, all together only 5 methods those you can use in your applet. So, five methods have
their own meaning, the start method is basically to start running an applet, sometimes we
have to control applet view. So, in that case if you want to control then you start,

98
sometimes you have to also close the applet which are there in one program you can use
3 4 applets.

So, sometime we have start one applet close another and like this. So, in that case you
use start and close stop method and then paint method already you have used it if you
want to draw something on the applet area, then you call the paint method and the in the
body you can write anything like. And destroy method if you want to remove an applet
from your program. So, you can use the destroy method while they are running. So,
destroy will kill the applet view forever in a program execution. So, these are the
different methods are there and, I will just highlights or explain one method call the init
method.

(Refer Slide Time: 22:28)

So, let us see the init method how it can be reconfigured in your applet programming.
Now, here let us look at the low code these are import section already we have learned
about it. And then this is the name of the applet called hello world and in our earlier
program this code was not there. Now, I want to use this code where this code this part
of the code already it was there. So, it is fine now let us see what is the [imp/impact]
impact of this code so, here basically init one method I have called these basically call
another method resize is a one method which is defined in awt it is already there.

So, this resize method I call an 200 200 what is the idea about is that. So, whatever the
applet size if you mention in your HTML, you can note that in HTML we use usually

99
what should be the size of your applet view say 300 300, but after the CPU call and init
method with resize as 200 * 200. So, an applet size will be automatically resize to 200 *
200 view there. So, so idea about resize command is there. Now, let see the output if you
use resize through init method and if you do not use it how it will work for you.

(Refer Slide Time: 23:59)

So, here is the method the view without any resize. So, this is the program this is the
applet the 300 and 300s are default size that we have mentioned and then the output will
look like this. So, here basically 300 by 300 is the applet without any resize.

But, if you use the resize method that mean these code is used and again you use the
applet, this is the HTML file, then the applet that will appear with the smaller size. So,
resize is basically will allow a programmer to control the size of the applet as it is there.
So, this is one example of resize in init method use of init method, there is another one
use of init method. So, that applet how we can given input to an applet, because while
applet is running it is a basically via HTML and then how input to an applet be given
there. So, input to an applet if you want to give then you should give via HTML itself.

100
(Refer Time: 25:04)

So, here also the init method can be used for this purpose. Now, here let us look at the
code of another use of init method which is basically being used here to input pass an
input to an applet while applet is running. Now, if you see the code little bit carefully.
So, these are the import as usual and it basically import applet and awt and dot star is
basically another way of importing; that means, it will input everything. If you are not
sure about which particular class is responsible for your applet program, then you can
instead right dot start that mean all the classes will be imported into your applet program.

In this case the name of the class that I have given is rectangle test, name of the rectangle
and this program basically is mean for drawing a rectangle on the applet. So, for this the
method that is required is g drawrect, it is already defined the graphics package. And
then it will basically rate and this basically needs 4 parameter x y w h. So, idea about is
that if this is the applet view and then x y is a coordinate; that means, from where the
applet rectangular will start and this the w and this is a h. So, x y and this is the w and
then h. So, this is the specification that is required. So, we have to pass the input while
we call g.drawRect() and the four parameter that is require here x y w and h to be
passed.

And then we want to get the value x y w h from the applet itself. So, for this we can write
the init method. So, this is the init method we have write it here and then code in the init
method is there. This is a typically I mean some code it is required, here the idea it is that

101
say there is a integer passing, it is declare it is already there in Java dot line package
basically it will pass the value that is there in the applet and then store as an integer. So,
this is the standard syntax in Java. And get parameter is basically get a value from the
HTML code. So, this is a get parameter method and then that parameter where in HTML
code, it is written as x value. So, in HTML code if there are certain parameter which is
defined as x val ,y val, w val ,h val, they well be retrieved from the HTML file process it
and store them as an x y w h in this case as an input to the parameter applet.

So, this is the idea about how the input can be given to the applet. Now, let see the so this
is the program your new applet program where it will read x y w h from the HTML file
and then it will draw a rectangle. Now, let us see how the HTML file will be in this case.
So, what is the change in their HTML file is there.

(Refer Slide Time: 28:20)

So, here the HTML code will be same as earlier HTML body tag and everything, only
the code that is required here, basically applet code this is the code that needs to be
executed and you can write the dot class also dot class. And then this is a width and
height that you have specified that window size and here param name x val and this
value equals to 20; that means, you want to say that this is a parameter name x value
whose value is 20 this is a typical HTML code that occupy x value is now val 20 40 150
for y value w value h value respectively.

102
So, this is the HTML code that you have to write in order to pass the values, from an
HTML to the applet code it is there. So, once these HTML code is there you run this
code as usual using applet viewer applet viewer.

(Refer Slide Time: 29:20)

So, applet viewer can be run here and if you run this HTML code using applet viewer, it
will display the applet look like this. So, it will draw the rectangle which x y coordinate
with this one and w is this one and h is this one. So, applet will be drawn. Now let us run
the same program, but we changing the deferent value. So, if you want to change the
value definitely you have to negotiate the HTML file there.

So, in HTML file here 20 40 150 is written, if you give the different value so, different
rectangular will be drawn accordingly. Now, let see how the new HTML file can be with
the new set of values and then corresponding HTML can be drawn.

103
(Refer Slide Time: 30:03)

So, here again I have rewritten the HTML file here with the different values 30 13 in this
case and then corresponding applets will look like this. So, you can change of change,
while you taste it and then writing the different values and then you can run by means of
applet viewer, you will be able to see that how the different shape it is there.

Now, if I ask you that how to in addition to the in addition to drawing a rectangle, if I
want to print one message here that this is my rectangle, how you can do that, you do not
have to do anything here especially only the thing that you have to use that you use in the
paint method some other value like. So, for example, in the paint method here in the
paint method for example, here right. If you want to draw a message on the applet so,
what you can do is that instead of g drawrect you use g dot draw string this method and
then you can type whatever the string that you want to do so, you just use this one.

So, this way in the paint method you can add any methods of your own to display
whatever the content that you want to do it. So, this is the way that the applet can be
developed and have a basic idea about how the applet can be developed and, then you
can execute it using a HTML. So, here our objective was to how to write applet and then
the same can be displayed on the screen ok.

104
(Refer Slide Time: 32:28)

So, we have learn about applet now; obviously, there are I mean certain differences
between application and applet. And as a first look they have the two different structures
and as you see here these are structure of a usual applet look like and here is a structure
of an applet and this is a structure of an application. And in case of application you
should declare one class call the main class and in main method, but you can see in case
applet there is no main method.

Now obviously, it has implication will learn about this later on. And then so, this is the
one important different that in case of application one class is there, which includes the
main method, but in case of applet there is no need of main method. And another
difference is that an application can include any user defined method; that means, user
can give some name of the method and then use it. But, in case of applet other than some
specific methods user cannot give any methods. So, these are the key differences
between the two in addition to their, there are few more difference there are few more
differences also.

105
(Refer Slide Time: 33:44)

So, other than the naming and the main class and the main methods that applets needs to
be embedded in an HTML page try out to it is execution whereas, an application does not
required. And so, far input output is concerned; obviously, application will allow to in
read any input from any source, from keyboard from file or whatever it is there, but as
you see in case of applet these kind of input is not direct input is not possible. If you
want to give any input, then you should give all the input via an HTML file. And few
more salient difference between the two things that applet cannot communicate to other
applet or other browser or other machine.

Whereas, application will be able to communicate that is; obviously, recover for network
programming internet programming then JDBC :Java Data Base Connectivity and
elsewhere, but applet cannot do that. And applet also cannot run any program written
maybe in any other language or any other application from the local computer. So,
whereas, application can do that and, applet also not able to interface with any other
programming languages program written in any other programming languages.

106
(Refer Slide Time: 35:18)

So, these are the differences; obviously, the reasons are there why all these are the
differences. All these are the differences because the purpose of these two programs are
different, that is why the developer makes the differences for us and definitely all these
questions on the answer to all these question that may why so, many restrictions in
applets are there will be in due course of time. And then obvious another question is that
whether we can build and application and applet together. So; obviously, what is your
idea is that no applet and application are the two separate entity they cannot be build
together. Anyway so, we will discuss all these things and many more other things in next
lectures guys.

Thank you.

107
Programming In Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 06
Demonstration – II

So, in the last lecture, we have learned about programming in applet programming; Java
applet programming. It is something different, in fact, java programming is very fun this
is because of the applet in fact, an applet is really enjoyable. So today, we will have a
quick demo about how we can write the java applets and then the same applet can be
executed and then the different twist in the applet also try to understand in today’s demo.
So, let us first write our first simple java applet program.

(Refer Slide Time: 00:57)

So, so in today’s demo, we will discuss how we can write a java applet and embed it
using HTML file. And there are few applet programs that we will discuss that the simple
applet program called the hello world applet and then there are a different way the applet
can be configured is basically resizing setting background color and then taking input to
the applet via HTML and all these things. So, today we will discuss all these things in
our demo. So, let us start our demo,.

108
(Refer Slide Time: 01:34)

So, we are now in a position to write our first java applet, this is not applet later on this is
not the right one, right. First hour you just run 2.1 2 point yeah. So, this is the simple
java applet that we write, we have written it for you yeah. So, as we have already
mentioned in our discussion in the last lectures that the first portion that should have the
input section for any java applet you have to import two packages the java.applet.Applet
and then another package is java.awt packages and under these two packages two classes
namely Applet and Graphics.

So, these two class files are to be inputted because they are essential for running your
applet program. Now here we see the name of the applets that we have given here is
demonstration_21 and we have already mentioned in the last lectures that it should
extend the class Applet. So, extends and regarding extends we will learn about it later on.
So, this is the way the name of the class file that, the name of the java applet program
that you can give it in this case demonstration_2 1 is that java file should be.

Now, these are simple java applet it includes only one method the paint method and the
paint method is to display a miss, the name the text here, in this case, it welcome and 150
and 150 is the location where the text will start displaying in your applet. So, this applet
once it is written you should save it with the extension.java and the name should be
given as demonstration_21.java.

109
So, we have saved this file as this one demonstration_200.java and then we should
compile it, that compilation is the same as the java application compilation is javac. So,
javac then name of the java file demonstration_21.java (Refer Time: 04:04) you type it.

(Refer Slide Time: 04:10)

So, right so javac then the name of the file it is here at demonstration_21.java, yes. So,
this is the file yeah. So, this now this compilation produces a class file, the name of the
class file you can see the demonstration_21.class.

So, this file is required to run the applet, now in order to run this applet we need 1
HTML file to be created.

110
(Refer Slide Time: 04:55)

Now, with a simple HTML file look like this here the standard syntax that is there, you
have to blindly follow it at the moment later on you will be able to understand the
different tags the meaning of these things. Today also you will be able to explain some
meaning of the tag.

Now, the important tag it is there in HTML file called the apple;t applet code
demonstration_21.class the file that you have just now created and then here width
equals to within single code 300 and height equals to 300 and you can see there is no
comma nothing is there.

So, this basically specifies the size of your applet should be on your display screen. So, it
is basically 300-pixel X 300 pixels. So, once this HTML file is written you can save this
file using any name. In this case, we have given the name of this HTML file as
HTML_21.html. So, let us save this HTML file as HTML_21.html. So, this file is
written here ok, we can see the HTML file that is created here in our directory project
directory HTML 21.

111
(Refer Slide Time: 06:10)

Now, we can run this HTML 21 using applet viewer. So, I applet viewer and then give
the name of the file as HTML_21.html. So, this is the way that you can browse this one
and once it is browsed this applet is created. So, this is the look of the applet that you
have created, here you can see the title bar and then default applet is there and that
welcome it is there.

Now, if we again go to the applet program that we have written here, go to the program
here ok.

(Refer Slide Time: 06:43)

112
So, welcome and then we can write welcome NPTEL Java, NPTEL Java capital
welcome yeah right fine. Now let us see how we can run it again repeat the same
procedure compile because you have changed in the main program. So, this should be
compiled again and then the class file should be created and the class file is created and
the same HTML file we do not require to change anything because HTML file you will
remain same then run it. So, it will display it, yeah you can see this will display this one
right. Now let us see if we change the applet code little bit let us go to the HTML file
that we have created for this applet. Yes and then instead of 300 we just give 200 x 200
and then save it.

So, here we need not compile it again because there is no change; however, HTML file
does not record any compilation. So, simply browse this HTML file using applet viewer
and then you see because of the size has changed the text that will be printed according
to these things not properly displayable so you have to be careful about it. Now if I
change the width say 500 x 500, you will be able to understand the meaning of width
parameter and height parameter in the applet code they are in HTML file yeah.

(Refer Slide Time: 08:20)

So, you can see the size of the applet has increased and then the display and everything.

Now, go to the applet program again and then here that g.drawstring we have used only
one text. So, let us print another text. So, we just repeat it. drawString and then
g.drawString then install welcome. So, let us pin that Kharagpur and then location I just

113
see 50 and 20. Now let us see we have changed the location; that means, the welcome
will be printed in some location and then 50, 20 really and we have changed the program
file applet program. So, we have to compile it.

So, let us compile and then now after the compilation we just no need to change in the
HTML file. So, it is not required and then we can browse the HTML file using applet
viewer ok, now you can see two things, the Kharagpur is printed at 50 20 location
whereas, welcome NPTEL java is printed at 150 150 location. So, this is the way the
applet program your first applet program where you can display some messages or text
in your applet view applet window. So, these are first applet program.

Now, let us go to some other applet program; we have another program where you can
see the applet, the applet that we have shown you here.

(Refer Slide Time: 09:45)

So, there is a title bar there is no text displayable. Now, this title can be changed, but to
do this thing you do not have to do anything in your applet program only the thing that
you should go to change in the HTML file.

114
(Refer Slide Time: 10:01)

So, go to the HTML 2.2 program, yes now we have little bit change about HTML code it
is not as simple as the first HTML file that we have created for your first program.

Now, here if you see in the there is a tag called the title and we have written it takes there
the hello world applet, if this is the text is written in HTML file then this text will appear
as a title in your applet status bar in the top of the applet viewer and the rest of the things
are same and lets run this program and then I come we shall come back to this HTML
file again. So, this is the basically same program, but with the different applet HTML file
it will basically use demonstration_22.class. Another java program, java applet that we
have created. So, just go to the demonstration_22.class program first, yeah it is basically
new java applet we have created right run it show it.

115
(Refer Slide Time: 11:07)

Go to that note foot notepad yes notepad just a star. So, this is the new program
demonstration_22 is basically the same, but only it will print hello world. Anyway
basically the same applet, now we embed this applet into our current HTML file, as a
current HTML file like this now let us run this HTML using applet viewer yeah.

(Refer Slide Time: 11:35)

Now, you see right. So, here you can see in the first applet which we have executed, they
are applet viewer demonstration_22.html class. So, it was not showing there, but it is

116
here showing where is this showing that title the hello world applet? It is not showing
nothing. So, let me just do some changes here we can see it.

Browser, lets go to the chrome then we will not be able to go. So, that title will not be
able to display using applet viewer, it will be done by why do not check it fine. So, now
so, these are a very simple applet that we have tested with.

(Refer Slide Time: 12:31)

Now, we will come to this regarding the different methods. So, the applet can include
many methods and in the last lecture, we have discussed 5 methods on which the init()
method. Now today we will just have a quick demo about the usage of the init() method.

Now, here again, see another applet program, go to the camp account background and
outer common from the yeah. So, yeah right , let us look at this program, the first two
lines are the import section and then there is the name of the applet here
demonstration_23 and then here is the init() method, the init() method has only one
statement called the resize 300 300. So, if you ambit this applet class in an HTML file
with certain width and height parameters and then init() if it is if you want to resize this
value into some other values, then you can do it using the resize method, resize method
is defined in applet class.

117
So, by default it will come you do not have to bother about the declaration or defining
the resize method it is already there in the applet class, it will call it and they need to
basically initialize the applet with the desired size in this case 300 x 300.

(Refer Slide Time: 13:55)

Now, let us come to the HTML slide here and you see that 200 and then 200 is the
default height for the applet from the HTML we have fixed it. Now if we run it so we
will see a clear code, clear code clear right.

(Refer Slide Time: 14:15)

118
Now, here javac so, this is basically compiling this program and then class file is created,
this basically embedded in the HTML file and then being the HTML file yeah. So, here
you can see it basically displays of the HTML file here with the resize.

Now, let us go to the resize method again and then let us change 300 x 300 to 500 x 500.
So, definitely, it will reconfigure your applet size to 500 x 500 bigger applet, now again
run the same HTML file. Now we have not done any changes in the HTML file only we
have done the changes in the applet program and we can see the applet is coming in that
way. So, it is basically an HTML file where you can define one parameter which can be
reconfigured from the applet program itself and for these things you have to use the init()
method and there the resize method.

So, we have discussed the usage of init() method and thereby the research application, let
us have another application another use of the init() method this is also init() method is
initially is basically mean for initializing your applet. Now here we are going to discuss
one another applet which basically initializes the background color as by default the
background color is white.

(Refer Slide Time: 15:45)

So, you are, now this is the one program let us have a quick look.

So, in this program we have used another method another class which is defined in awt
packages, the name of the class is color this is basically regarding setting colors of the

119
different components in an applet or applet itself. And so, this is the program name, the
name of the program is demonstration_24 extends applet as usual and you just check a
look the method init. Here in earlier init() method, we use a resize, but in this case, we
use the method setBackground, this method is defined in the color class which is in awt
package and here the method is used to set background.

So, it will basically set the background color as yellow. So, for this thing the parameter is
color.yellow. So, this is the default standard that capital letter you have to write the color
name and then the white paint the same thing it will just pin the takes the applet
background color and this is embedded in an HTML file.

(Refer Slide Time: 16:51)

The name of the HTML file, in this case, is HTML 2.4. Now let us view this HTML file
we have created the class file for it ok. Now so applet viewer runs this HTML file yes,
run yeah you can see the background color is created like this yeah not here, fine.

120
(Refer Slide Time: 17:20)

So, the applet is created now, let us go to the applet program again now we can do many
more things in the init(). So, init() is nowhere for set background, I can again do the
resize, let's resize here resize then 400 x 400 so; that means, initially the applet was very
small I want to make it a little bit larger. So, 400 400 be the size then we have to compile
it again because you have changed the applet code. So, the compilation is done and then
embedded in HTML file no need to change in the HTML file itself. So, now, you can see
the applet is now viewed with a little bit larger in size the color is yellow.

Now, again in the saved background, if we change the color say rate we just write rate all
these colors are defined in color class. Here applet background will appear, we have to
change the class file. So, compile then run this one.

121
(Refer Slide Time: 18:20)

So, the background color will change the rate. So, now, we can understand about the
init() method. So, init() method is basically you should use to initialize your applet view.

Now, there are there is another important application of init() method which is very
interesting also so. In fact, I told you that you cannot give or applet cannot take direct
input from the keyboard. Even applet cannot take any input from any other sources.

(Refer Slide Time: 18:52)

Like say key file or any network or whatever it is there and applet also cannot write
anything into anywhere also, applet only can display on the screen.

122
Now, here is another example, if we want to give some input to our applet. So, how the
applet can be given input to that so if you want to pass any input to your applet program
it is possible by the means of HTML only. Now let us see this is the one program which
we have planned to pass input. So, here basically the applet is planned like this, it will
take any message from the input as an input and the same message will be displayed in a
location x and y which also should be read from the HTML. So, here we have declared x
and y. So, this is the program demonstration to_2 4 5 25 is the name of the applet and
here we declare two variables x and y which basically will be, whose value will be
collected from the HTML.

So, we have declared the two variables as integer and then later one comes, let me finish
this one good here yes and as I already told you this applet will take a message from the
outside also. So, the message that will be stored here in a temporary variable the name of
the variable is msg called the message and it is the type of String; String is a class which
is already the declare in the lang package java.lang package. So, it is by default it is
imported. So, you do not have any import specially and then here integer parseInt this is
basically is parsing or pre-processing of the value to an integer, this is because the java
reads everything in the form of a string.

So, it is basically convert a string to an integer value. So, that is why the command is
integer.parseInt and it requires the value, that value should get parameter getParameter
basically the method which will read from the HTML. And in that HTML there should
be some tag get a value called the x position and the value should be supplied there in the
HTML file then it will basically parse the HTML and whenever the exposition where
very parameters named it will face and it will take its value and the return to x as an
integer.

Similarly, another value which is parameter name is y position in the applet file at an
HTML file and its read it and then return to y and finally, getParameter msg it will also
read a parameter msg that is there in HTML and return as a string. So, need not parse
into any other type. So, it is simply written it as a msg and finally, drawstring it is same
as earlier it will display the message that will read from the HTML file and it will display
the message at the location x and y the value of x and y also read from the HTML file.
Now let us see the HTML file for this applet, how it should look like.

123
(Refer Slide Time: 22:18)

So, definitely, it is a little bit different than the previous HTML because here we have to
specify the three parameters msg, x position, y position three parameters along with their
three values. Now here we can see the first the code, the applet code is as usual it
basically include the class file, in this case, demonstration_25.class file and this is the
size of the applet in this case 300 as width and then 300 as height.

Now, it read the first parameters called the message, the first parameter that we plan to
read it here as a message the value is here this is a parameter example program. And then
the second parameter namely the x position also we read it here value as 50 and then
third parameter y position that is there is, in this case, is 50. So, these are the values
which can be passed to an applet via an HTML file. So, this is the HTML file for your
program and then we shall able to run this of HTML file we have already created a class
file for this. So, this is the class file, yes class file clear (Refer Time: 23:43) screen clear
fine.

124
(Refer Slide Time: 23:48)

So, now we let us run this an HTML, the name of the HTML file is this one ok.

Now, here you can see we have read the message this is the pro example, it not clear. So,
so these are texts that we have already passed from the HTML, this is a parameter
example program and then the location where it printed is 50. Now again if we change
the value here accordingly it will take the different value and then the same applet will
run, but will different input. for example, not here. So, write the message in capital
HELLO and then the position is 20 and 50, 20 and 50, we have changed it, no need to
compile the program because there is no change in the applet program only the change in
HTML file. So, here you can see we have taken the different message and then we have
printed in a different location, which read from the HTML file itself.

Now, let us see if you run the same program without any extension what will happen?
See applet viewer HTML_25.without HTML. Now lets see if we are able to run it, now
you will not be able to run it this is because it should require the full name of the file to
execute it. So, if you do a partial name of the file then your applet cannot recognize it
and it will not be able to run it. So, you have to be careful when you call your applet
viewer the right file name should be given there. And another thing is that the name of
the HTML file not necessary to be same as the name of the class file that you ambit if
you do it its good, but if you do not do this is not an issue ok.

125
So, there is no problem this is 1, now. So, this is the way you can see how the applet
programming is possible, we have learned only the init() method and the HTML file that
is required to view it and fine. Now let us see one twist is here; that means, is it really
allows the applet viewer is required that it should record the HTML file allows here is an
example you can check it.

(Refer Slide Time: 26:15)

Let us see the program here ok.

(Refer Slide Time: 26:24)

126
Go to the program yeah look at this program, this is a new one program is basically same
as the first program that you have used it, yes and see these are the input section, as
usual, it is there input section. And this is the name of the new java applet, the name is
demonstration_26 the paint method it is they are no unit anything is there very simple
and it will print now will come to the applet.

Now, and here the HTML tag or HTML code that is required to embed this class file is
written here at the bottom. So, you see this is that this one, here the HTML code. So,
sometimes many programmers prefer to write the applet program and at the bottom or at
the end of the same program file they usually embed the HTML code. So, they usually
want to avoid writing both the things in the two different file, rather they save all the
thing in the same file. Let us save this program as demonstration_26.java.

Now, you should compile it. So, when the compilation will take place all the portion
which is written as an applet tag should be ignored because they are under comment. So,
they will compile successfully, for example, in this case, we could compile it. So,
compilation creates your class file demonstration_26.class file and now we see without
embedding it in an HTML file we will be able to run it, to run it we just simply type
demonstration_the java file name that you have given earlier you write it.

Now, here you can see yeah so right now there is just little wait. So, here applet viewer,
we just call the applet viewer for the program demonstration_26.java we did not create
an HTML file for this particular example now let us see whether applet viewer can take
this or not, yeah very nice. So, we can see that applet viewer, take this file as an input
and then successfully executed and it gives the output.

Now so, some sometimes if you want you can avoid this having the two different files as
a.java file as well as the .HTML file and then you can run it. So, it is not magic. The
policy it is here is that both the java and applet viewer, in fact, the runtime interpreter.
So, java program interprets the byte code which is in the class file form and then applet
viewer is also an interpreter who is basically interpreting the HTML code only. So, in
this case, the applet viewer interpreter the demonstration_26.java file and in the process
of interpretation whatever the statements or lines it is they are on the way it is ignorable,
except those are the line which are with HTML tag.

127
So, applet viewer only executes those are the under HTML tag successfully. So, in this
case, the tag applet code demonstration_26.class has been interpreted and then executed.
So, this is the way you can use it this is a shortcut method of course, , but my suggestion
is that you can have the HTML file separate and then.java file separate, create the class
file successfully and use it and enjoy the applet programming more on an applet
programming will be discussed there is many things regarding the applet programming,
it will be discussed in due time.

Thank you very much.

128
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 07
Encapsulation

Today we shall discuss about a very important object oriented concept, it is called
Encapsulation. So, our today’s topic is Encapsulation in Java. As we know the concept of
class is a basic things in any object oriented programming. So, we have to write program
in Java this means that we have to write a set of classes. All classes then can be used to
create objects and this way the object orientation is possible.

So, today we will discuss about the basic concept of class which basically can be
achieved with the concept of object oriented principle called encapsulation, and the
different elements that is possible in a class.

So, first let us clear the concept of class in Java.

(Refer Slide Time: 01:31)

As I told you that class is a basic building blocks in any Java program that mean using
the class you can write the entire Java programs.

129
(Refer Slide Time: 01:49)

So, class basically what exactly a class is? So, a class in fact, is a template; that means, it
is basically gives a framework of an object.

Now, how an object can be described? So, in order to describe an object we need many
elements for that object. So, the elements which are very important in any objects are
called fields, the methods, constructor and sometimes special items called blocks and
also class within a class called the nested class. And another important concept also can
be included in an object is called the interface.

So, mainly there are 6 different items to be incorporated in a class. Now fields and
methods little bit we have familiarity in our last few programs, but other 3 things like
constructors and then interface and everything is not known to us at the moment. So, we
shall on all this thing slowly. In today we will basically discussed or emphasized on field
methods and constructors these 3 things.

130
(Refer Slide Time: 03:29)

So, now a basic structure in its simplest form will look like which is shown here. As we
see in this fragments of the programs is a basically pseudo program not exactly the
program. So, any class can be defined with its own unique name.

So, it is called the class name usually it is given by the user, so user defined name. So
here so this is the name of the class that you have you are going to build, so these are
name. And then it consists of 2 things which is mentioned here as you see a set of it is
called the fields or member elements. All are member elements method also a member
elements the particularly it is called fields and other is called the methods.

So, fields and methods are 2 very important things in any class. A class can consist of 1
or 0 or more methods and 0 or more fields. There is quite possible that a class does not
have any fields also possible that a class does not have any methods, but which is really
not useful is a useless thing without any fields are any methods anyway.

So, logically a class have 0 or more member elements fields and methods. So, fields is
basically simplest of his form is basically reference variables or some primitive variables
that means objects and other name of the other variables that can be define and then
methods are basically the operations which are possible to manipulate all the fields
variables are there. So, these are basically called data in a class and these are basically
called operations in a class. So, these are the 2 things data and operations when they are

131
punched together it is call encapsulation which you have a little bit learn in our previous
lectures.

So, here encapsulation means data and operation are to be put together.

(Refer Slide Time: 05:58)

So, this is a basic structure of the class and let us have a very simple example. Now
suppose a circle, a circle is an object. So, there are number of objects all the objects are
different, because of its own centre location as well as its radius, the 2 circles are 2
objects, they are having either centre location or radius or both are different.

So, such an object can be defined by its own class. So, here is an example how a class of
type circle for you look like this. So, this basically if this is the name of the class a circle
in this case the circle has 2 fields, one is declared as float type the radius r and another 2
fields are also declared as float type x and y namely the coordinates of the centre.

So, here as we see a circle is defined in terms of 2 data, centre location x and y and then
it is radius. So, this basically completes the definition of a circle. However, in this
definition we have not included any method, if we in if we include some methods in it, it
will basically makes a sense. Now let us see how the different method that is possible in
this definition.

132
(Refer Slide Time: 07:42)

So, here the circle class that we have discuss just now has been augmented with 2
methods. The name of the methods as we see here one method is called circumference
another method is called area. This means these are the 2 operations which can work
with if the radius is given to this method. So, they will these 2 methods will be able to
calculate the circumference of the circle using this is a formula and area of the circle
using the standard formula So, here of course, r is in use; however, other 2 variables
mainly x and y is not in use.

So, we can pair some other methods to utilize x, y as well as both all x, y and are there
any others details description of this things will take the program little bit lengthy, we
just now ignore it. And we will discuss a detail usage of all member elements, all fields
in using some other operations or methods. Anyway, so this basically gives one a form of
a class called the Circle having 3 different fields x , y ,r, 2 methods namely
circumference and area. So, this way we can define the object the class namely Circle
here in this case.

133
(Refer Slide Time: 09:15)

Now, let us see what the uses of this class is. Now once you declare a class Circle, we
shall be able to use to declare its objects.

So, suppose this is the definition, suppose this is the definition of your class which we
have already discussed it and then we can use it to create objects. So, for these things we
can create our main class program. So, here is the idea about the main class program we
dip. So, this is the class defining the circle category and here is another class we are
defining which our program is.

So, here we are defining the program. The name of the program is the name of the
program in this case is circle demo 1. So, we have given the name of r 1 and we have
already familiar to the main class declaration by virtue of public static void main String
args. So, this is the usual statement to declare a class as a main class using the main
method, and here you can see we have we have declared one object. We give the name of
the object as c and the new is basically the usual operator who is basically create an
objects of type circle.

So, this is the standard sentence that you should follow to create an object of type in this
case for example, of type class. So, the object namely c is created here, this object c is
created, once c is created we can use its different member elements, namely the different
fields and then also its method.

134
Now here we see the c.x basically implies that it is the element x for the object c likewise
c.y, c.r and the values for this fields has been initialized as 0.0 for x 0.0 for y 5.0 for r.
So, this basically gives an initialization of an objects why are the centre is located 0 0
and having the radius 5. So, this way an object is now created with its value in it. Once
the object is created then we can use its method to do certain operation. For example, in
this case we use c dot circumference that means, for the object c we call the method
circumference; that means, to return the result of its circumference.

So, whenever we call it, it basically use or use this code to calculate the circumference of
a circle whose radius is r. In this case it will calculate the circumference of the circle
whose radius is 5. Similarly, in the next statement it will calculate area of the same circle
c and the result will be printed using System.out.println().

So, this is a one method, this is a one class call the main class who is basically creates an
object of type circle and the name of the object is c and for this object we can access the
different elements ,fields and methods. Methods are basically operations on the data
which is there in that objects. So, this way we can use a create objects. Now with so, in
this example, we have created only 1 objects, but it is quite possible to create the
multiple objects having a class definition ready.

(Refer Slide Time: 13:41)

So, in this example we can see how we can create more than one objects using the same
concept that we have learned just now. So, here if we see c1 and c2 are the 2 objects

135
created a using this concept new and that these are the 2 objects of type circle. And so,
here we see these the initialization of the first circle having centre at 3.0 and 4.0 and
radius 5.0 and this is the initialization of the another circle whose centre is at minus 4.0
minus 8.0 and radius is 10. So, the 2 circles are now built, 2 circles having the 2 centers 2
different radius have been built. So, the 2 circles are created.

Now, once the 2 circles are created, we can call the methods in them. So, for example, as
we see in these 2 statements System.out.println()., we use the circumference method to
return the circumference of the circle c1. In this method we see area of the circle c one in
another statement we use the same thing, but for the circle c2. So, we just now learn
about how the multiple objects in this case 2 objects can be created and all their member
elements can be accessed in from the program.

So, this is the concept about creating multiple objects. And now we will discuss about if
we can include more than one classes in a program .So, our next example is towards
this .So, we will discuss about multiple classes declaration in a program, in a Java
application.

(Refer Slide Time: 15:49)

So, multiple class for example. Already you have learn about the Circle class, how a
Circle class can be created and thereby different objects of it can be used. Now, so this is
a circle, now suppose another objects say is a quadrilateral it or a rectangle just we want
to create it.

136
Now, so this is suppose example of cuboid and it is basically define with 3 parameters
height, width and depth. Now so this is an object like circle right, it has that 3 member
elements and definitely it has its own method. Now let us see how we can define a class
for this kind of object Quadrif (Refer Time: 16:44) here in this case. Now this is the class
definition for this objects and we give the name of this object as a box and as we see the
class Box content 3 data and then it has 2 methods; one is called area and another is
called volume. So, a by means of area method if the width height and depth is given to us
we shall be able to calculates the area, total surface area of the box and given this width
height and depth we will be able to calculate its volume, this is method for calculation.

So, these are the 2 methods and the 3 member 3 fields to define these objects. So, now, 2
different classes are defined. Now this after the definition of these 2 classes. Now let us
see how we can utilize this class definition to in our program.

(Refer Slide Time: 17:54)

Now, here is the program who is basically use more than one class in the program. So,
the name of this class let it be Multiclassdemo we get this is because, it is basically is a
program which use the different classes that we have just notify. And here you see the 2
declaration Circle c =new Circle() this basically creation object whose name is c. In the
next statement, we create another objects called b of type Box. So, the 2 objects are
created, once the 2 objects are created now definitely we have to give the value to this
objects because they are created without any specific value in them.

137
So, we have to initialize objects. So, for the initialization as we see here these are the
statement that basically initialize the circle objects for its x, y and r value in. So, you can
see c dot x implies that it is a x value for the object c like, likewise the object b is
initialized with its 4 different values namely width 3.0 and then height 4.0 and depth 5.0.
So, the objects is now initialize with its member elements data and now we can access
the operations which are defined for each objects in their corresponding classes.

So, here we can see in this 2 statement, we access the 2 methods which are defined in the
class Circle, namely the circumference and area in another statement. We access the
method area, but it is defined for the class box and another is volume also define for the
class Box. So, the operations in each objects are now accessed once they are objects are
created.

And so this way we can utilize the different elements, the different classes which we can
define; one thing is that all the classes that we have define we can store in one program,
one file in this case, for example, the class Circle and we can store in the program file
after this class Circle we can write the program or the quotes for the class Box, they can
be placed one by one and then finally, the main class. So, main class is here Multiclass
demo can be written and all this thing, 3 classes, the class says for the class definition for
Circle class definition for Box. And finally, multiclass demo it is called the main class
who is basically creates objects defined by the different classes can be used. And all this
things can be stored in a file the name of the file should be same as the name of the main
class.

So, in this case MulticlassDemo.java should be the name of the file. So, once all these
things put together and you set the file as MulticlassDemo.java, your program is now
ready and you can compile it and then run it. And then once you run the different result
as per the main method will be executed and you will be able to get the output.

138
(Refer Slide Time: 21:46)

So, this is a concept we have learned about that how we can create the class and how we
can create the different member elements namely the data and operations in it and how
the different classes can be used to instantiate the create objects. And finally, using those
objects how we can solve many problem. In this case we can create a set of class a class
Circles or a set of boxes and for a circle and boxes we can create the different
geometrical parameters like area volume pay then circumference accepted etcetera.

Now, so here are few things that are you want to highlights it. So, there are 3 classes in
the last example that we have considered, out of these 3 classes 1 class is called the main
class, which we have told many time. So, main class is because it includes the main
methods. So, if you want to run a program successfully, then what about the classes are
there they should be there and there should be one class called the main class which
includes the main method. And of course, in one program only one main class that mean
one class with main method should be, you cannot have 2 classes and in both the classes
again main method it is not allowable.

So, you cannot do that and the main class method should be safe as the same name of the
main class name, but extension should be dot Java which is already there. Now if you
have any program without any main class. That means, there is no main method in any
class then this program cannot be compiled.

139
So, execution is also not possible, if it is not compiled execution is no I am in question,
so that is not possible. So, you should have one program one file; the main class should
be there this means that should include the main method.

(Refer Slide Time: 23:42)

Now, here is an example say suppose you have included 2 classes Circle and then Box
and then save them as you say tem tem dot test.Java. If you want to compile it your
compilation error will be the output. So, you will not be able to compile it successfully
because in this file test.java, there is no main class. So, this is one important thing that
you should consider. For example, if you compile this it will easily give this kind of error
on your terminal.

So, in that compilation error; that means, a class file is not created.

140
(Refer Slide Time: 24:22)

Now, so we have discussed about class declaration, the different elements in it; namely
data and operations. There are many more operations we can include; in fact, there is no
limit. There is no limit on how many data should be put into a class, there is also no
limitation how many method should be placed there inside a class but depends on as per
your requirement you should include as many data as many methods in the in a class.

Now, let us extend the definition of class circle little bit in a detailed manner. Now
whatever the discussion that we have discussed here in this, I just want to include one
more method all these things you have already learn previously.

Now, in this class declaration I use one more method in it, the name of the method is set
Circle and you see in this method it has 3 parameters. In all the method that we have
discussed there is no parameters in them, only they are name of the methods without any
arguments, but here we declare 3 parameters namely a, b and c. Now these 3 parameters
as you see from the quote this basically the value a will be assigned to x that mean x, y
and z will be initialized by these 2 3 variables.

So, setcircle is in fact, is basically to initialize the object initialize an object circle. And
here is an example so this example if you see these the main class, the name of the main
class is the CircleDemo3 and this create 2 objects c1 and c2 and using the setCircle we
can initialize this c1 and c2 objects as the x y 3.0, 4.0 and radius 5 point zero for the first

141
and minus 4.0, 8.0 and 10.0 for the second and all this things are as usual. Now you can
see, the setCircle method is basically initialization attempt.

Now, this initialization in Java is possible in more pragmatic way. We will discuss about
are the different way this object can an object can be initialized the concept is call
constructors. So, we will quickly discuss about the concept constructor now.

(Refer Slide Time: 27:01)

So, constructor is basically the concept of automatic initialization and the idea it is that
whenever an object is created this method will be called automatically. So, it is way no
need to call it explicitly. For example, the method circumference the area we have to call
it explicitly for an object, but this method whenever object is created automatically it will
be executed.

142
(Refer Slide Time: 27:22)

And so, for the constructor is concerned, it has few specific things to be considered.

So the name of the constructor should be same as the name of the main class method or
the class right. If you want to declare a constructor to initialize an object of a class the
name of the constructor should be same as the name of the class and it should not have
any return type. And constructor is basically used to initialize the internal member
elements in it.

(Refer Slide Time: 27:56)

143
Now, let us have an example and this is a simple example as we see this is a class Circle
as we have already created earlier and this is a constructor write it basically similar to the
setCircle but the method code is like this one. So, this is basically setCircle we have to
call it explicitly but this method whenever it is equal we do not have to call it.

Now, let us see how we can use it in our program and this is a one program who is
basically use the constructor and here you can see here. So here we can create an object c
1, c 2 and when we call it then we call who is the parameters. So, 3.0, 4.0, 5.0 are the
parameters which has been used to call it; that means, the circle object is created, we
pass the values, the constructor will take this value and pass it to the c1 objects and then
c1 will be initialized.

So, this is the initialization and one more thing there is little bit mistakes in the typing,
so, all these are the capital C, you should note it anyway. So, these are Circle class for
example, here is a capital is a typing mistake anyway. So, the objects are created using
the constructor in this case and the rest of the things are the previously discuss concept as
we have already have.

(Refer Slide Time: 29:25)

Now, so the constructor that we have created and now there is a special use of particular
keyword is called this keyword. We just want to use it this is a special keyword to
resolve certain name collision.

144
(Refer Slide Time: 29:33)

I can discuss about an example, so that I can discuss it. So, in this case a this is the
simple things that we have discuss setCircle and here is the constructor that we have
already discussed earlier. And suppose this constructor is defined, who is the parameter
like this one. Now this means that the x value will go to this x value, but this x and this x
should be should not be the same actually.

So, the in order to make it distinguish, so what we can this that we can use this keyword.
So, this dot it is means that this x, here this dot y means that this y and this dot r means
that this r. So, by means of using this we can specific specifically mentioned that this is
the member elements belong to this class itself.

So, this means it is belong to this class the current class. So, this way we can use it.

145
(Refer Slide Time: 30:27)

Now, so then rest of things are the same and the concept is called multiple construct. So,
we have discussed about the constructor concept, which basically used to automatically
initialize an objects. Now we will discuss that in a class even you can define more than
one constructor. So, more than one constructor is basically helps the Java programmer to
initialize an objects in a multiple ways. This concept is called the multiple constructor or
called the constructor overloading.

(Refer Slide Time: 30:58)

146
Now, let us have a quick example about the constructor overloading concept. In this let
us look at this program. Here we can see this is a one constructor we have defined; this is
a one constructor we have defined. So, constructor number 1 and this constructor has the
3 input as a parameter and initialize the elements in the object like this way and in this
constructor we only pass the radius r, but others r default value are 0 0. So, this is the
second way of constructor and here we initialize in terms of another objects c. So, this is
a way of constructor 3 and here it is also default constructor without any argument v.

So, this means that an object can be created without passing any value, with only one
value who is passing an object of types Circle itself and sometimes passing 3 different
value. So, these are the 3 different way; 4 different way rather the way an object can be
initialized. Now here is an example you can see, how you use multiple constructor to
initialize the objects in different way.

So, this is the initialization of objects passing 3 values to it. Their initialization using
passing only one as a radius and these basically if c1 is known this one; so this mean c3
and c1 are basically the 2 objects having the different or same member elements called x,
y and r and here is the c4 is a another object initialize creation without with a default
value default constructor; that means, all values are 0 0 and radius is 1 in this case.

Now, we can see how using the constructor or the overloading constructor concept, we
can initialize the object in a different way. So, this concept is called the constructor
overloading and then all the different object can be accessed their methods can be
accessed as usual in the previous example that we have discussed about it. So, this is a
concept of constructor overloading.

147
(Refer Slide Time: 33:11)

And there is again one important use of the keyword this. I just want to discuss this with
an example.

(Refer Slide Time: 33:18)

So, you can see this example here. So, this constructor can be used to reference the
method itself as I told you. For example, this is the constructor Circle that we have
discussed Circle and we pass this x and y. We have already learned about that this dot x
equals to x and everything like that.

148
Now, there are few more use of these which is highlighted here illustrated here, I will
discuss about. Now here if you see this and then the input parameter that mean this in
this case the constructor of this class. So, here basically constructor of discussing the first
constructor in this constructor; and we call this constructor with the value this 0 0 and r
but it takes only input as r as a constructor. So, this constructor Circle will called which
in turn, call this constructor to initialize it in terms of 3 different values.

Similarly, this is another constructor which use again this operator here these. And then
it basically, takes the value from this Circle c and initialized this as this one and this is
another example by is a default constructor without passing any parameter this one.

So, this is another example of this. So, this is basically use for the 2 purpose to resolve
the name space; that means, in the same name or variable if it is used then by using this
dot the we can, so resolve that who which name basically it implies. So, this is the idea
about the constructor and multiple constructor rather.

(Refer Slide Time: 34:58)

Obviously there are few more questions that will be discuss in our next class. So, we
have mention earlier that Java is most simple language. So, why it is simple compared to
other languages like and then another thing is that there are many detail things is things
need to be learned prior to experience our good I mean a programming. So, we will
discuss about the specific some few important things in Java, which needs to be learned
very carefully. So, in our next lecture we should plan it.

149
Thank you very much.

150
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 08
Demonstration – III

So, in the last module, you have learned about encapsulation. Encapsulation, in fact, is a
very important concept is a very important object-oriented paradigm. So, after learning
the basic concept of encapsulation so, today we have planned a demo where we learn
about different aspects of encapsulation.

(Refer Slide Time: 00:39)

So, our today’s demonstration includes how we can create a class and then for a class,
how the different objects can be created and then how we can add many methods in a
class so, that a class can take it completes form.

An important concept in encapsulation which is very essential for any program is that
automatic object initialization. So, this concept is achieved in Java by means of a
constructor. So, concept of the constructor will be demonstrated and also we will discuss
constructor overloading. So, it is one part of the polymorphism in java concept so that
many constructors can be planned, so that, an object can be initialized in a different ways
and there are some concept that is very much used to resolve the certain collision, it is
called the namespace collision resolution.

151
So, this is achieved by means of a special java keyword call the; this. So, we shall learn
about this in this lecture. So, let us have the demo. So, first, we will discuss how we can
create a class right. We will discuss a program very small program; let us have a very
small program.

(Refer Slide Time: 02:05)

In our theoretical discussion, we have discussed one class called the circle. So, here we
can see this is the; where is the highlighter. So, here we see we declare the class Circle
here.

So, this class Circle has 3 data namely x, y and r all three data’s are declared as double.
In addition to this data also this class has two methods; one is circumference and another
is the area. So, the two methods are defined here. So, this completes the definition of a
class called the circle. Now, once this class is declared you can keep this class in a
separate file or in the same file where the main class will include. Now here in the
following, we discuss the main class which is saved in the same file. The name of the
main class, in this case, is demonstration 31. Now in this class, you see how we can
create an object of the class type c circle.

So, we create an object the name of the objective c and to create an object, you can note
it the new operator which is used here. So, new and then again Circle and then within the
parentheses, it is basically the general syntax to declare an object. So, with this
statement, we declare an object called the c the object is created; however, the different

152
data that is there for this object is yet to be initialized. So, in the following three
statements we initialize the members x, y, and r with the values 0.0, 0.0 and 5.0.

So, this completes the creation of an object, in this case, the name of the objective is c.
Now once this object is created, we can access any value in this object. So, in the next
statement, we just painting the circumference of the Circle that we have created. Now in
order to access the method circumference, you note that we use c.circumference. So, this
means that we call the method circumference of the object c. In the next statement again,
we call the method area of the object c. This means in this statement, we shall be able to
print the area of the Circle which we have just now created

Now, let us have the demo. We will compile we will save this program as here the name
of the main class is Demonstration_31. We should save this file as the
Demonstration_31.java and then we can compile using java of c. So, let us see the
compilation javac demonstration ok.

(Refer Slide Time: 05:27)

So, we just compile it as there is no error. So, the compilation is successful, we can run
this program using the java comment java is an interpreter. So, run this program and you
see running this program and then circumference here in the Circle that is calculated as
39.4159 and the area is calculated 75.

153
Now, we have learned about how encapsulation is possible here in the form of
encapsulation, we create a class Circle and for this class, we created an object. Now here
the question is arisen that whether we can create only one object in one program or many
objects in a program. The answer is that multiple objects can be created for one class
even multiple objects can be created for other classes also many classes also.

Now, in our next demonstration, we will see how for the same class say Circle the
multiple circles can be created and let us have the demo here.

(Refer Slide Time: 06:41)

Again we use the same declaration of the Circle class here. It is as usual in the earlier
one. Now only we change the main program main class. So, name this main class as
Demonstration_32. Now here we can see, we have created two objects c1 and c2. In the
earlier example, we have created only one object, here we have created two objects and
for these two objects c 1 and c 2. We initialize its data values namely for the first object
x y and r are initializes three 3.0, 4.0, 5.0.

154
(Refer Slide Time: 07:19)

Whereas, for the second object c 2, we initiated the same set of values with -4.0, -8.0,
10.0. Thus two objects are created and their data are also initialized.

Now, in the next 4 statements, we see how we can access the different methods in these
two objects namely circumference and its area. So, it is the same as the earlier program
accept that for two different objects we have used it. Now let us have the demo for this.
So, in this case, two objects are created and you will be able to get the values of the two
objects here. So, the same process we can compile it and then we can run it. So, now, we
can see the two different objects and as the objects are the different their area and then
circumference as the printed area also different.

So, now we have understood how for a class many objects can be created. In this case,
we have considered to their may be a large number of objects of the same class can be
created. Now, in our next demonstration is that whether one program can include more
than one classes or not.

155
(Refer Slide Time: 08:37)

So, this demonstration includes the same. Now here we include one class name, the
Circle which has the same definition as earlier. In addition to this class, we declare one
more class the name of this class which has been given is called the Box. This class Box
has 3 data field, width, height, and depth. In addition to these 3 fields, it has also 3 2
methods namely area and volume.

You note that the method area which is defined in class Box is totally different the
method which is defined for the class circle. So, the two methods are defined in two
classes, but they are different; they are not the same which we have defined in a different
way.

156
(Refer Slide Time: 09:29)

On the other hand, circumference is a unique method in the class Circle where is the
volume is also a unique method in the class Box. So, this way we create two classes
namely Circle and box, we can save all these two classes in the same file as the main
class. Now let us have the look of the main class, we give the name of the main class as
Demonstration_33. This is the main class which includes the main method and now you
see that in this main method, we create two objects one object of the type class Circle
another object of the type class box. So, the two objects c small c and small b are created
here.

Now, again as it is as it was in the case of the circle, we initialize the value. Here also the
objects that we have created to initialize their values. So, here in the first statement, we
create we initialize the value of the Circle objects with 3.0, 4.0 and 5.0 whereas, for the
Box object we initialize the value of width height and depth as the values 3.0, 4.0, 5.0.
So, this completes the creation of two different types of objects of two different classes.

Now, in the next four statements, we can access the different methods. As we have seen
here for the Circle c, we access the area and circumference and for the Box b we access
the area and volume. Now let us have the execution of this program, we will be able to
see that the two objects they are defined in terms of their classes and then they can access
by the main method. So, now, we can see that for the first two printouts is basically the

157
display. Circle circumference and area and next two output is for the Box area of the Box
and volume of the Box

Now, we have understood about how many classes can be created. It is not necessary that
all the classes should be maintained in the same file in the main class. We will discuss
the organization of the classes in your in our program that will be discussed in due time
not now. So, now, let us see where we can see when we create an object. So, it is our
responsibility to initialize. The objects initialization of an object means initialization of
all the member elements that belong to the object. For example, for the Circle x y r for
the Box width height and depth, we have to the initialization, but this initialization as we
have done. In the last few examples, initialization is a little bit tedious because we have
to do it forcefully anyway, but the initialization can be done more sophisticated way in
our next program. We will see how the initialization of the objects can be done in an
easy way.

(Refer Slide Time: 12:49)

So, here is one example a 3.4 right let us see. So, now, we have declared here one,
another class Point it has two member elements x and y declared as an integer. It does
not have any method in this case. Anyway, we want to discuss how this x y value can be
initialized. Now here if you see, this is the usual procedure that we can create an object
of type class and for this thing, we can initialize the value from the main program. This is
a usual procedure that you have to learn earlier apart from this process.

158
Now, we will discuss how we can initialize by calling some methods. Now so, do to do
this thing we have to declare a method in the class Point itself. Now let us see the next
class 3.5 as a demo, we can see the class Point is little bit redefined with another method.

(Refer Slide Time: 13:41)

The name of the method which we have included here set point. The setPoint() has been
planned to initialize its value. So, here example we can see the setPoint() method has the
2 initialization statement x equals to 10 and y equals to 10.

Now, come to your creation of an object. Now we create this object by the main class
here. The name of the main class is Demonstration_35 and we have declared one
variable distance ok. It will be it not useful here in this context anyway, but here see we
create an object p of class Point is the next statement here and then we call the setPoint()
method is basically initialize the values for the object p and as you know by means of
initialization one method setPoint(), it will initialize as x equals 10 and y equals to 10.

Now, in the next two statements if we can print the value of the x and y of the object p, it
will be printed like this. Now let us run this program.

159
(Refer Slide Time: 14:59)

We are now executing this program. The program that Demonstration_35 which
basically includes the Point class declaration and then the setPoint() the method their and
then we will create an object of the type.java. So, the object the program is now
successfully compiled, we just going to run it 31.5; ok fine.

So, let us see here. So, here we can see the object is created and we did not do any
initialization in the main method. We did the initialization via the setPoint() method and
the initialization initiation here x equals to 10 and y equals to 10. Now here we can see
that initialization this method, but how at this method always initialize only with certain
initialization. Here, for example, x equals to 10 y equals to 10. This means that if we
create any other objects, it will and we call the setPoint() method for initially, we always
initialize with the same 10. So, this is not good and not desirable.

Now we will have a good method that how the installation object can be done with the
different data values. So, in that case, we have to again rewrite this function this method
using passing argument. Now here is an example, we just slightly change this class
declaration and setPoint() method also passing two values a and b here a and b are the
two values to be passed to this method. So, that a can be used to initialize the value of x
the and b can be used to initialize the value of y and the rest of the program is same as
earlier one, but only the difference you can see when we call this setPoint() we pass

160
1520; that means, in this case, the objective p which we have created it can be initialized
with its x value as 15 and y value as 20.

Now, let us run this program and then have a quick demo. So, 3.6, right. Now let us run
this and we will see the object data member will be printed as 1520. Now let us come to
the program, we can call this method or we can create another object say p 1 and p 2. We
are creating two objects p 1 and p 2 here right; the p 1 and p 2 ok.

(Refer Slide Time: 17:47)

Again setPoint() we just on keep it. One another p2, another say 0 and 0 p1 p2 0 p1 and
p2 and 0 0.

So, we create two object one is 15 and 20 as the value of x and y while another is 0,0.
Now again we can print it just two statements. So, we can print the values of two objects
here right for the first one is p 1.x p1.y p2.x p2.y right. Now let us save this program.
Now here we have created two objects and the two objects are initialized with their own
values and then we use this main method to print their values by which is at. Now we can
see that the two objects are created and they have in been initialized by their own values
by means of setPoint() method

Now, here is the one idea about we have to explicitly initialize the object by means of
declaring and defining the method.

161
(Refer Slide Time: 18:53)

In java, unique features are available which basically help java programmer to
automatically initialize the objects and that at the time when the object is created itself.
Now this concept the automatic initialization at the time of creating an object is called a
constructor. In our next example, we will see how the automatic object initialization
using the concept of a constructor is possible.

Now, let us have the program here not this program; go to the program number 3.8.

(Refer Slide Time: 19:39)

162
So, let us have a simple program which basically helps to automatically create the
objects and then initialize it. Now let us have the program here. Now the class again we
can continue our this demonstration with the class Circle this class Circle has the 3
member elements x y r two methods circumference and area.

Now, we declare one method. This is a new method that we have added here in this class
the name of this method. You see the is the same as the name of the class. This is a
unique thing here the name of the method is the same as the name of the class and also
you can note in this case this method does not have any return type. So, this is called a
constructor which basically has the same name as the name of the class itself and it
should not have any return type

Now, here the name of the constructor is there for Circle and this constructor is defined
with 3 arguments. All these three arguments are of type double a b and c here. Basically,
a is the argument which will be passed to the value x, b is another argument whose value
will be passed to y and c is another argument whose value will be passed to r. This
means that if we can create an object passing 3 values and these three values will be used
to initialize its member element. Now let us have the main class here after defining the
Circle we can initialize the objects now here we see at the time of creating the object.

So, we are creating the object using the new operator here. Now in the first creation, we
create the object c 1 and we passed 3 values 3.0, 4.0, 5.0. This many means that
constructor, it will call the method Circle which is the constructor method and pass this
value to the Circle objects c 1. Similarly, c2 objects will be initialized. After the
initiation is over, the method will be accessed and then the method will print the different
values according to the calculation or definition of the method.

Now, let us have the execution is the same as earlier. It is no different so far, the
compilation execution is concerned; however, from the result point of view, it is a more
sophisticated way of initialization. So, we have created the object at that time we have
initialized the object at the time of creating the objects and then this is by means of
constructor this concept is called the constructor as I told you.

163
(Refer Slide Time: 22:39)

Now, the constructor has its more dimension. In the sense that it also gives a lot of
flexibility to a programmer to initialize an object in a different way. Now if we if you
want to initialize the object in a different way this then you have to define. So, many
constructors for your own requirement Now this concept is called the constructor
overloading, now here again let us come to the discussion of the class Circle in the last
example we have discussed how the automatic initialization by means of a constructor
with three arguments we have defined it.

Now, in addition to this, we want to define another way of initializing. Here in the next
constructor that we have declared. Here if you see, this constructor has only one
argument double c and the constructor is defined like this if we call a constructor with
one argument, then it will initialize their member elements with x equals to 0 y equals to
0 and r equals to 0 as for this definition. That means if we create an object passing only 1
argument, then the java runtime compiler will automatically understand that this
constructor should be invoked.

If we create an object passing 3 arguments, then the first constructor will be called. Now
here again you see the third constructor that we have defined here. It is a little bit
different; here we can pass an argument which is the object itself that is quite possible.
So, here the Circle c another object which has been passed. if we passed it this means
that the new object that will be created having the same data member as the Circle c

164
here. So, this is the one constructor; that means, a duplicate one object can be created a
duplicate object in the sense that they are different objects; however, having same data
values.

Another way is called the default constructor. If you define a constructor without passing
an argument,t then it is called the default constructor.

(Refer Slide Time: 24:43)

So, in this case, the last constructor the fourth constructor in the series is called the
default constructor. Here the default constructor means that x equals to 0.0, y equals to
0.0, r equals to 0.0. Now let us have the main program. So, the main program is defined
here by means of main class demonstration_39. Now here we see we have created 4
objects and each object is created to with their own constructor.

So, the first object is created with the first constructor second object with the second
constructor and third object with the third constructor and finally, this one here ok. So,
so, here if you see the c3 and c1 when we create the object c3 we pass the c1 c1 which is
a which is an object of the class Circle as for the third constructor declaration. And the
rest of the things are basically printing the different parameters area and circumference
for the four Circle that we have created and definitely c1 and c1 c3 should give the same
result. Now let us have the Demonstration. So, let us have the quick demo, here we are
overloading constructor now. So, all 4 objects are created automatically and the objects

165
are created at the time of creation of at the time of creating the object; I mean declaration
and passing the values.

So, this is about the overloading constructors. Now there are a few more important and
interesting facts about this class and then object constructor.

(Refer Slide Time: 26:31)

We will just want to discuss quickly one concept it is called this keyword. Now this
keyword concept can be understood very easily if we follow this example. Now let us
consider the declaration of one class call the student. Here, this class has four member
elements. Here integer roll number name and course as the String type and then key as
the float.

Now, here again, we see the this is the constructor declaration, roll number, name, String
course and it. Now here you can note the arguments that we have passed they have their
name and in this case, the name of the data members are also the same. Now if we try to
initialize then definitely. So, for roll number equals to roll number, then this is not the
correct similarly name equals to name it is also a little bit ambiguous. So, what you can
do is that we can define it by means of this one. So, this.roll number indicates that this
roll number belongs to this class member whereas, only roll number is the argument that
has been passed similarly this.name specify this the name members of the class Student
and this.course the name member of the class course.

166
Now so now, if we run this one we will see exactly how we the next part will discuss
later on. Let us see how we can use it. So, this is basically this keyword which basically
helps to resolve the namespace collision. So, in this case, roll number name and course is
collided with the data member it is there. So, in order to resolve it, we can use this
keyword. So, here we have used it and then we passed it.

Now, you can see the first time when the object is created the first object to keep Java
0.0 and now let us come to another way. Now, this point let us come to the special use of
this keyword in another 3.11 let us run the 3.11 demo.

(Refer Slide Time: 28:39)

Now we will just discuss more important thing here. Now in the context of Circle again
this keyword can be understood very precisely. So, here again, constructor, we can see
the constructor has been defined with x y r which have the same name as the member
element and we resolve it by using this it is at the same thing applies to the other also.

So, if we want to resolve some name which belongs to the same class with another
variable. So, we should use this. So, this is the one use of this keyword in java program.
now there is another use of this program in the java keyword to understand these things
let us have a simple program; let us have the program 3.12.

167
(Refer Slide Time: 29:23)

Now, here we can see that this can be used to have some other advantages see. Here let
us have program very simple one, it is very easy to understand. A is the class which
declared here and it has one method m another method n. The method m will simply
print hello m, n also will print simply one String hello n.

Now, we if we want to access the same method in some other method, then definitely we
have only learned that in order to access a method we should create an object. But
whenever we are declaring a method or defining a method there is no question of
creating any object. Now if the objects belong to the same; that means, if you want to
access the method which is in the same class, then we can resolve it by specifying this.m.
For example, in the method void n, we call the method m which is defined in this class
itself.

So, in order to resolve it, we used the this.m this means that void n whenever we call for
a new object created here for example, A then this will call the method m as well as
method n. So, this so, so, when a.n; that means, we call the method n; it will print hello n
and then it will print that hello m. Now let us have the quick execution of this program
so, that we can understand about this one.

168
(Refer Slide Time: 30:53)

So, this method is used to refer to one method which belongs to the same class without
creating an object. Now, this is the demonstration execution run of the program that we
have discussed now ok.

We can understand. So, that the method m has been called from via n method which is
defined now let us have another quick example of this method. It has many purposes that
can be used who you want to give another.

(Refer Slide Time: 31:29)

169
So, this is the one method you see. So, class A is declared and A is the constructor go to
the constructor definition there a constructor is there fine. We are clearing the A
constructor; Now, here, the constructor there are two constructors right the first
constructor ok. Let us come to the second constructor what is the second constructor we
define the second constructor by means of passing an argument then type integer. So,
this means it will like this one right. Now here one default constructor which define who
is basically initialized by a default value say 5.

But that installation calling by the one already defined constructor namely A intakes. So,
if you want to call any constructor within another constructor, then you can use this and
then specifying the parameter values that you want to have now let us have the execution
of this program. So, this basically calls a constructor in a constructor and this constructor
is basically a nesting type of calling it is it is also part of the overloading constructor. So,
execution is there. So, you can see how the whenever we create an object here in this
statement a equals to new A. We call the default constructor when the first constructor
whenever the first constructor is called it basically initialize the member elements with
value 5. We have no member actually, the value is 5 is passed to the class object and
then it prints hello a using this value x.

So, basically, it basically prints as 5. So, this is the way. Now let us have the last day
demo it is more interesting to understand.

(Refer Slide Time: 33:21)

170
So, the last demo, it will be easier to understand. Now again Circle class. We create the
one constructor is basically using 3 parameters. Now, this constructor then can be used to
define another constructor by means of this the methods. So, for example, the second one
this we call the same constructor here by using the this and passing 0.0, 0.0 r similar is
the second constructor we use this c.x c.y c.r. Here this and all these this basically
indicates the one privilege constructor which is which has the three parameters and
automatically it called them.

So, this way it basically has a little bit change in the similar program that we have
discussed earlier that these are the use of this operator. So, we have discussed constructor
overloading and I just last things I just want to mention. So, what the constructor
overloading is concerned to constructors can be treated as different; if they are different
in terms of the argument number of arguments and the type of arguments. So, that is only
things are there that you can already realize about it and if you can go through the all
examples, then you will be able to understand that all three constructors or whatever the
constructors they are different because of the different argument that we have passed ok.
So, this concludes our demonstration on in encapsulation.

Thank you very much.

171
Programming In Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 09
Java Programming Insights

So, let us learn in this lecture few detailed things in java. So, there are many things
which we have assume that whenever you have to write java program, we have to follow
it. But now we are in a position to learn about why we should follow so many things in
java programming. So, it basically makes a little bit easy to understand the different
concept in java. So, first is the main method. So, main method looks very cryptic
compared to the main method as we have learnt in the C programming. It has many
things in it.

(Refer Slide Time: 00:53)

Now, we will discuss about the concept of main method. Now before going to have this
discussion, here just I want to start with one another example and the name of the
example is here if you see, we create one class call the Calculator. This basically
calculates for any value i in it and the results will be returned and store into the value x.
And here if you see we use another method, but this method we have not defined
anywhere. So, the name of the method is basically square root and here Math dot square

172
root, it indicates that this method belongs to some class; the name of the class in this case
is Math.

Now, this class is where actually now if you see this is one import section that we have.
Now import is very important whenever you want to use some a special class defined
somewhere, then you should use import. So, here actually java dot lang package has been
imported. So, it is basically there is a package where many mathematical calculations
related to the classes and then methods are defined so, this one. So, this basically the
method has been imported here.

So, that we can we can access the square root. So, we do not have to define the square
root method of our own as it is already there in the lang package. So, we can use it. So,
this is basically one method that is basically already library method we can say. Now this
is a class declaration and the name of the class is Calculator, it is not a main class. Now
here Example is the main class in our case because it contains the main method here.

So, if you see the main method it has many things these are the three things are prior to
that public static void. Now we should know exactly what it is the implications of all this
naming that public, what is the public? Why is static? ,the void and everything and
further also you see in this there is an argument; argument is like this. So, the first thing
is called the type; that means, the name of the argument is this one which is an array
actually.

So, it is an array of type the type is called the String. So, it is gone the array of strings.
Now Strings is basically a class. This class is defined in again java. lang. So, these are
the 3 few things that is very important public static void and then String args and
everything and rest of the things are very simple. Here we can see the Calculator class of
the class we have already declared and for this class we create an object and the name of
the object is a. And for this object we initialize its member element the value i as 20 and
then finally, we use this objects and then for this object we print a.x where x basically
store the square root value of i.

So, it is square root of a.i that mean in this case a.i is 20 is 20. So, if you run this
program. So, this will basically print the square root of 20.

173
(Refer Slide Time: 04:24)

Now, here few things as I have already told you import is required because you want to
use some class and some methods in them. So, we have to use the import lang here and
this is the main class which includes the main method.

(Refer Slide Time: 04:41)

Now so, main method is very important concept in java. So, there should be one class
and the one class having main method and that is the main class and this is because as
you see that in a java program there maybe many classes.

174
So, out of this many classes so, they are there should be some indication that the
execution should start from which class. So, if a program file contains a main method,
then it gives a signal to the java runtime environment that we have to start its execution
from the main method. So, out of the many methods right so, the main methods if it is
there in that class so execution will start from invoking this main method and then main
method will call some other method, create some many objects and then do whatever the
operation it is there.

So, main is basically the starting point of your execution and the java runtime can
understand that it is there. If you do not have any main method in any class, then java
runtime environment will not be able to understand that which and then it will give an
error.

(Refer Slide Time: 05:55)

So, this is why the main method is there and there should be a main method.

Now, I will discuss about this main method having many what is called the elements in it
like public static void mean main and all where the String and everything. So, the first
the item that you can say the first what is basically public. It is called the access
modifier. In fact, in java there are many access modifier, 3 different type of access
modifier a one is public, another is private, another is protected.

175
So, in this case it is public and it is always should be public. If you make it private or
some other type, then it will create an error compilation will not be successful. So, this is
the one called the access specifier and the it should be public always. So, this is always
required indicate that public; that means, the main method should be publicly useable.
So, anyone can run a program if you want to restrict that this program should not be
executed by anyone, then you can withdraw this public you can write private, but it is no
use because you have return one program which no one can run it then it is not useful
things right.

So, you should always make the main method as a public and this is a way that public we
can declare. And then the void so, void means you know every method should return
sometime. This is the concept or method or function or operation any operation can have
0 or more input and always return something like.

Now, in some situation it does not return anything, then in that case we should mention
that void. So, in this case as the main method does not return anything because main
method is not called by anyone other than the java runtime environment itself. So, the
main method is not responsible to return to anything from its caller so, that is why it is
void.

So, always this keyword should be specified as the void. So, void is the return type
which should be declared as a void null value actually, it should not return anything in
that sense. And next is static, this is very important. So, some methods you know what
about/above the methods we have discussed earlier say areas, circumference. In order to
call this method, we first create an object and for that object, we call the method for an
c.area or c. circumference like this. That means if you do not create any object, then you
will not be able to access any method in it. Whereas, the main class if you see we usually
do not create any object of this class and then without creating any object of this class,
we want to access its method in which is define in it.

So, that is why if you declare a static, then no object creation is not required necessary
without creating any object we will be able to call this method. So, if a method is
declared static. So, no object is required to be created to access this method for that
object. It will automatically be accessed like.

176
So, here the main class we don’t create any object therefore, the main method should be
accessed without any object creation and that is why the static method to be there. So, we
have understand about why it is a public. Public is an access specifier, static is the
keyword. So, that object instantiation without any we can access this method, void that
main method should return anything.

Next is String args, this is argument. Now, these are the argument that needs to be passed
to a main method. Now this indicates that a variable number of arguments you can pass.
So, that is an array it is there is a point at to array like all the pointer concept is not there
java. So, it base there args is basically and array of any size. Now the size is
automatically define when you run the program, we will discuss about automatic size
declaration of this String args function.

So, here basically the input to the main method of type String and in java you know
everything treat as a string whether integer, it is also consider as a string, a floating value
is also string, any object is also string and then there is a manipulation where the
different objects from can be transferred from string two types say, string to integer
string to float like this one.

So, this is why the concept of argument here the string is declared. So, it is basically
indicates that array of string objects. So, these are the few things are there we have
already used it without knowing what is the reason for that, but this is basically the basic
syntax of the java main method that it should be ok.

177
(Refer Slide Time: 10:59)

(Refer Slide Time: 11:01)

(Refer Slide Time: 11:03)

178
(Refer Slide Time: 11:05)

So, we have declared about public, concept static and then void. And then main method
this one right.

179
(Refer Slide Time: 11:07)

And then String args is basically passing input to its argument in a different way.

(Refer Slide Time: 11:13)

Now, output, we see in the program that output from a program usually displayed on the
screen if you want to display some output on the screen, then we use one method. This
method is called println method or its many variations println has its many variation like
println, print ,printf ,like this one anyway.

So, println is a method. Now this method is again defined somewhere it this method is
defined in the java dot lang package and java dot lang package has one class called the

180
System. In the class, it is defined and in fact, for the System there is an output class and
then in this outputs called the method is defined. So, it is the idea is that the println
method which we used here it is defined here and the println method has again variable
number of arguments as input. Here the argument is basically one string than one value
and then another value.

So, the three arguments are there four arguments the other one string one value another
string and another value. So, 4 arguments are there and so, the println method is
customize to the any arguments actually one argument, no argument, many arguments
whatever it is there. And if you want to use multiple arguments all the arguments should
be separated by plus sign. So, in this case for example, so, this plus this mean this
argument plus this argument plus this argument plus this argument and so on.

So, this is the basic syntax of the System.out.println() and this is the method. As I
already told you defined in see java.lang package, in this java.lang package there is a out
a class variable and this is the type of Printstream and in this Printstream is declared in a
System class. All these things regarding the output system, Printstream and everything
we have planned a detailed discussion when we will discuss about the input output
stream concept. So, they are belong to input output stream.

So, here basically is an output stream actually because System.out.println(); output some
string into screen actually. So, this the concept of the System.out.println() which we have
frequently referred in our earlier example.

181
(Refer Slide Time: 13:43)

The concept is like this and as I told you it has many variation println. Similarly print the
difference between the println and print is that after this output the automatically console
or the cursor will go to the next line, if we use this one and so, cursor will go
automatically to next line. So, that is the concept of println. So, ln stand for next line.
And if you use the print then cursor will not go to the next line, but if you use the print
again force to your cursor to go to the next line, then you use this “\n” it is same as C
printf function.

Now, in addition to this println and print similar to the print f that is we have used in C
program also can be used is the same as printf. So, in that case System.out.printf() and
then format it because you can customize your output to express into integer format,
floating point format and everything. So, in our demo we will discuss about the use of
println ,print and print a format in details. So, the idea about the println method it is there
and now I will just discuss quickly about how we can fit input to our java program. So,
during the execution of the program, how input can be given to the java program? So,
this is called the java runtime data input concept.

182
(Refer Slide Time: 15:21)

Now, here is an example you see the first kind of input that can be given to java program
is called the common line input. So, this program if you look it little bit carefully, you
will be able to understand few more things which you have already learn earlier
something extra here. Now here we have defined one class name; name of the class is the
Echo and this is the main method as usual earlier right

Now, here you will be able to understand that what is the usage of stream args as its
argument. Now purely you can recall if you declare an array, the name of the
array .length return the size of the array. So, here in this example args.length, this is
means this is the string array what the length is. So, this is arg length and then here we
use a for loop; that means, if this loop will roll for all elements in the args array and then
it basically print the arguments that is there in this array; that means, the different array
objects the string type of objects, if it is there it will print it like this.

Now, here again question is that how this elements to the array can be given it to it. Now
here is idea is that during the execution of this program, we can give the output to this
one. For example, suppose the name of this class is Echo.java, it has been compile and
then name of the compile class is Echo.class. So, we can run this Echo.class from your
directory and then while you run this earlier that java Echo. Echo, then in addition to this
java Echo. You can give anything you can type anything. For example, here we can run

183
this program Echo and then giving three input hi, Debasis Samanta then it basically take
the three string object.

Now, this first string object will go to the first location of the arguments array that is
zeroth location. These will go to the second location of the array and then this will third.
So, in this case the so zero zeroth location first location and second location and here the
args array will be loaded with three strings hi Debassis and Samanta. They will be stored
in the three different array locations and then size of the array is 3 , array index from 0 to
2.

So, args 0 we will store hi args1 will store Debasis and args 2 will store Samanta. So,
now you come to this for loop, then this for loop start from i zero and then for the first
print first System.out.print() will args 0 and then the space then go to the second i equals
to 1, it will print args 1 then space, then second it will print args 2 and send and then
finally, the new line n; you will basically go to the next line like.

So, this way if you run this program, it basically gives output which is from here. So,
here we can understand that how we can pass input to the array while it is running.

(Refer Slide Time: 19:14)

Now, again the same program if you run with different input for example, say this is the
program again same the input is like 1, 2, 3, 4, 5, 6, 7. So, here you can see the length is
seven and then starting element is at args 0 and the last element is arg 6 and this loop if

184
run, then it will print all the elements one by one as this one. So, this is output that it will
print.

Now, if you run this program without any input simple. The earlier way you have run it,
then the length will be 0 args dot length will be 0 and then this loop will not roll and it
will not give any print statement to be executed. So, this is the concept the common line
input to java and it is very useful one concept in java for the java programmer that they
can use it.

(Refer Slide Time: 20:08)

Now, let us see how we can practice another simple program you can understand it very
quickly. Here is another is a common line input concept and this is the same thing as we
have earlier. It will print the message from this print statement; it will print args 0 and
this one.

Now, if you run this program run this program with different output it will look likes.
For example, if you run this program say name user argument, then Debasis so, it will
just print how Debasis, “How are You”. So, this way you can just take the input and then
in your method in your operation belongs to that class all the input can be used for your
own purpose that input can be string that input can be number, that input can be any
values whatever it is there.

185
But in case of String args whatever the input you give, it will store in the form of a string
type objects and latter on you will just convert it. Regarding this conversion, we have
some discussion; we will discuss about it.

(Refer Slide Time: 21:11)

Here is an example, suppose as I told you, input is in the type String class; string objects
right and then if it is an input integer then how we can get the integer value from it. So,
these an example here. So, lets see this example again Calculator class that we have
discussed earlier and then we create an object a of the calculator class like .

Now, the args 0, if we pass an input as an integer then args 0 will take as an input and
then this method Integer.parseint() it is declared in again lang function lang packages.
So, Integer.parseint() basically, it will take an string objects as an input and parse it and
then after parsing it will return an integer value and then it will store in the a.i. So, here
we can see that arguments that will be passed from the common line as an input will be
passed to the objects value namely i here for a.i. So, the objects will be initialized once
the initialized we will be able to call this. For example, for this object we can call this
math square root function and then this is the syntax right.

So, here basically you can see the difference there. In the similar example which why we
have discussed that we have initialize in the program itself statically, but here we can
pass the value to a member elements data fields right while the program is execution .So,
during runtime we can pass the input to it. So, this is the concept that is the input to the

186
java program and here if the same program if you run it, then it will execute like here. If
you give the input say five 6, then output it will produce which is shown here.

So, so this is the way the input irrespective of its type can be passed by means of while
your invoking the program. So, here the think that during first invocation; that means,
running the program you have to pass all the input that is required for your program.
Now, there are more better way that instead of giving the input at the very beginning of
the execution, we can give the input at the time of the execution.

(Refer Slide Time: 23:39)

So, there are few more other way of doing this things. So, for this things a very good
utility program is there. This is called the Scanner class. The Scanner class is defined in a
package. It is also defined in package called util package. java dot util package and in
that package one class call the Scanner class.

So, this basically you have to import it; if you want to use this Scanner class and then
here is an example giving that how we can take the input; it is not a common line input.
So, it can take the input point the program is in execution not just the before the starting
of the execution. So, here this method if you look at this here. So, this scanner class has a
constructor the Scanner and this constructor is initialized by an object call the System dot
in as a parameter.

187
So, it is a default standard the System.in you have to specify because in the System one
class dot in is a feel and it basically create a Scanner for this one. So, so once you call
this i mean create an object of the Scanner, here the s is the object of type Scanner class
which is basically call this and this s basically is responsible for taking input from your
user. Now here for example, we give a form that enter a number first number.

Now so, the numbers whatever it will be enter from the keyboard. It will be stored into
temporary location; now num1 and num2 we have declared; they are the temporary
variable. It is declared here and then the object that s is basically created earlier is now
ready to take the input from the keyboard. So, here is a syntax that s.nextint(). So,
basically it will read the object as an integer from the keyboard and nextint is basically it
will go on reading one after another. So, it is the nextint. So, as the first time is the first
integer that is type from the keyboard we will read it and then it basically return this
value and in store into the num1

So, num 1 is now initialize at this 1. Similarly it will give prompt that
System.out.println() for the second number and then it is also read from the keyboard
and then number will be returned and store in num2. So, this way using the Scanner
class, we can read two numbers one by one at a time and they can be stored in the two
the temporary location shear. And then finally, they can be manipulated for example, this
will print the sum of the two numbers just we can read by this program.

So, this is the use of the scanner class and here is the one example that you can discuss
about how it is basically execute.

188
(Refer Slide Time: 26:42)

Now, this is the complete discussion of one class actually. Here we use the Scanner. So,
you use this statement that you have to use the special class Scanner and this is the one
example of a class MaximumCalculator which have the main method it is like this. So,
this is the Scanner object we have to create as I told you, if you want to read from the
keyboard.

So, this Scanner object is created and then we can read two numbers one by one using
this nextint as you have already discussed and these two numbers will be stored into
variables a and b and then it will basically print the largest value out of the numbers that
we have print a pay a greater than b or others and then it will print like this. So, these are
the typical print statement to print the value as for the logic; it is there.

So, this is the one example of is an alternative example to the common line argument that
we have discussed here. And so for the things to things are there you have to import it. If
you want to use the Scanner class, then you have to create a Scanner object using this
one and then use this type of methods that Scanner object.nextint to read as many as the
input you want to read it.

Now, definitely you have to mention that when you should stop it, I will tell you one
example so, that you can understand.

189
(Refer Slide Time: 28:09)

This is an example that how it can work it. So, this is the method that we have discussed.
Now in this example we use again Scanner class and using the Scanner class we store a
number of elements read from the keyboard and store into an array. So, is a typically this
is the new way of defining an array. We will discuss about new definition of this array.
So, this array list is already defined in util package and the integer this means array will
store integer type of data and this is the name of the array l.

So, we declare using this a an object call the array object the name of the array object is l
and using this syntax. So, this a very important syntax usually people use whenever they
have to use read list or numbers from the keyboard anyway. So, this is the definition that
the number of elements can be temporarily stored in an array like and then size of the
array will be decided here shortly. Now here Scanner input, we create the new Scanner
object like a s c n r in the last example and for the scanner object we use this input has
nextint; that means, if it has the nextin. So, long basically it will go on reading one by
one until you stop your reading entering the numbers.

So, it basically check that whether user has entered any number or not. If it has entered,
then the same number in an integer format will be add into the l. So, l dot add is a one
add method in the objective l and it basically put into their. So, here we can see using
this concept, we will be able to read a number of objects number of numbers whether or
any type of object share. For example, integer if you not integer is a float type, we can

190
declare the float array whatever it is there. So, the number of objects of different type the
user can specify and then can be read from the keyboard and can be stored here.

In this case we read numbers and then the same numbers can be processed here. For
example, here you see we just simply read each numbers from the array l using the get
method is basically read one number from the array at a time and then because of the
find the total of the all i numbers and this basically calculate average. So, this is an
example this shows that how a set of numbers can we read from the keyboard, can be
stored in an array and then array can be used to process something. For example, here
how to calculate the average here.

So, now let us see if you run this program then ok. How it will give the output it is like
this? So, it basically ask that the enter the input, then you are typing 5, 6, 4 and stop
entering into input you should press control z. So, control z is basically to indicate that
termination of scanning. So, once the terminate, then it will do the program and then it
will print at the average value for a. In this example for example, the input is 5, 6, 4the
average value is 5.

(Refer Slide Time: 31:36)

So, this way if the Scanner input will work their and finally, another method which is
also very useful method regarding this method, we will discuss in details when will
discuss the input output stream in java. So, the method that is there as it is in the same
context just I want to discuss shortly up to. So, is a data input stream and using the data

191
input stream is just like a Scanner class like. So, we can create we can read some input
from the keyboard here is an example just quickly said it. So, this is basically the data
input stream is defined on package io package. So, java.io should be imported.

So, this is why if this is required and we are we are declaring one class or for on its
called the interest calculator. Basically this program will read three values principal
amount, interested and year and it will calculate the interest this one this is the. So,
basically it we have to read three different values of different way amount is floating
point value and year is maybe integer interest in a floating and finally, it will calculate
interest and result will be printed on the screen. So, this is the concept that it is the
program is there.

Now, here you see just how we have written this program. Here we can declare so to
float objects on the principal amount and then rate of interest because they are the float
type a new way of declaring float object, otherwise you can simply declared as a float
type ,double type we have already declared. So, in that case also it can work anyway this
is a new technique. This is the new way of declaring float object in java, you just learn it
later on you will understand many things about creating the objects actually ok.

So, this the is a one way of creating float object and have also declare another variables
call the number of years. It is an integer initialized at 0 and now here you see we declare
one object call in object. This object of type data input stream. This is again like System
dot in we have used in a Scanner class the standard and this data input stream class is
defined in io package. So, we use this and then it basically create an object. So, that it is
ready to read something from the keyboard just like Scanner class there.

Now, here is a tempString is a temporary string whatever it is read from the keyboard or
something, it is read as a string as I told you. So, we will read the string and store in a
temporary called tempString. Now this is prompt that and give the user from that entire
principal amount is basically clear the buffer because whatever the user enters it will
stored into the keyboard buffer. So, System.out.flush basically clean the buffer. So, that
buffer is zero now or null then it basically for the in object that you have created using
data input stream readLine.

So, whatever you type from the keyboard the entire things it will read and then read as a
string. So, it will store in the tempString form and then this tempString will be returned

192
as a float value and this is a function it is there just like integer dot ParseInt here also
Float dot value of tempString. So, it basically scan the string and then its value is
converted into the float and stored as a float object.

So, this is the concept. Similarly rate of interest plus and then read the keyboard buffer
and rate of interest is read here. So, two value one is that principal amount is read and the
rate of interest is from the keyboard. Next the number of years gain the same thing int
read line and here you see we have to convert this into an integer, it will read as a string
and using this conversion we convert this string into the integer object and number of
years is the integer object.

So, the 3 input which we have read here as the principal amount, the rate of interest and
number of years. On the 3 inputs are read from the users, we are now ready to calculate.
Here we calculate the interest total as a float value and this is the formula it is for this is
the simple multiplication. So, the value will be calculated and this value will be printed
on the screen

So, idea it is like this and here is a quick demo so, that you can understand about how it
works like. So, this is a example. Here we can run the program the number of program is
InterestCalculator. So, it will ask user to type it, you will type it and then enter. So, it will
take the value and then finally, it will complete its execution.

So, this is the way you can write about the different input ,output, streaming input. In
fact, to a java program three way the input is possible we have discussed. These are
mainly major way that we can use it. So, regarding other things, we will discussed next
in our next class.

Thank you very much.

193
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture - 10
Demonstration –IV

In the last lecture we have learned about many detailed things about Java Programming
the different return type and input, output and everything. So, today we will have with
some we have some illustration about output and input in Java. And you know input and
output are the two important activities in any Java application.

So, these two things are very important; so we will discuss about how the different way
the output can be and also what are the different procedures; so that you can pass inputs
to a Java program. Now, so far the output is concerned in this illustration in this
demonstration we will discuss about output related to display on the screen that is called
the standard output.

That mean how the different way output can be displayed on the screen. There again
output can be in a different way so that output can be passed to a file, output can be
passed to a network line, output can be passed to a database, which is situated in a
remote location all these things will be discussed later on.

(Refer Slide Time: 01:37)

194
So, now, let us have a quick idea about how the input and output are possible in Java
program. Now we have discussed the different methods which are there in the system
class which defines a Java.lang package; namely the println(), and printf(). So, in our
demonstration, we will discuss the uses of these three methods which are defined in
system class as a System.out class actually more precisely.

And then after this discussion about output, we will have a discussion about the ways the
input is possible to Java program. There are three ways by which a programmer can pass
input to the Java are called the command line argument using the scanner class and using
the data input stream class. So, let us have a demo about these four things now.

(Refer Slide Time: 02:32)

So, the first demo includes; how we can print the value on the screen. Now, this is a
quick demo let us see this is a very simple program. Now we here we declare simple
class the main class is here we do not have any other class in this case because it is a
very simple example. So, the main class is defined here demonstration_for 41.

Now you can see the first two statement System.out.println() 1 2. Now you can guess
what the print it will give. It will definitely print the same 1.println() and then 2.println();
however, it will give the print in the two different lines. So, println() means it will print
the string or any value and then the cursor automatically goes to the next line.

195
So, for the first two print, the cursor automatically goes to the next line. Wherever for the
third print, it will basically cursor goes to the next line. And for the fourth print because
the next third print is only print cursor will not go to the next line. So, it will the cursor
will be there in the third line itself. And similarly for this cursor will remain in the same
line. Now let us have the demo.

(Refer Slide Time: 03:46)

So, that we can understand about the working of this print statement, now you see the
first two print is basically in the two lines. And then second two prints are in the same
line and then cursor basically in the current line actually; where the cursor is blinking
here. Now so this is the idea about it, now let us see I am just adding one more statement
we will see how it will work for you. After the third print writes this again system right
and then enter and then System.out.print() and then \n print \n \n.

Now, \ it is like this not that yes. Now here if you see the third int statement that which is
a fourth print statement rather which basically is a print and then it is just like in C
programming language is a \n rather. So, \n is basically newline character that means it
basically jumps the cursor to the next line. Now you can anticipate what output will be.
So, the first two outputs will be in the two different lines, then the third output also in the
third line and the System.out.println() cursor will automatically move to the next line.
And then the last print statement will be the next line. So, now, let us see the output it is
there we can see it.

196
So, this is the effect of 10 so is the new line character. So, it is the same as c
programming or C++ programming concept actually. So, newline character is also Java
except. So, this way you can see how using print and println() we can display the value
on the screen. Now, this println() can also print more than two statement or two strings
or values. For example, in the last statements say right print 2 plus, we can give a 3.print.

So, basically, we are printing 2 string and the 2 strings are basically mentioned in a
separate way by means of plus this is called the concatenation of string ok. Now you can
see it is like this now any value also can be printed. Now let us declare one value so int x
at the beginning int x equals to 5 5 5. And the last statement let us plus x these.x plus
this.x. Now let us see run compile this program now you can understand what you want
to do is simple x you can get whether it will take or not. Let us see just we face one
problem plus x fine compile. So, this.x is not required here right.

So, we can see it like this on right to we can print any value whatever it is there. Now, in
this case, this is not resolved because here no resolution or no collision that is a this is
not acceptable. So, we can just simply refer and here also we do not have to create an
object because the main method here is static for any static method we in fact, access any
value without any creating object. So, here the x value it is basically accessed here in the
main method without creating an object. So, no this.x is required in this case. So, we can
ok, now, here the little bit printing can be made more configured plus x we can use this
space comma.

So, plus x before ++. Now a little bit more please cls. Now we can run the same program
again we have to compile it because you have to change the program. Ok run, now you
can see. So, using all those things we can customize our format printing on the screen.
So, it is under the control of the programmer. So, you have learn about print and println()
in addition to this print and println() Java also allow to use the printf() function. It is
same as System.out.printf().

197
(Refer Slide Time: 08:55)

And the printf() function is basically the same as the standard printf() in C programming.
As the name printf() it is called the formatted print. That means, we can mention the
format in printing. Again let us have the quick demo of this method this type of use of
the print printf().

(Refer Slide Time: 09:12)

And in this you can see the program here demonstration_42. And we declare one method
the main method in this main method we declare a variable x as 100. And now you see
you use the print f method printing simple integer and to print the value we use

198
percentage d. It is just like a c syntax within double quote whatever you write it will print
as a (Refer Time: 09:46). But the format if you specify then the value for that format
needs to be placed by means of a comma. There is no plus operator like that is there in
print or println(). So, here percentage d this means that x will be printed in the in decimal
format %d stands for the decimal format.

Now, in the second example if we see that we print one value call the Math.P I Math.P I
is defined in Java.lang package in the math class. And P I is a constant is basically pi 22
by c that is 3.1414519. So, this value will be printed. Now, here you can see the format
that we have mentioned to print the value of pi is percentage.2f. This indicates that it will
print after decimal only 2 digits and then before the, whatever the value it is there. So, it
is basically precision up to the 2 number the decimal point.

Now, again we declare another value float and this is 5.2 f we can declare is a floating
point number. Now again we can print this floating point number which has the different
form of percentage.4 if it basically says you can understand what is.mean; it means that
after decimal it will print up to 4 digits and then percentage whatever the value before
the decimal. So, in that case, if we print n so definitely it will print 5.2000. So, there may
after decimal four digits. Now if we assign this value like 0.38 and again if we call if we
print this with different format 0.20.48 you can understand what will do. It will basically
after decimal 4 digits and then before decimal maximum up to 20.

Now, let us run this program then will come to the discussion again ok. So, 4.2 is under
compilation compiling the program is successfully compiled now executed. Now you
can see what are the different output you can give it. So, hope that the output you can
just see the program and little bit output that can be right. Ok, you can see the output and
then format now let us come back to the program again. So, I am just going to little bit
do the changes there. Now let us come to the second statement second print printf()
statement second pass second.

Now, come to this percentage 4.8 right we just print here say for instead of 0.4 we just
point one ok. And say percentage here 2.1 2.1 percentage fine. Now next statement here
is 0.2 after decimal 0.22 and here before decimal if we see the total number 7, but we
want to declare 6. Now let us see what will happen. Now, here, you can see what we got

199
it there. So, is a truncate it now, truncation is basic not truncated. So, 0.25 it is basically
what is the idea about it is basically approximate right. So, right.

So, it basically does not truncate the decimal value it basically takes the highest value
whatever it is there without 3 before decimal it will not be truncated. However, after
decimal, as we have mention 0.2 although there is a 0.3 it has been cast to 0.25. So, there
is a little bit manipulation that the Java runtime in interpreter will do it and then it will
print it. So, now, here I am just want to mention one thing that whenever you use the
print f the formatting matters a lot. And you have to very careful about the formatting;
sometimes it is result may be correct, but because of the wrong format that you have
mentioned you may not display the right output.

So, that needs you very careful about while you are using print f. If you do not use
printf() rather simply println() all those things are not applicable no formatting is
possible. But println() in that case is very simple that although it will not do any format
for you, but it will print the right value for you. So, sometimes it is very safe to use the
print() or println() method instead of printf() in Java.

(Refer Slide Time: 14:42)

Our next demonstration so we have to learn about print println() and printf() method to
display the output on the standard output namely display screen.

200
(Refer Slide Time: 14:48)

Now, I will discuss about how the input can be passed to users program there are three
ways. One is the command line input so command line input concept is that; while you
run the program; that means, you call the program. That means, your main program that
time itself what are the input that is required for your program you can specify. This
means that Java will take these inputs automatically and then run it Java will not take any
input later on then I mean it will not ask any input.

So, if you know that these are the inputs, that is required for your program you can pass
them at the time of calling this program or executing this program. Now whatever the
input that will give Java interpreter will store all this input in a temporary array. So, this
array is called the args. So, screen args that you can see is just highlighter you use. String
args that we use so this string args basically we will use you use temporality store all the
input that you passed. And as you know it is declared this string; that means, all the input
will be stored as a string object and it will be processed then.

Now we have already discussed in theory class that is a string object can be configured
or passed to transform to the different type using the different methods defined there in
Java.lang package. Now here let us see this example it is a demonstration for 34.3 and
here the public static void main (String args[]) as usual we do not have to do anything
here. But now you see you have to use a for a loop. So, power in i equals to 0, i will be

201
less than args.length. args.length is basically the number of inputs you passed that means
how many input object is stored in the args array.

So, this basically there if you pass 3 then it will be 0 to 2 actually this kind of thing.
Because the first object is stored in 0 indexes is 13. So, the total number of the object is 3
and it will basically store in args 0, args 1, args 3 if it had it will be three inputs are
passed. Now the next statement is basically System.out.println(args.i). It basically what
about the screen that he passed it what is the input that you have passed it will be print as
a string and it will just go on printing this one.

Now, instead of println() we write print() only. So, it will basically print and at the end
System.out.print() l n print after the, for loop fine yes. And fine so next statement is
customary written is no need to write it system.exit(0) is basically will quit this execution
anyway. So, now, this is the program that we have written you can understand what the
program will do for you. The program can be called with input and though those input
will be passed to this object. So, let us have this execution this program there in I
consider fine no problem let us see.

(Refer Slide Time: 18:16)

We have done some mistake here run hello ok. So, now, here see this fine. So, now, you
see we have called this method with 3 input hello to java. Now, so, this method takes and
then print it like this one. Now let us go to the program again yeah. So,
System.out.println() where the first System.out.println() go there println() no issue. And

202
then and fine we have a little bit change it absolutely no problem there are a no major
changes minor changes we have done it. Then not equal fine command fine right run this
program.

(Refer Slide Time: 19:13)

Now we are calling this program passing may not 1 2 3 4 5 6 7, 1 2 3 4 5 6 7 now you
see the different input that we are passing separated by a comma. Here although we have
entire 1 2 3 all these are the digits or next is maybe say 5 5 5 let us see ok. So, we have
the entire 8 numbers. And all these numbers entered in Java program will be these are the
string and they will be printed as a string. And the 8 numbers should be printed in the
next line let us run this program.

Now, you see these are the numbers it has those numbers have been printed here taking
the input ok. Now go to the right. So, this is the way that by which we can pass
command line input; now we have one more example so, that we can understand about.
So, that command line input needs to be used very carefully because you have to specify
whether you have passed input or not. So, that is why some step if you had it then it will
be a more robust program.

203
(Refer Slide Time: 20:23)

But regarding the robust program writing will discuss in details later on. So, it is a 4.4
demo 4.4.

(Refer Slide Time: 20:32)

Yeah, now let us see the program the same program it basically checks whether during
the command line argument is passed or not if during the common line no argument is
passed it will report that statement if it passed it will print this. So, here basically the pass
if statement to check that if during the command during the execution of the program if it

204
passed any common line argument not. If it is not then it will print a message that the
common line arguments are there.

If it not then it will print that the command line argument no command line argument is
found. So, and if it is there then it will print all the command line arguments using is
stress is expiry special for commands string well args; that means, all the value what
about the true it will go on printing. So, this is basically an alternative way of printing all
the input that you have passed to this program. Now let us run this program it basically
reports if you do not pass any input.

(Refer Slide Time: 21:39)

And if in the report if you pass any input then print it. Now we are running this program
without passing any input 4.4. Now so we are running this program without any input
and you will see it will. So, no command line argument found. So, it gives that because
we do not give input. Now again we are running the same program while passing hello
Java hello Java 123.

So, these things are there ok. So, so fine no problem. Now you see it print it will the
command line arguments are hello Java 1 2 3 it is according the next other than else part
and then for the statement. So, so this is I mean this is a trick for writing a good program
whenever you use the command line arguments. Now command line arguments also can
be used to pass into the integer I can go to another program let us go to the 4.3 demos of
the 4.3, 4.3 right.

205
(Refer Slide Time: 22:54)

Yeah, so, here in the for loop of comment [FL] maximum for loop brackets second
bracket we comment [FL] fine now we are just ok. So, comment [FL] fine in you can
delete this formality clattering will be above it fine we are removing and fine. So, now
we are just here integer I equal 0 declare [FL] ok.

We are declaring one variable integer and then we are I equals to integer.parseInt()
integer.parse p a r s e parse capital over p a r s e parse int I n t capital I n t parse I n t I n t
parse int then args 0. Then System.out.println() int then System.out.println() in outer
command System.out.print()ln() then the value within the value of I in an integer is plus I
semicolon system exit a common [FL] fine.

206
(Refer Slide Time: 24:43)

Now you can change what we have done it nothing a different will take the passed input.
And then passed input will be passed as a string, but it will be converted to an integer.
So, how so common? [FL]

So, you can command Java bracket [FL] ok. So, we have fine [FL] [FL]. It is fine this is
correct this is fine. Now it is there little bit clean the always thing garbage and then you
can run it.

(Refer Slide Time: 25:23)

Capital I right this is correct parse capital small p [FL] it is [FL].

207
Student: (Refer Time: 25:52).

Now let us we have written the program we have to go fast. Now we can see the input
can be passed as an integer right. 1 2 3 and this basically although we passed as a string,
it will convert to an integer enter the value of I is an integer.

(Refer Slide Time: 26:13)

But if we pass hello then it basically gives an error. The error is basically run time error.
So, this is an error because it is not able to convert this value to an integer value. So, this
is the error, which is pointed out. But will learn about how this kind of error can be dealt
with later on.

Now, so we have learned about command line input the value whatever it is passed as a
string and that can be converted to any type as you want. So, this is the idea of the
common line. Another way the scanner input. So, let us have the demo of this type of I
put 4.5. So, now, let us see there is one plus which is defined in util package Java.util the
name of the class is the scanner class. This scanner basically helps you to read the input
from the keyboard and then that can be used for your purpose.

Again this scanner will read as an integer as a float as you string whatever it is there.
Now here is a quick demo of this one we declare one plus the main plus is demonstration
under 45_45 and here you see that the first declaration Scanner scnr = new
Scanner(System.in) So, this is the typical syntax about new is basically the q r to create

208
an object the name of the object a type of the object belongs to the class scanner. And
then here argument this is default we have to parse system.in that is means the standard
input. So, system.in indicates the standard input means the keyboard

So, basically, the scanner will read some value from the keyboard. So, this is the way we
can create an object the object name of the object is scnr. So, this is the use the defined
we have defined this object name. Now we would like to read two numbers from the
keyboard using the scanner class and then those actually the scnr object will be ready for
you to read the input from your keyboard.

Now, this basically can be done by means of one method which is defined in the scanner
class itself is called the next int. That means it will go on reading and here to success in
reading will take place the value will read from the keyboard and then store into the
temporary values a and b. And whatever the value it will be read as an integer because is
a next int method will scan as an integer. And then the next two statements if the
statement is basically processing it will print whichever the value is highest one. Now,
let us quickly run this program to see how it works.

(Refer Slide Time: 28:59)

Ok, now we are giving two input so let us give 45 then 54 enter. So, here we can see the
input the result that will be printed here like this one. So, that means it read two number
successfully and the two numbers it basically compares and then maximum number is
printed there.

209
So, this is the one way is an alternate way to common line input that we have discussed.
And some people find it more I mean easy and then convenient for their programming so
it is there. Now, let us have another demo on the same utility of scanner class again 4.6.

(Refer Slide Time: 29:57)

So, let us have the quick again we use the scanner class which is defined in a util
package. So, input statement that we have used earlier like this one and here we just see
enter the radius we read the radius. But in this case, we read the number not as an integer
as a float. So, we should use the next double now again we create the scanner object in
this case sc and then radius the value will be read from the keyboard as a double and then
it will processes it and then give the result. So, let us run this program.

210
(Refer Slide Time: 30:31)

So, here we can give for 50.5 anyway so no problem although we enter 50, it takes as a
format again run this program 5.5. So, this basically takes the value as a floating point
number as a double format and then calculate the area of the value using the formula that
is defined in the method.

So, this is basically the way the Scanner class can work for you can read any number
from the keyboard in any format and regarding the different format that is possible that
you can have in the scanner class itself. Like next string, next float next double next
string so many ways the input can be read. Now, so this is the scanner class, now let us
have the last method using the data input stream class.

211
(Refer Slide Time: 31:38)

It is a little bit difficult to understand at the moment regarding this data input stream,
who will discuss in details when we will consider about input-output stream. Now let us
have a very quick demo of this use usage of the data input stream class it is more or less
similar to the scanner.

(Refer Slide Time: 31:56)

But here we use data input string class which is defined in I o package. So, in this case,
we should import Java.io.*. Their data input stream class is where we can I defend

212
Java.io.datainputstream also anyway .* means it will import the entire package io
package.

Now, let us see we have declared two objects principal amount rate of interest they are
declared as a floating object. So, an object of type float can be declared using this kind of
statement. And also we declared another member elements number of years, which is
declared as an integer. So, three variables three elements have been declared here as
principal amount rate of interest and number of years. Now we just create an object the
name of the object is called in basically input object we can write I np whatever you
know in ok. So, in as the object is created this object is of type data input stream and data
input stream and if you see the argument system.in that mean. We now decide our we
now direct the data input stream to read from the keyboard.

So, here also you can use a filename so that it can read from the file regarding file
reading and everything that is another discussion will be discussed later on. So, yes
system.in means that we want to read some value from the keyboard for which we create
an object call in. Now temp string is a temporary string and again data in data input
stream class will read anything in the form of a string and it is required to convert into
the desired format.

Now, let us see how we can work for that. So, System.out.print() enter principal it gives
a form to the user that you should enter the principal amount. System.out class is
basically clean the buffer. So, basically, every keyboard or standard input has its own
buffer if you call this it will clean so, that no garbage will be entered into your in the
input. Now temp string basically stores the value, which is read from the buffer keyboard
and it is basically to read a buffer keyboard the statement the method that is required is
read line method is declared in data input stream class. So, it basically read the entire line
from the keyboard buffer and it will store as a string in a temp string with a temporary
variable.

Now, we convert this value temp string into the float type and the conversion is followed
by this kind of method float.value of temp string. So, this is one method by which a
string can be converted into a floating point value. Now again the next we can give the
form to enter the rate of interest same as system.out.class again same the read the

213
keyboard buffer and then we finally, read the string and then the string is converted into
the float value and store in the rate of interest.

Again we give the next command next informed the entire number of years. We clean
the buffer read the buffer and then finally, convert this value that we read from the
keyboard using Integer.parseInt() and store into the variable call the number of years.
And then we declare interest total and this is simple formula calculate the interest given
the principal amount rate of interest number of years and then print the result. And let us
see how you can run this? There are a few things I will discuss shortly.

(Refer Slide Time: 35:31)

Let us have a quick demo we run this program ok. So, warning you can include it there is
a warning because of some depreciation no issue is basic casting. So, you can ignore
warning can be ignored now it is asking the principal amount right rate of interest 5 10
whatever it is here is 2 no problem. So, it is calculated the total interest like this one.

So, this is the way the method can be calculated, it is an actual rate of interest should be
0.5 whatever 0.05 like this one anyway. So, so this is a one execution now let us come
back to the program again and if you see there is one statement that we have try and then
within double brackets entirely brackets, we face everything and for this try going to the
end we have end the curly bracket here this one and followed by a catch. Now, this is a
try catch statement, which is basically for exception handling. So, if you do not put
sometimes compiler will report an error and may not execute to create the bytecode. So,

214
that is why it is customary to use try-catch whenever the data input stream or some input
stream class is used. So, regarding this try catch and everything will discuss it in details.

Now, if you do not give try catch let us see what error you can face it. So, just remove
that try block command this command catch command now we have removed the try
catch it is a very simple to program without any try catch as we do not know anything
about it. Now let us see whether we can compile this program or not now here
compilation is not successful. So; that means, it requires the try catch, which is required
for dealing if there is an error in input.

So, that is why there are many in.readLine(). So, sometimes there may be the program
can call this. So, try catch now there is an alternate way to deal with now you can do it in
the main function here writing throw exception there is a one way instead of the try class
also you can do that. So, here we are doing like this now we just use throws an exception
this is also an alternative way in the main method if you do it then without try catch also.

(Refer Slide Time: 38:04)

Your program may run. So, warning you can ignore. So, this program is running now let
us go clear right c l s.

215
(Refer Slide Time: 38:12)

Running principal amount 5000 at 0.1 0 0.100 fine and the number of years 5. So, this
basically gives you the calculation of interest how you can do this.

Now, you have learned about three ways of giving input and regarding input and output
will discuss many more thing on the running discussion. So, it is a till time is a today up
to this demo we have planned about print how to output on the screen and then input to
the program ok.

Thank you very much.

216
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 11
Java Scope Rule

Scope rule is a very important concept in any programming language. So, Java is no
exception for this. There are mainly 2 scope rules static and dynamic. In Java also we
follow both the scope rules static and dynamic. In today’s lecture we will discuss about
Static Scope Rule.

(Refer Slide Time: 00:41)

Now, let us see a small program here is a class declaration called the class Box. So, this
class is you already know that it has the data as well as the method in this case area is a
method x y w is another class is a member of this class.

Now, let us consider another class, here is the Circle. The Circle has data like x y r and
then another method is called the area. Now if we consider the 2 classes; namely Box
and Circle then we can see that x y both member data members are declared as float in
both the classes, but the thing is that x y which is defined in Box it has scope within the
Box class. Similarly, the x y which is defined in the class Circle it has the scope only
within this class Circle.

217
Now if we write a main program, let us name this main program as GeoClass and we
declare here the 2 members, the x and y which is declared as 50 and 60. So, x and y is
basically member which belongs to GeoClass. Again this x y and the x y in class Box or
x y in class Circle are totally different.

Now, here again if we see in this method we create 2 objects of type Box and then Circle
b and c respectively, and then if you see System.out.println this x this x is basically, x
equals to 50. Similarly if we call this one b.x, so b.x is basically this x in float. Similarly
b. area of the method b and like this c. x is the x of the class c and c.area is the area of the
method c.

Now, so with this scope we usually resolve by specifying the name of the object. So,
b.x ,c.x, b.area c.area like, so this way we can resolve the scope and the scope that we
can follow it is called static scope, because by saying the program we can tell that which
method or which member has the scope of what.

(Refer Slide Time: 03:23)

Now, this is the one example of static scope rule. Another example: now let us see
another class that we have declared here. So, static scope the name of the class and in
this in this class we declare one variable x as integer and x is declared as 20. Now if we
see it is declared within this main method; that means this x has the scope of the entire
method.

218
So, here x is the one class that we have the declared, it is declared as an integer the scope
of this is basically the entire method, the main method. On the other hand, we have
declared another variable integer y equals to 20 and as it is declared here not here; this
means that, this y has the scope of this part. So, this scope the scope of this is this one.
So, the 2 variables which we have declared has the 2 different scope, x has the scope of
the entire whereas, the entire whereas, the y has the scope of this one.

Now, so this is basically another example of static scope rule and in this case, if we see
in this case if we can attempt to access y is equal to 100 is basically report a compilation
error. This is because the scope of y is beyond this right. So, y does not have any scope
outside this region. So, that is the case of the static scope rule and it is in case of simple
variable that we have discussed.

(Refer Slide Time: 05:49)

Now, so we have learned about the simple scope rule. Now there are 2 concept in Java
related to the scope rule it is called the instance variable and the class variable.

Now, let us first discuss about what is the instance variable. Now let us refer to the
concept of class box, we have created 2 objects say b1 and b2. So, b1 and b 2 are the 2
objects and the 2 objects have the 2 variable 3 variables x y w. So, if we create b1, it has
instances and this is the one instance corresponding to the object b1 this is the another
instance corresponding to the object b2. So, there are 2 instances of the object that we

219
have created. Now let us consider another instances of another object say class 1. c1 is
another objects of class Circle, c 2 is another object of class Circle again.

And again here we created the 2 instance of class Circle, where x y r are the 3 instances.
So, here this is the one instances and this is the other instances of the right. So, whenever
we maintain the memory. So, basically this x is the separate and this x is the separate.
Similarly this x they are all separate existence. So, this is the idea about instance
variable.

Now if so instance variable we have learn about. So, whenever an object of a particular
class is created, we consider instance variable for that objects are created.

(Refer Slide Time: 07:49)

So now, we will discuss the static variable declaration.

We have mention the concept of static, while we are discussing about main method
declaration. So, public static void main, so they are the static concept was declared that
without ok, if we declare a method as static. So, this method can be called without
creating any object. This is the concept that we have learn about, but the concept of static
keyword in Java also has its own implications.

Now we are going to learn about it. So, in Java we know there is no concept of global
variable declaration. All the variable; that means data that will be declared will be
encapsulated in that class, but sometimes we may require the global variables also. So,

220
Java developer can provide this one by means of static keyword. So, if we declare a
variable or a method as a static, then such a variable is called class variable or such a
method is called class method.

Now, we are going to discuss about class variable and class method one by one. So, if we
declare a variable as a static; that means, if we declare a variable as a class, the
difference from this class variable to the instance variable is that instance variable has its
own local copy whereas, class variable has the global copy. That means, for all instances
of all objects belong to a class, if it is a class variable then it has only one copy whereas,
for all variables which are declared as instance variable they have the different copies.

Now, so here is a one example. Here suppose b 1 b 2 b 3 are the 3 objects belong to the
class Box and if we declared w as a static, so that declaration like say static keyword
before this, so static float w, if we declare w as a static right this way, then w become the
class variable.

So, it means that, in this example all x y they are the instance variable, where as this w
and the other static variable of class variable; this means that it has for all objects is the
only one copy is there. So that means, it shared w is shared among all 3 objects that we
have created. So, it is a class variable, that is the static variable then it will have only one
instance for all classes; that means, shareable to all classes. So, this is it about 2 concepts
that instance variable versus class variable.

(Refer Slide Time: 10:51)

221
Now, let us discuss an example to clear the concept of static variable more
understandable way.

So, here we discussed one class name, of the class is Circle here. So, we declare a 1 class
Circle and we declare one variable here, you can note the variable is a circlecount and
which is declared as a static. These variable is declared as a static; that means, circle
count is a static variable or class variable in this case. On the other hand, here we declare
other 3 variables. Simple as a public double x, y ,r they are basically instance variable.

So, in this in this class example, we declare 3 2 types of variable; class variable and
instance variable. Now, let us these are the as usual we have already familiar to this is a
constructor, there are many way constructor using this. So, this is the one constructor
which is defined explicitly and these are the constructor which basically it defined using
this, this means called the superclass constructor this constructor using other parameters.
So, those are the concepts that we have already learned about it.

So, this basically compressor, the declaration of a class Circle, so, this is a class circle
that can be initialized an objects or create an object with different parameter that can be
passed here. Now in addition to this, this method has this class has the 2 more method
circumference and area. So, this completes the declaration of the class Circle.

Now let us come to the declaration of this method public static void main string args
method. Now, here we declare 3 objects c 1, c 2 and c 3, so 3 objects are created. Now
for 3 objects therefore, so for the instance variable x y r are our concern, they have the 3
instances separately whereas, for the circlecount for all the 3 objects c 1 c 2 and c 3, it
has only one instance.

So, this means that if we print the c1.circlecount and then c2.circlecount and c3.
circlecount, for each circle it will give the value. As it is basically whenever this is
increased, so circlecount will be increased, when one object is created. So, initially it is
0, when this is created circlecount is 1. This is created circlecount is 2 and when this is
created circle count is 3. So, this c one has its circlecount one c 2 has circlecount 2 and c
3 has circlecount 3 and at the end of these things the value of the circlecount when the all
3 objects are created is basically 3.

222
So, in this case, if we print c1.circlecount c 2.circle count c 3.circle count it will print 3
3 3 in all cases. However, if we print the circlecount print c1.circlecount here it will print
1, if we print here then it will print 2 and if we print here it will print 3. So, this basically
this is because the circle count being a class variable is a global variable. So, if the value
is changed by any object, it will be reflected automatically to the global object. So, this is
a one good example of static variable.

(Refer Slide Time: 14:51)

Now, let us consider the discussion of we have learned about static variable likewise a
method also can be declared as a static method.

Now, a method can be declared as a static method, if we use is a static keyword again.
So, static keyword is used to declare the method. For example, here again come to the
Circle class, it has instance variable these are the instance variable and this is a one
method the constructor this is a one method called the bigger. This bigger takes an input
and argument as a circle and return another circle. So, this is a method and here another
method you can see, this method we have declared again as a bigger, but this method is
declared as a static.

Now, these 2 methods are called overloading, overloading method means this bigger and
this bigger although same, but they have the different task and operation, because its
argument is 1 circle, it is having 2 it code is different than this one. So, these 2 methods
are overloading method.

223
However, in the second overriding method, overloading method that we have discussed
here as a static; this means, that this is the simple instance method. That means,
whenever one object is created, we can call this method for that object. However, if we
declare a method as a static, then it is called the class method. That mean this kind of
method can be accessed without creating an object.

Now, let us see one example in the main method it can clear your idea when I mean how
the 2 methods instance method and class method is different. So, here is the one example
that we can see here. So, we can create a circle circle and so a b are the 2 circles objects
are created and then c basically is another circle object is created, but it will be returned
by bigger.

Now, you see this bigger method this bigger is basically the instance method because in
that it is accessed by accessing objects. However, in the next example if you see, here
this bigger a b is called for the circle class without creating any object. So, this is a idea
with the class method. This means that a class method can be invoked without creating
any object and that is why our main method is static which belong to this class Circle this
is because without creating any object class Circle, we can call this method a main is
called without getting any object of that class. So, this is idea about the static method.

(Refer Slide Time: 17:57)

So, we have discussed about static scope rule, and then the class variable and instance
variable as a class method and instance method.

224
Now, we will discuss about the nested class in Java program. The nested class means a
class can be defined within inside another class. So, it is called a nested class and in Java
there is no limit about how many nesting is there. It can be going and, but nested class is
not a good practice because it basically creates a lot of i mean a source of many errors
are there, but sometimes if we see that this class is only limited to the this part only then
in that part we can discuss that class. So, being defined a class as a nested, it is basically
very local to either that class or belong to that method or belong to that block.

So, nested class concept is it is although rarely used, but it has some usage in some
context. So, let us discuss about the idea of the nested class concept. Again come to the
declaration of class Circle that we have discussed here and here you see the circle class is
declared, circle class is declared and within the circle class, we declare one class called
point. We declare this class as static; we can declare simply public class Point. If we
declare static means it is only one instance for all the circle of that we created that is why
the concept is there anyway.

So, this is a one point that we have declared within this class. So, this class concept, this
declaration, this declaration is a nested declaration, and it is the example of nested class.
Now let us see the complete code for this.

(Refer Slide Time: 19:55)

Here is the complete code and there simple one code here. So, we declare one method
within the class Circle, the name of the method that we have declare here is a boolean

225
method; Boolean is a variable, the name of the method is inside and these are the code of
this method, very simple code it basically the method is to decide whether a point inside
a circle or on the circle or outside the circle. It is a simple logic that you can follow it
will create a distance from the centre of the circle to that point.

And this distance is less than radius of the circle then it is inside. If it is equal to the
radius then it is on and then if it is greater than the radius then it is there. So, this concept
it is used here. So, this Isinside method and let us see the main method. The main method
creates 2 objects a is the object of class Circle, pa is the point and then pa dot display is
basically call the display method which is defined in the class itself. And then here
basically it will check that whether this point pa is inside the circle or not. So, is basically
we create another circle b and p b and then we can call whether this point 3, 3 is inside
the circle or not and here this point p is inside the circle this circle or not.

So, this is the idea about that here the class p is to be local to the circle class. This means
that this class point cannot be accessed by any other class either in this file or outside this
file. That mean, if we use any other program where we can use these class Circle, but we
cannot use the class point there exclusively, it can be used only the class Circle is used
like this one. So, class circle class point p class point is totally local to the class circle
only. So, it has limited access in that sense.

(Refer Slide Time: 22:13)

226
So, after knowing the nested programming, nested class concept, the Java also provides
us the recursive program.

Now, recursion is an important concept and it solve many complex problem very
quickly, only the thing that is required is that to solve the problem which needs to be
solved using recursion, we have to have a very clear definition of the problem itself.
Now let us see how the recursive program can be written in Java, we will consider a
simple example; we know the calculation of factorial. So, a factorial n factorial will look
like this one, so the factorial n which look like this one.

So, n factorial is basically as you know this is a common declaration n factorial is look
like this ok. And we know that 0 factorial equals to 1, so it is there. So, this basically this
basically the concept of the factorial, and if we write a iterative program using some for
loop, the calculation of this recursion is not a big job and this code is basically explain
how recursive program, how the calculation of factorial can be done using an iterative
program, so using for loop, but the same thing can be done using a recursive program, let
us see how the recursion is there.

(Refer Slide Time: 23:59)

So, the factorial calculation can be defined recursively using this definition.

So, here is the definition of recursion n=n*(n-1)!. It is called the recursive definition,
because n! is defined in terms of (n-1)!. So, this is why that mean the same thing is

227
define by itself. So, that is why the concept of recursive. Now, this definition can be
straight away implemented in a recursive program and now here is an example how we
can see. So, here you just let us look at the code. So, we have declared here the one class
Recursivefactorial and then integer n is a data for this class and factorial is the method
which basically will calculate the factorial of any integer n.

Now, here is the code, basically complete codes for calculating the factorial of any
integer and if you see n factorial this is a factorial n=n*(n-1)!, so this definition. Now,
here also for every recursive program, you should consider the termination condition. So,
is the termination condition is that 0 factorial equals to one because this factorial will call
factorial n minus 1, to calculate the factorial n minus 1, it will call the factorial of n-2
and so and so on. So, call will go on this way, n to n-1 to n-2 to …and whenever it will
come to 0 it basically return 1. So, no more call of the factorial function is there. So, this
is a concept of factorial calculation.

And here is the basically we create an object. So, x is an object of this class. So, it is
basically recursive factorial. The object is created and we read an integer value from the
common line. So, x dot n is basically the value of the class at a (Refer Time: 26:24) n
and then it will basically call the factorial x .n as a output it will give you the factorial of
n basically. So, this is idea about factorial calculation. If you look this program little bit
carefully you will be able to understand. So, this is the idea about, now if we practice
more recursive program, then a concept of recursion will be good. So, I will just clear
few more example.

228
(Refer Slide Time: 26:57)

Another example, this is also good example for to discuss the recursive program writing.
Now the series I have listed here. If you see the series, then if I ask you what is the next
number, the next number you can guess that this next number will be 34. So, here if we
see any number is basically sum of the previous 2 numbers. So, this way the recursion is
here. Recursion means, here again I just discuss about how the recursion come into the
picture here. So, the idea about this, and so if I ask you to write a program which will
print all the numbers according to this series, this series particularly called the Fibonacci
series or Fibonacci sequence. And this is the iterative program is very simple loop, that
loop is basically declared here, you can understand that this loop will create this kind of.
So, these are iterative approach of calculating Fibonacci series.

Now, let us see how the same can be done using writing a recursive function. So, in that
case you have to understand that how this Fibonacci series can be expressed in a
recursive way. Now, so here is basically the recursive definition, so far the nth Fibonacci
number is concerned where n maybe 0 1 whatever it is there. So here basically this
basically the recursive definition of any nth Fibonacci number, if you see if you have to
calculate the nth Fibonacci number it is basically Fibonacci(n-1)+ Fibonacci(n-2).
Similarly, n-2 can be recursively calculated n minus 2 can be recursively calculated. So,
this way a recursion can be grown out and this basically is the termination condition.

229
Now having this definition within us we are now in a position to calculate the recursive
version of the Fibonacci series calculation.

(Refer Slide Time: 29:19)

So, here is the recursion recursive version of the program. Now let us look the program
here we have so, this is basically the termination condition. So, this is basically here is a
termination condition as we see, this is corresponding this one is implemented and this
basically Fibonacci(n)= Fibonacci(n-1)+ Fibonacci(n-2). is basically Fibonacci n minus 1
plus Fibonacci n minus 2. So, this way the recursion will be carried out and this is a
simple main program, which create a which read a value from the keyboard and then
calculate its Fibonacci and then print the things.

So, these basically, print the entire series of the Fibonacci sequence. So, this is a one
program that you should practice with your own time. So that you can understand both
the recursion program that we have discussed for the factorial as well as Fibonacci, so
practice.

230
(Refer Slide Time: 30:19)

Now, let us before conclusion, let us have one more example and this is the GCD
calculation, GCD stands for greatest common divisor. As we see GCD of 2 numbers
integer number rather can be calculated like this ok. So, GCD of 113, one this 8 and 8 is
like this one. So, this is the as per the simple definition of GCD. Now let us see how the
same the GCD can be defined recursively.

So, here is the recursive definition these basically, include the recursive definition of the
GCD it is basically same as the same as this one right almost same this one; so this
basically recursive. Now if we convert this part, if we convert this part into a Java
program is a method in a Java program it basically calculation.

231
(Refer Slide Time: 31:11)

Now, let us see how the method for the same in Java program will look like. So, this is
basically is the method recursive version of the GCD calculation. The definition those
things that we have discussed here, here it is basically implemented here, and then here
the recursive version is that is GCD is basically GCD of this one, so this concept it is
there.

So, this way the recursion can be carried out and this is the main method where we just
call this recursive method to calculate the recursion for any 2 integer read from the
command line argument from the keyboard. So, this is the idea about the GCD
calculation and so we have discussed about few example of GCD calculation.

232
(Refer Slide Time: 32:01)

Now, let us consider another simple program. Can you guess it? Although it will take
some time right maybe 30 seconds you can think about. So, what this code will give
results?

If you think it then you can understand that recursion is little bit understandable to you.
Anyway, if you run this program with your own machine and then it will you will see
that it will give this kind of output. Can you explain why this output for this program?
So, if you know the recursion then you will be able to explain these things very carefully.

(Refer Slide Time: 32:35)

233
Anyway, this is about the concept of static scope rule in Java we have discussed about.
And there then in our next lecture we will learn about information hiding, this is very
important concepts. And then also we should learn about how a very big Java program
can be developed.

So, these are the next topics that will be covered in the next discussion.

Thank you very much.

234
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 12
Demonstration – V

In the last module, we have learned about the static scope role in Java and also a little bit
about writing a recursive program. In this Demonstration, we have a quick illustration of
the different concepts regarding the scope rules that we have learned and then recursive
program writing.

(Refer Slide Time: 00:33)

Before going to that we should have basic control structure, I know that you, if you are
already an experienced C programmer for you all those basic control structures, is known
to you, but those are new for them it is just to make the consistency we will just discuss
quickly. So, there are different loop structures and then switch case will be covered and
then finally, discuss the scope rule and then Java program writing using a recursive
function. So, let us have the quick demo about first our example is how we can use the
while loop let us see the program.

235
(Refer Slide Time: 01:23)

So, this is one program as you can see this program basically uses the while and within
this while and there is a condition; that means, this loop will continue until the value of
count is less than 11. And you can guess that what this while loop into it basically
includes on print statement, it will basically print the odd numbers starting from 0 0 next
sort numbers star after 0 is 1 of course, so, 1 3 5 7 like this one.

Now, let us run this program. So, that you can see how this while loop will roll it, you
write the compilation, you have to compile it right the Java C. So, this is a program that
is compiled the here we can see the program is compiled successfully now let us run this
program. So, Java yes and as you can see this a printing first ten odd numbers it is here.
Now, this is a one form of while loop now let us have another form we can open 5.2
program

236
(Refer Slide Time: 02:35)

So, this is another program and it is the the same thing in the earlier program it is
printing the odd number, but as you can see this program is to print the first ten even
numbers. And here instead of while we have used the do while statement and is mostly
the same thing, but obviously, there is a difference between the while and do while. Now
let us run this program and then let us first we have to compile it yeah so, running this
program. So, it basically prints it, now if I asked you what is the difference between
while and do while?

So, while basically check the condition first whereas, in the do while at least one loop
will roll and then once the one loop is done then the condition check at the end. So, the
difference is that while loop may not execute in a single loop, but at least do while at
least one loop will be executed.

237
(Refer Slide Time: 03:47)

Now, similar to while and do while there is another constructor in Java it is called the for
loop. The for loop is totally different than the while loop or do while loop. Now, in case
of any loop, there are three things are to be considered initialization for the loop variable,
in the first two examples the loop variable was count.

Now, initialization of the loop variable and then the condition checking; that means,
whether the loop has reaches it’s the termination condition or not and then updating of
the loop variable. Now all the three things can be done using for the statement in one
line. Now here we can see the first statement here int i, in this case, it is the loop
variable; that means, it is the this is the variable i which controls the execution of the
loop. So, here int i = 1; that means, initialization of the loop variable as 1 and this is the
condition checking that look will continue until the value of i is less than 11 till the value
of i is less than 11.

Once, the value of i=11 or more it will exit the loop and i++ once the loop is completed
one its term then it will increase the value i automatically is in the one. Now here in this
for loop as you can see is a simple print statement which basically prints the value of i.
This means that this for loop will print i=1 to i=10 the 10th first integer number. So, if
we run this program then we will be able to see exactly how this for loop works for you.
So, this for loop as we expected that it prints 1 to 10 consecutively.

238
Now, so, this is an example of the do while and for loop or the three loop structures in
Java program, it is very similar to the structures that are there already in C and C++.

(Refer Slide Time: 06:03)

Now, the loop can be controlled or it can be terminated abnormally and before for this
thing there are two more statements is there called the break and continue. So, the
purpose of the continue statement is that if some condition is satisfied it will not execute
the remaining part in the for loop block.

For example, in this example here the for loop we have this if i; that means, i not 2 there
means if i is an even number, then it will not execute the next statement namely
system.out print ln and it will go to the next round of the loop. So, continue is basically
skip the remaining part in the for loop is going to the loop again. Now if we run this
program as it is you can anticipate that this will print the first statement in the for loop is
print; that means, it will print two numbers in one line and whenever there is a mode it
will go to the next line like this one. So, is the print statement will print the values here.

Here we can see 0 1 in one line and then mode so, 2 it goes to the next and so on so on.
So, continue statement is executed after every odd-even number in the for loop.

239
(Refer Slide Time: 07:35)

So, this is the idea about the continue like continue there is one break statement; the
break statement whenever a condition reaches. So, it is basically terminate the loop
without any satisfaction of the loop control termination criteria. So, this is an example
here we can see here i mode 10 indicates that whenever the value of i reaches to 10 or
multiple of 10 whatever it is there so, the loop will be terminated.

So, in this for loop as we can see int i=1 and you can see the condition here is basically
null we do not give any condition; that means, if you do not put any condition checking
there then that loop will suppose to execute for infinite times. But if there is a break
statement and if there is a condition which satisfies the condition then the break
statement is executed then the loop will be terminated there. So, although it looks like an
infinite loop, because of the break, there is a condition that it will terminate the loop.

Now, let us run this program as you can see it will pin i=1 2 3 and till i=till it reaches
i=10; once i=10 loops will break and it will terminate the loop yeah. So, it is basically
the concept that how the break statement is there? Now so, we have learned about basic
control structures there mainly the while do while and for loop with break and continue.

240
(Refer Slide Time: 09:03)

Now, in addition to the simple control structures there is basically a decision structure if
else; if else is very simple we do not have to discuss it in a detailed manner, but like this
is if int is a multiple decision checking is done in Java by means of the switch case. Now,
we will discuss the next program in switch case; now here is one example before going
to this to discuss the switch case statement is basically how we can test whether a
number is prime or not.

So, it is basically usage of both for loop as well as if statement now for basically you
have to test till a certain number is prime or not the condition is that i less than num 2
because, you have to check for this kind of things; that means, if any number within this
num 2 if we have to test that whether num is a prime or not. So, up to half of these things
we have to roll this loop. So, that we can check that any number within this range it is
divisible by this number or not so, the divisibility check by num not i. So, it basically
checks the divisibility.

That means it is divisible by this i where i is basically 2 to that range and then if it is
there then it will check that ok, if it is divisible then it is not a prime. So, each prime is a
Boolean variable declared a false and then is broken because no more testing is required
otherwise it will continue. Now, we can test this program by passing input from the
keyboard and here is the execution of this program capital so, 5.6 5.6. So, now, v 6 as it
is on the 6 is prime now let us run this 31; 31is a prime so, it will check that prime.

241
So, like this so, you can test that using this control we can test this. So, logic is basically
any logic can be implemented using for or while and then if else statement there another
logic structures is there as I told you the switch case structure let us consider one simple
program.

(Refer Slide Time: 11:23)

And this switch case is basically here we can see. So, and we can see the first few blocks
is there do while blocked it basically print something until you type 1 to 5 any number if
you type anything. So, this loop will continue ok. So, in order to come out from this
loop, you have to either print 1 or any number less than greater than less than 5 actually
here.

So, if any number you type better than 5 it basically breaks the loop now let us see once
the value of i chosen from here. That means the user can enter any value which is greater
than or=1 to less than auricles to 5; now once the value is read and then there is a case.

242
(Refer Slide Time: 12:11)

So, depending on the type the number that you have chosen we have a lot of switch cases
is there; that mean if i that we have written in the first statement here the choice
basically. So, it depends on the choice it will depend on the different states will be
executed.

If choice=1 so, the case 1 code will be executed and if choice=2 the case 2 code will be
executed. Similarly, for all 5 cases, the different statements are there in this program and
you can see for. So, here basically switch based on the value of same switch variable
here choice the different cases will be executed all cases are basically few courses are
there. And, then all case statement will be a term at the end of this case statement there
will be a break; that means after this case is where it will break that switch loop actually.

So, this is a structure of the switch case concept in Java program. Now let us run this
program so, that you can understand how it will work. So, the advice is that you should
have this code and then try to practice of your own; so, that you can understand how the
codes are working. So, here now choice 1 if I press say 9, then you can understand what
will happen it will loop so, it is asking this one; now again choice says 2. So, it basically
tells about the switch. So, this is a way that the program can be executed. So, this is a
simple example of the switch case statement.

(Refer Slide Time: 13:57)

243
Now, so, these are the control structures which are widely used in your Java program and
you have to learn it you have to practice it. So, that you should have very skill about all
these programs; now once that things are there our next topics in this discussion
demonstration is the usage of scope rule. As you have discussed that Java follows 2
scope rule static and dynamic so, in this demonstration, we will limit our discussion do
static scope full only.

Now, let us have a quick look to this program and here we can define a class the name of
the class is demonstration_58, these a name of the class and under this class only main
method very simple class. And you can see them, for the main method the matching and
then beginning curly brackets are there. In addition to this, we define a block in a
program can be specified by means of {}. So, here the block it is there; now in this block
inside this block, you see x=10 as an integer variable is declared.

Now so, far the scope rule is concerned the value of x is valid within this block only; that
means, it is valid that system.out.print ln x is correct. However, outside this block if we
try to access a system.out.print ln x then it will give an error and that errors can be
reported during the compilation time. Now, let us change this the last statement
system.out.print ln x; that means, we are trying to print it although it does not have the
scope now save the program and run this program and let us see what will happen. So, it
will give an error because System.out.prinln(x) the last statement in this class has out of
scope the x does not. So, it is basically a compilation error.

244
Now, again if we make it commenting the program and then we will see this program a
will be compiled successfully and also executable save this program ok. So, the program
is now compiled successfully earlier it was giving an error now the program will give the
result that it is x is=10. So, you can understand the scope it is a very simple example, but
it is understandable that: what is a scope of a variable inside a block. So, this is the scope
in a block.

(Refer Slide Time: 16:39)

Now there is a few more example. This is another example, you can see and how you can
understand also what is the scope of this example. Now can you tell me what is the scope
of this example; where x is the variable for which we want to discuss the scope.

Now, if you see here int x=0 it is declared within the for the loop this means that this is
the scope of x within the for loop only. So, within the for a loop, there is a print
statement which prints the value of x it is, but outside of this, for loop, if you attempt to
print it will give an error. So, let us uncomment this one and then run this program then
you will be able to understand that it will give a compile-time error because here the
statement it is out of scope.

So, here the x the scope of these values variable x is within the for this loop. So, it is an
error is the definition that the scope is not there; now again comment it run the save the
program and then run this program here no compilation error and run it will print
basically for loop will be executed successfully in this case.

245
So, for loop is executed you can see it. Now how you can change the scope rule now let
us come to another example so, that we can see how the scope can be increased here. So,
is the next example similar to the last example.

(Refer Slide Time: 18:01)

Here you can see int x which declared outside the for the loop this means that the value
of x is spread throughout the for loop as well as outside this for loop also. Earlier when it
was declared within the for it was only scoped within the for, but in this case, the scope
is the entire program. So, this program is self-explanatory as we have already understood
about it. So, this is about the simple concept of scope and fine. So, let us discuss one
more example which has the different contexts of the scope let us run the program 5
points 5.11 yeah fine.

246
(Refer Slide Time: 18:47)

So, this is the one program; now let us quickly examine this program watch this program
little bit here x and y are the 2 variables declared and the 2 variables have a different
scope. So, for the scope of x is concerned as it is declared in the main method this means
that the scope of this variable x is the entire method.

So, when you have from this method the value can be accessed on the other hand. If we
see the int y 20 which is declared within the block with under this block under a; that
means, the scope of this y is within this block. So, in the statement after
System.out.println() x and y the next statement is valid because it will be within this
scope. However, outside this y=100 it will give an error.

Now let us run this program and then we can see that it is giving the compile-time error.
So, all these errors will be reported during the compile time; that means, Java compiler
will check the scope of all variables for you. So, if there is an error in the scope then it
will report it the competition will not be successful. So, this is the compile-time error we
can say.

Now, if we comment it then definitely because the scope is now as closed and then it is it
will work perfectly. So, here no compilation error program will give the output according
to the program ok. So, we can understand the concept of scope here. Now, there are
many more things about the scope we have discussed the global variable idea in Java
program, Java does not support the declaration of the global variable.

247
(Refer Slide Time: 20:37)

However, the concept of global variable is by means of the concept of a class variable; a
class variable and then instance variable as we have already learned about it. Here, for
example, x y r these are the instance variable because they are declared as simple as a
type; on the other hand if we declare a variable with a skiver static then it is called the
class variable, in this case, we can see the circle count is an example of a class variable.

So, we have declared here one class variable namely circle count and then three instance
variable x y r and these are the usual code of the constructor of the class circle. So, we
have already discussed is I do not want to discuss it more and the two methods
circumference error as usual.

248
(Refer Slide Time: 21:27)

Now, let us come to the main method here; now you have to just watch the main method
a little bit carefully. So, in the first statement, we create an object of the class circle the
name of the object is c 1 and it will print the c 1.circle count. Now here once the object c
1 is created it will call its constructor. Now, here it is the default constructor. So, if you
go to the default constructor then you see in the default constructor here in the last
constructor that we can see. So, it will basically it will initialize all the instance variable
as 0 0.1 0.00 and 0 point 1 x y and r and the circle will be increased by 1.

Initially when we create when we define this circle count be 0. So, the global variable is
initialized as 0 and after this whenever the constructor is called for this it will increment
this one. So, now, let us come to the main method here again yeah. So, once the circle c
1 is created so, c 1 has the value circle count this means that if we print in this it will
print the value 1. On the other and next c 2 create an object. Now it will call another
constructor 5.0 which is the second constructor in the line of different constructors are
here.

So, public circle double r here also circle count++ that mean it will increase the circle
count by 1. So, after the c 2 object is created in the main so, the circle count becomes 2.
So, it will print the 2 and similarly circle c this is the 3rd constructor the 1st concert I
should say it will be invoked to create the circle class object c 3 and then c 3. And, then
circle count, in this case, will be again in increased by 1 and then here the fine right

249
circle c this is the 2nd constructor right this one now in the 2 now let us run this program
and then you will be able to see the output.

(Refer Slide Time: 23:33)

So, where for each circle an object is created once the circle object is created the static
variable will be processed according to the construction of the object and then it will
basically run it will print the current value of this one. And here we can understand that
the circle count is a global variable look like for all instances of the objects there are only
1 instance of this variable. So, here we can see the running of the output is basically 1 2
3.

Now let us switch to the program again and you can see we are just giving to the last
statement which has been commented here, I just removing the comment here let us
uncomment this statement yeah up uncomment this statement fine. Now, comment it
now little bit if bigger the window here fine yes now if we see the right.

250
(Refer Slide Time: 24:33)

So, after creating this c 1 circle right one and we are now in this statement now can you
tell me what exactly the value that it will print. So, here in the first object circle count
has been created 1 2 3 and then when you are come to here. So, the circle count for this c
1 is 3 and again 3 and 3. So, basically, the latest values of the circle count will be
accessed. So, it basically indicates that let us say the compile this program and run it. So,
here in the last statement, we will print the value of circle count which is the ultimate
value after the end of this program.

So, here you can see it printing the 3 3 3 this is the latest value after ah. So, it has
basically one instance and then one it is updated by any object it will be reflected any
other object which basically has the access to this value. Now so, this is the idea about
the static variable concept likewise there is a concept of class method and instance
method our next program will illustrate the concept of these two methods in a Java
program the class method and an instance method.

251
(Refer Slide Time: 25:45)

We have already discussed that a method is an instance method in order to execute this
method an object is required. So, via an object, the method will be called. On the other
hand, the class method is a method which does not require any object to be created the
method can be called itself.

So, this example basically to illustrate the concept of class method and instance method;
now let us here all the circles are basically instance method because, whenever you have
to create an object all these constructors will be called automatically, say they are by
virtue of default that the instance method. Now we declare one method let us go here the
circle figure public circle bigger the 2nd years. Now, this method little bit bigger the
window yes yeah so, fine.

252
(Refer Slide Time: 26:43)

Now, is the 1st method we can see bigger. So, this is the method public circle bigger
circle c. So, the method will basically argument will be an object circle is the c.r greater
than r return c; that means, that c is a bigger circle else return these that mean the current
circle. So, this is the one simple method and this is called the instance method.

On the other hand another method bigger is an overriding method we have discussed, but
this method is different from the previous method by two things; one is called the static
keyword the 2nd one has the static; this indicates that this method bigger is basically the
class method and also it is different from the argument point of view. Earlier only one
argument whereas, this is the two arguments all arguments are of type circle type of
objects.

The code is like this is a.r greater than b.r return a then a is a bigger circle else return b.
So, it will basically return that is a return type is a circle here in this case. Now, let us see
the main method here we create an object 2 object, 3 objects, 4 objects here of course.
Anyway so, 1st two objects are type class circle a b and then here we can see the b
a.bigger. So, basically, a bigger method is invoked with reference to the object a. So, it is
an instance method, on the other hand, the second call.

So, the bigger method is called with reference to an object it is a circle in terms of
circle.bigger so; that means, without creating any object this method is called. So, this is
an example of invoking the class method. So, here the two invocations the instance

253
method and class method and it indicates that the way of the class method works
differently than the instance method like this.

So, so this is an example of an instance method and class method ok. So, these are the
main concept those are there in java so, far the static scope rule is concerned. Now, let us
switch to our demonstration to give the execution of recursive program we have already
discussed while we are discussing the theory is that recursion recursive program writing
in Java. So, let us first run the recursive calculation recursive way calculating the
factorial.

(Refer Slide Time: 29:09)

So, this program is well understood I believe. So, here factorial is a method which is
defined in the class recursive factorial and then recursion is basically following the
recursive definition of factorial calculation the code is like this. Very simple n
factorial=n star factor n minus 1 with termination conditions that 0 factorial=1.

So, this is the implementation of this factorial definition of n; now in the main method
we create an object of type of the class recursive factorial here and then pass the value to
this subject from the keyboard as an input and then we call this x.factorial x.n; that
means, then we call the method in these subject of the class recursive factorial and run it.
Now let us run this program quickly you can understand that how it will run recursive
fine.

254
Now, as it is an input to be passed because r 0 is there. So, we should give the input say 5
right if we run this program again with some say larger value say 10 it will also execute
for you yeah. So, it is like this, but it cannot take a very large number say for example if
we say 100 you will see whether your program is now. So, a factor of 100 if 0 it is giving
it is because it is out of the pound of this one. So, in that case, an integer has its own
limit. So, if we declare say long integer instead of int it may take some larger values
anyway changing this we can change this one, but we have to changes for that it is later
then exercised for you. Now, let us come to another recursive program to print the
Fibonacci sequence.

(Refer Slide Time: 31:01)

So, this is the program we have already familiar with the program that we have discussed
in our last module and. So, here again, the recursive definition of an nth factorial is
basically n minus 1 factorial plus n minus 2 factorial and then termination condition is
that 0th factorial=0 and then 1 factorial is 1. So, these are the 2 termination condition
followed by the recursive definition it is the same as writing the factorial we create an
object of type recursive.

Fibonacci here is the class where we have defined the recursive method Fibonacci and
we call this and this for loop is basically print in succession all the Fibonacci number till
the x.n this is the user different number that up to which the Fibonacci number you want
to print.

255
Now, suppose you want to print up to the tenth Fibonacci number. So, we can run this
program with passing input; here input needs to be passed through the keyboard let it be
10 and you can understand that how it will print 10 Fibonacci numbers in the Fibonacci
series 10 ok. So, it prints the first 10 Fibonacci numbers in the few Fibonacci series. So,
this basically the recursive now let us come to the GCD calculation that we have
discussed in our theoretical class.

(Refer Slide Time: 32:25)

So, this GCD calculation basically has this kind of recursion rule is like this one and we
have implemented there is a few more termination condition. Now, you can see in case
of recursive factorial only one termination in case of Fibonacci there is two termination
condition. Whereas in case of GCD is a couple of termination condition there and all
termination condition followed by the recursive call so, in this case, recursive call gcd
mn mod m. So, this is as per the recursive definition of this one.

Now here two integer values are to be passed and then Java program will call for this
recursive function which is defined here as a gcd and we call the gcd with the two value
passed to it and it will call. So, g is an object of the type this class is created and call this
function and then it will execute a let us run this program so, that you can understand
about its execution ok. First, let us see enter 31 and then 13. So, this is 2 input you have
to give it give 2 input 31 and 13 13.

256
(Refer Slide Time: 33:39)

Now you can see that GCD is 1; now let us run this program with say 33 and 11 you can
understand that the gcd that value it will give you right. Even if you give you 11 and 33
also it will work yeah, now if we give 0 and say 100 you can understand that what is the
gcd of this number 100 so, it will print the 100.

Now, if you give. So, this is the way that the GCD and with this function is a call for
integral value only you should pass always integer if you give some non-integer value it
will report an error.

(Refer Slide Time: 34:25)

257
For example, if we run this program passing say non-integral value it is not acceptable to
the run time in, but as in Java run time invertise say giving an error. So, it is basically
you have to give the integral value always. Now so, we have learned about factorial
calculation; so, factorial calculation, Fibonacci series calculation, GCD calculation like
this one. So, the most important thing that you should understand how you can cast a
program by following the recursive definition.

(Refer Slide Time: 34:53)

If every program has its loop all this program has its counterexample of recursion
actually. So, if a program needs to be solved by means of some looping construct then
the same program can be solved by means of loop recursive version also. Now let us
have a quick look of this simple example you can understand this is the program we have
declared recursively. So, it basically here is my method is a recursive method which is
declared in the class demonstration under 517 and the method has the termination and
one important thing is that every recursive function should have termination statement.

Without termination, the recursion will go on infinite execution never terminate this is
not desirable. So, every recursive program should have in this case we can see that
counter recursive is 0. So, along counter is not=0 so, along counter is not=0 it will go on
counting and in this case my method whenever it will call first time it will print the value
of count and then my method call will be called again with reducing the value of counts.
So, if we pass say counter value it will call subsequently less counter so on so on.

258
And then print all the 10 counter and when the recursion is over it will come to the
previous counter value. So, now, if you see whenever before recursive call it will pin and
then on recursion, it will pin some values and go on printing. And then let us see exactly:
what is the output of this call. So, if we call this recursion with 10 as a value as counter
how it will do it; I can explain that why this output is where you can also explain that
how this output is happened to this program.

You can see here the two series of statement because of the two print statement and then
recursion is going on printing this one and then recursive call and when the recursion is
back from the loop, it is again starts this one. So, there are two series of the statement
and the recursion is the there actually recursion exhibition for use a stack it basically
before terminating recursion it goes to the call of the recursion so on. So, that is why it is
there. So, this is the one example now let us have the quick look of another example for
your own practice.

(Refer Slide Time: 37:11)

So, again you can learn it from these series in the same line of the previous example one;
you can guess that what input it should give it again p is the method which is defined
here recursively. Now let us run this program on it after the execution of this program
with the value of p as 5 here we have do not have to value 5 it will print this one.

Anyways so, regarding the scope, the control structures and then recursive program
writing is a matter of practice. So, I advise you to practice more and more programs in

259
this line so, that you can learn it. For your own practice, if you need the program all
those courses that we have given here a demonstration you can have it, you just send me
to send us a request. So, that we can send it to you, thank you very much and have fun
for the Java programming more.

Thank you.

260
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 13
Inheritance

So, in this lecture we will discuss one important object oriented paradigm is called the
Inheritance. We have discussed the encapsulation, then inheritance is another important
object oriented paradigm; in today’s lecture we will discuss about the Inheritance. So,
first we should learn about the concept and then how this concept is basically
implementable in Java program.

(Refer Slide Time: 00:41)

Now, inheritance is very common concept is a biological term although and you know
exactly the inheritance means basically inheritance a child children inherits from its
parents order it is the (Refer Time: 00:54). So, the concept it is like this and then single
inheritance means, if it inherits from on only on entity and multiple inheritance means if
one entity inherits from the multiple entities.

So, concept it is there the both single as well as multiple inheritance and then inheritance
can be also hierarchically with multiple levels; so, multi level inheritance. So, children
inherits from the parent, grandchildren inherits from the children like this one.

261
(Refer Slide Time: 01:23)

So, these are concept actually very common it is there, but so far the object is concerned
the concept it is also there. Here for example, if we consider animal is a kind of object
then animal has the different other type of objects. So herbivore, carnivore like this one
so, here animal is a general whereas, herbivore is a special and if we see the lion and
hyena they are more special.

So, from generalized to more specialization is the concept of inheritance and this is
called the IS-A concept; that means, lion is an animal, hyena is an animal; so, is IS-A
concept. So, they are followed they are basically related to the IS-A relationship. And
there may be many hierarchy; that means, that hierarchy means it is in the different level.

262
(Refer Slide Time: 02:11)

So, this is a concept of there now, here inheritance in Java is very useful for many
reason. The first reason is that using inheritance we can create given a class another
class. So, the concept of this thing is very important here.

(Refer Slide Time: 02:27)

Now, so this concept is basically given a class we usually call it is a super class. And, if
we can create another class from this class then this is called a sub class. As an example
here we can see Vehicle is a super class whereas, CAR and the TRUCK are the two sub
classes. Similarly, FireTruck is another subclass of the class TRUCK. So, here TRUCK

263
is the super class of the sub class FireTruck. So, this basically says that we can create the
number of classes inheriting from its super classes.

Now what is the concept of inheriting? We will come to this discussion about what
basically a sub class will inherit from its parent class. Now, this inheritance concept is
very important in Java program, it is because reusability. So, if we have a class say truck
then we can share this code of the class truck, and then we can implement some other
code in FireTruck So, it is basically code share ability or the reusability even the
maintainability, the code maintainability is very important aspect which can be done
using the concept of inheritance.

(Refer Slide Time: 03:43)

Now, how the inheritance of a class is possible. So, there is a syntax in Java program.
The inheritance in a class is possible by means of one key word called extends. So, here
the class this is the name of the subclass which basically you want to inherit. And this is
the name of the super class that from here you have to inherit and this is basically the
code of the subclass in addition to the code or the method or members which is there in
this subclass.

So, here basically all the codes which is there in super class is also accessible here in this
method. So this way, basically the idea of the code readability come into the picture. So,
this is the idea about that these things can be done using inheritance. Now let us see
some example so, that we can understand about this idea about the inheritance.

264
(Refer Slide Time: 04:39)

Very simple example, that we are going to discuss about say suppose there is a class
called the 2D point. So, 2D point is a class and we want to inherit another class called the
3D point. This means that 2D point, if it has some members and methods then all these
member and method may be is available to this 3D point or we can say that some method
can be overridden; that means, it can be redefined in this method. Now, let us see one
example. So, here is basically the statement of a class Point2D it has two members x and
y and display is the method.

So, these are the composition of this class. Now, here Point3D which basically inherits
point this is basically Point3D inherits Point 2D. So, it is so it should be corrected this is
Point2D. So, the Point3D extends Point2D; that means, Point3D inherits from the class
Point2D. And, here we can see we declare integer z as a new elements on it. This means
that for this class Point3D all these things which is there also use accessible here. So, this
means that x y and z all the three members are available to this or members of this class
Point3D. How again you can note it that display method which is there in Point3D also it
is there. However, the method which is defined here and there they are different. This
means that this display overrides the super class method display.

265
(Refer Slide Time: 06:25)

Now, on the other hand if we write say display1 and display2 then the two methods are
there and here with this change, what is the idea is that like x y is available to this class
Point3D. Similarly, display1 is also accessible to this method this one. So, this basically
a Point2D is a generalization concept is a general, then Point3D is a special one; that
means, it has many more things other than the Point 2D itself.

So, this is the concept of inheritance. And this is obviously, an example of single
inheritance and as it is a very simple example we usually call it a simple inheritance
example ok. So, this is the idea about the simple inheritance.

266
(Refer Slide Time: 07:19)

Simple inheritance and here is a main method that you can declare. Now if you can look
at this method little bit carefully you will be able to see these are the objects that we have
created for 2D class Point2D and Point3D. And these are the basically initialization.
Similarly, here the initialization of the point3 there is basically point2 ok. So, this is
basically initialization of point2. Now, here if you see in P2 being a point in class
basically Point3D x y is accessible.

So, this is the idea is that by means by virtual inheritance all the members and methods
are accessible with the object of subclass. So, this is an example of the simple inheritence
that we have discussed. Now, we quickly discuss about what are the different type of
inheritance that is possible in the Java program.

267
(Refer Slide Time: 08:23)

Now, this is an example of single inheritance. So, if we can derive a subclass from a
super class these are simple inheritance, we can say other than simple inheritance that
they are may be more than one class can be derived from the same class. So, it is called a
multiple single inheritance. For example, here subclass 1 is derived from the super class,
subclass 2 is also derived from the super class subclass3. So, this is another type of
inheritance and again a sub class can be derived from a super class another subclass can
be derived from another subclass (Refer Time: 08:56). So, this also is called a multi level
single inheritance.

Other than this multilevel single inheritance there is a concept of called the multiple
inheritance. Here for an example this class inherit from this and this. So, if a class
inherits from the two classes then it is the example of multiple inheritance. And, here is
basically the hybrid example here. for example; this class inherit from this one this. So,
these are single however, this class inherits from this one. So, it is called a hybrid
inheritance that mean both single simple as well as multiple inheritance are there.

Now however, the super Java programming is concerned all inheritance are not possible
rather in Java we have only single inheritance, multiple single inheritance, multi level
single inheritance are possible. Whereas, the other two are not possible Java does not
support multiple inheritance as well as hybrid inheritance.

268
(Refer Slide Time: 10:02)

Now, let us have little bit bigger example about inheritance maybe multiple multi
multiple single inheritance we can say. Here for example, Person is a general class and
then Student is another subclass which can be derived from the Person. Similarly,
Employee of say another subclass can be derived from the Person. Now, what is the
actual idea about this inheritance that can be understand about it? Here basically Person
may have some data as well as method of its. Here for example, these are the different
composition of the person. Now, let us come to the student it has another right and these
are another. Now what it does mean, that what it does mean that that the Student class
has all these things in addition to this one.

Similarly, Employee class has all these things in addition to this one. So, for an
Employee class all these things are available, for a student class all these things are
available. So, this is the idea about that by means of inheritance all the course which is
there; for example, these methods are nothing, but code can be accessible to this one. All
the codes which is there also accessible to the employee class so, code (Refer Time:
11:23) is there. So, by means of inheritance we can have this one. Now, here quick a
Java programming features our programming concept of this one.

269
(Refer Slide Time: 11:33)

As an example we can say about say a class Person that we have declared whatever the
idea that we have mentioned here written in a Java code like ok. You can relate to that
figure pictures, that we have shown in the last slide is basically related to this one. This is
a curve class Person is a general class and now Student class can be defined like. So,
having this person is to us then we can have the Student class which basically extends
Person class; so, it is there.

Next so, this way the Person class can be declared about and now here you can see here
the printData which is declared in this method, here is also used here to print the biodata
of the Student class like this one. Now so, this is the class Student which has been
inherited from the class Person.

270
(Refer Slide Time: 12:31)

Now, likewise we can have another inheritance the employee, employee also can be
inherited from the class Person who is basically has this one and whatever the different
methods are there we can declare here. So, this way the class Student and class
Employee is more what is called a code than the class person itself and inheritance is the
utilization of this one. So, once the all the classes are used then in your main class we
can use those things and you can process them.

(Refer Slide Time: 13:01)

271
Here for an example, we use the main method where the different objects of the class can
be declared individually as if they are the new class of their own. So, this way the single
inheritance is possible. Now, consider inheritance is like this is very simple not very
difficult to understand that is why Java makes the thing so simple. Only allowing single
inheritance and this inheritance can be gone into another level.

The same thing if I say suppose regular employee extends employee, then permanent
employee temporary employee extends employee. So, that other two different classes can
be inherited from the employee after the part employees inherited from personalization.
So, this way extension has no limit to any level we can go.

(Refer Slide Time: 13:51)

Now, here is another good example so, that you can understand about it. So, there are
many geometrical objects. So, all objects are of general type and then they can be a
special type. So for example, 1D object 2D object 3D object. On the other hand if we
consider the 3D object they are again different type, 2D object these are different type,
1D object is also different type. Now, further what is called the specialization also can be
done. For example, 2D object can be of the further specialization like triangle
quadrilateral and so on; quadrilateral maybe another specialization rectangle,
parallelogram this one.

Now, this kind of inheritance hierarchy; now if you want to create a program for
manipulating all geometrical objects so, first we can create the GeoObject which

272
basically has all the common attributes in it. Then whatever the special attributes slowly
can be added into its inherited classes. And then finally, the classes at the bottom level
can be obtained, they are basically the more refined or more specialized class that needs
to solve your problem. So, this is a concept that is followed there and now you can write
the programs for implementing all the type of objects that we have listed in a this
taxonomy only. So, this concept can be extended like this one. Now, we will discuss
about one concept the method overloading.

(Refer Slide Time: 15:13)

In the example of Point 3D inherited from the Point 2D, we have discussed about method
overriding; that means, that they are there is a method display which is basically defined
in both the classes. If we declare a method which is already defined in a super class then
the method called the overriding method. That means you have to override the method.
So, this concept is called a method overriding. So, method overriding it is basically
required that the method that we have declared in a super class can we can sometimes
needs to be redefined here.

273
(Refer Slide Time: 15:53)

So, if we want to do that if re-define then we can do it like this one. So, this is again
continuation of the previous example that we have discussed about. Here the display
method which is declared here these display basically override these display and then we
can use it here in this program as we can see it is here. So, this method as we can as you
can see here this method as you can see here.

So, Point 2D p is a point of 2D class and Point 3D q is a point of 3D class. And, here you
can see x is another class which we have created which basically up casting; that means,
q is a point of 3D, but we can cast into 2D using this kind of special features are there.
So, typecasting we will discuss details here later on. So, then x dot display then this
basically we will call the display method of this class although in q it is overriding. So, it
is like this way we can have the access of this one this concept is called the dynamic
binding.

So, dynamic binding is the one kind of runtime what is called a scope rule. So, scope will
be decided from which, because if we cast with others then binding will be different and
so on. So, these the dynamic a binding will be demonstrated in our practical class; so,
that we can understand these features more clearly. So, this is the idea about method
overriding it is there.

274
(Refer Slide Time: 17:27)

Now, regarding this inherited inheritance concept one thing that we should note that a
subclass object can refer a super class variable or method if it is not overridden. That
means, all the methods and variables are accessible to the subclass if it is not defined in
that class itself. On the other hand a super class; that means the reverse is not possible.
That means, is super class cannot access any variable or any method which is defined in
the subclass.

So, one way traffic it is actually. So, we can access in from the subclass platform only,
but super from the super class platform other than the method are variables defining the
super class we cannot access anything from the subclass.

275
(Refer Slide Time: 18:19)

Now, there is another very important concept, it is called the super keyword which
basically used for many purpose. So, super keyword has the many implication in this;
using the super keyword in Java one can use one can refer immediate parent class
variables. They are basically instance variability is there; super also this keyword also
can be used to invoke parent class method and super also can be used to invoke parent
class constructor.

So, there are many use of this super class. In our subsequent slides we will see how the
super class can service the three different facilities: referencing variables, referencing
method and referencing the constructor those are there in super class.

276
(Refer Slide Time: 09:15)

Now, this is an example if you can look at this example little bit carefully, you will be
able to understand that this is basically an example using the super keyword, where we
can refer a parent class of a instance variable. Now, let us see in this example we can see
this color is a variable which is declared in a class animal and dog is another class which
extends animal and in the dog class we can declare again the color variable. So, this
color is basically overridden variable; that means, this color and this color they have the
two different scope. Now, here if we see in the super class the variable color is white
value is white whereas, in dog it is black.

Now, in the print color method which is basically new methods in the class dog it
basically if we refer this color then this refer to this color. But, if we want to mention that
this color I want to mention which belong to the super then I should write super.color.
So, this super dot color will refer to this value whereas, this color will refer to this one.
Now, having this kind of concept now let us see this is basically on the main program.
So, here d an object of type this classes and then d.printColor we will call it and
whenever it call it then it will basically show the output which will look like this. So,
output is because of this first print color black, because this one and then super color
white.

So, these are the two output is there. So, this is a concept that super keyword is used to
reference the parent class instance variable. Now, this is this has another also use it is

277
called like the referencing the parent class variable, the super also can be used to
reference the parent class method. The method is the concept is same as the previous
one. Now, again look at this example here the animal is another class which has the
method eat. Again in the dog which is an inherited from the inherit in subclass of the
super class animal, it also declared eat.

This mean, that this method is basically an overriding method than this one. So, this
method a has its own which has the scope within the class dog and this method has this
kind of print statement. Now, bark is their totally new method belong to this and work is
also another method which is defined this. So, bark and work are the newly added
method in the class dog. Now, wherever now you see the work method which is a new
method in the class dog it called this one. Now, is super.eat() you can understand what it
does mean. It means that this is the method of this whereas, bark is the as usual because
there is no resolution and then it is basically this one eat.

So, these basically resolve the namespace. So, eat method belongs to this if it is prefixed
by super dot and these are the method it is there. So, using this super method we can
refer that this method belongs to whether it is a super class method or belongs to the
subclass method if it is overridden. And, this is an example of this one very simple you
can understand d that dog object is created and d.work(), if we call you can guess that
what output it should give it you; obviously, you can check that the output that it should
give you this one. So, dog work super. Eat() it is basically eating then, bark it will
barking and then eat again eating great.

278
(Refer Slide Time: 23:17)

So, this kind of output you can see it if you run this program. So, this concept is the
concept of that using super class we can resolve the parent class method then the base
class method.

(Refer Slide Time: 23:29)

Now, this is another example of use of super class is basically invoking the parent class
constructor. We will use this kind of construct frequently in our subsequent program. So,
we should understand it very carefully again this is a super class, this has one constructor
animal. So, this is the super class constructor, dog is another class is an inherited from

279
the super class in animal. So, it is a subclass of animal and here if we see dog is a
constructor. And, this draw constructor we use the super.

This means that if we use this say means dog will also call the super class constructor
that is then animal is called here. So, is basically if we writing this one means it is a
super class constructor is called here and then finally, dog his own method. So, this
means that in this constructor we have the two print statement this and this as well as this
one. Now, if we run this test case and then if we run this one then you can see that this
kind of output you can get it. Animal is created and dog is created because of these two
things are there.

So, this is the concept of the use of super here the super keyword; so, that if we write
super within parentheses this indicates that it will basically call the parent class
constructor. So, super we can see that super is a very important keyword. We have used
similar kind of key word this earlier and then another key word new also earlier. So,
those new these and super are very important keyword, we will understand also few
more keywords later on.

(Refer Slide Time: 25:15)

Now, this is another example of invoking parent a parent class constructor using the
super. This example similar to the previous example, previous example was pretty
simple. Here you can see Point 2D is the super class, 3D is a subclass and here whenever
we create a constructor Point 3D we will construct this one; that means, we can. Now,

280
here again you can note that in Point 2D there are two constructors. So, super if we call
then which constructor it will refer to, actually it depends on what kind of arguments are
there.

If we call this kind of argument then this is basically reflect to that that constructor who
is matches its argument. For example, here super is a default constructor. On the other
hand we could write that super using these are the say three different value; then that
constructor will be called here. So, it depends on so using the parsing proper argument
which matching to that constructor, now in the super will refer to that constructor. So,
this is the idea about the super constructor is there.

(Refer Slide Time: 26:23)

And whenever we use this kind of inheritance one very important concept is that
dynamic method resolution. So, this concept is basically runtime polymorphism if we
create many object, many object many object finally, which belongs to the method
belongs to which object it little bit confusing. So, that confusion can be avoided by
means of ok, if you can understand this concept little bit carefully.

281
(Refer Slide Time: 26:45)

Now, one example can be given so, that you can understand about that which binding;
that means, which are the method reflected to a particular call. Now, we can consider this
example here. So, Bike is a super class, the Splendor is another subclass which has the
run method, you can see run is overeating method here. And, after this declaration of the
two classes super class and subclass we have the main method declared here ok. So, it is
very simple, so b1 is an object of type this class; that means, if we run b. run() so, it will
run this code method.

On the other hand here bike b2; that means, we create an object of type b2 and b2.run()
the resolution is quite see that this method will be run in this case. On the other hand now
come here this is little bit tricky. Now, here we create an object by means of this memory
allocator then Splendor, but actually we cast it. And, then we store it b3, but its type of
the Bike object and then if we call this b3.run(). So, then which method will be called
here. Actually in this case as it is the object of splendor although it is b3 run, we should
not confuse that this b3 as the object of class bike then this run is this one, it is not like
that and it is basically Splendor; so, it is run.

This means that dynamically so, b3.run() it changed from this method to this method. So,
it is called a runtime polymorphism and it has many utilization, those utilization we will
discussed when discuss about the packages and others. So, if we have to store many
objects in an array and then objects of different type then better idea is that that array can

282
be declared of the super class object type x. And, then if it is declare super class any
subclass object can be put into that or array and it can be process in y irrespective of the
different object. So, this is the one good example of the runtime polymorphism in the
Java.

(Refer Slide Time: 29:05)

Now, this is another example is you can guess that what output it will give it to for you.
So, A this is a super class, this is a derived class, inherited class, subclass and this is the
main method and you can understand that how it can. So, you just look at this point and
then you can try to give the answer then you can understand that whether you have
understood it or not.

So, if you run it this program and it will give this kind of output you can say and that you
can resolve it how it is basically giving this kind of output. So, this basically the idea
about that if inheritance is there, you have to little bit clear about that how the different
method is called there.

283
(Refer Slide Time: 29:51)

Now, I will quickly discuss about two more important concepts in Java: one is called the
abstract class and another is the final class. A class can be declared an abstract if we
declare an abstract class then its all method and all data member also can be declared an
abstract actually.

(Refer Slide Time: 30:09)

So, abstract class is basically the class which does not have any method to be defined
clearly or the method can be kept as a void that mean without any code. Now, abstract

284
class as it does not have any code or any other thing. So, that any object of that class
cannot be created.

(Refer Slide Time: 30:31)

So, it has certain properties like and abstract class it is declared by means of a specifier is
called a abstract. And, it can have again abstract method and non-abstract method. All
the method that we have discussed so far, non-abstract; if a method is prefixed with the
abstract keyword then it is called the abstract method. It cannot be instantiated this
means that no object can be created for an abstract class. And, it can have final method if
the abstract class has a final method then that object cannot be that method cannot be
overridden in its derived class.

So, this is the idea about the abstract class and then so, abstract class is like this. So, if
we can declare a method no objective is can be created, but it can it can be used to derive
many classes from it. It is basically gives a template, template means this is a
generalization a concept that this one whose ultimate implementation will be done when
we derive the subclass.

285
(Refer Slide Time: 31:41)

Then the final keyword: the final keyword is very one is a strict keyword we can say that
if we can declare a final, then this final class cannot be used for inheritance. So, no class
can be derived from the final class that mean final class cannot be a super class. And, in
addition to the declaration of a class as a final we can declare any variable any method in
a class as a final also.

If we declare a variable as a final so, that variable cannot be overridden in any derived
class. And, if a method is declared as a final so, same method cannot be overridden in
any class objects. So, final in the sense final that it is basically no more implementation
in any derived class is possible.

286
(Refer Slide Time: 32:31)

Now, here is an example here we can see the class Bike is declared as a final. This means
that this will give an error because it is not permissible. So, this is an error ok.

(Refer Slide Time: 32:49)

So, we have discussed about the basic concepts that is related to the inheritance of
classes in Java programs. Now, there are many more questions that can be answered in
subsequent classes. For example, can you inherit a class from other class which is
defined in other package? Now, that here concept of package first should be learnt; so,

287
that we can give answer to this question. And, then information hiding that is on another
pending job that we will discuss in our next lecture hours.

Thank you very much.

288
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 14
Demonstration – VI

Let us have a quick demonstration on the topics that we have learned in the last module.
Our last module was on was based on the inheritance in Java. So, today we are going to
have a quick demo on the topic that we have learned in the last class.

(Refer Slide Time: 00:37)

So, to in today’s demo we are going to cover the basic concept of inheritance, namely the
simple inheritance and then we will discuss about multi-level inheritance, we have
discussed about the super keyword which used to avoid the names space collision, the
super keyword use of the super keyword to invoke the superclass constructor and then
using the super keyword we can reference to some variable of the superclass. And then
overriding is an important concept in any inheritance, so method overriding will be
discussed.

There are two more keywords namely; abstract and then, the final keyword that is come
on the way of inheritance. So, we will discuss this one. So, these are the topic that we are
going to discuss in this demonstration lecture. Now let us have the first demonstration on

289
simple inheritance. So, how is a class can be needed from another class we can see it let
us have the demo.

(Refer Slide Time: 01:45)

Now, let us watch this program here in this program we see a class namely class A is
declared. This is the superclass in this case, this class has 2 members i and j and it has 2
one method called the show i j printing the values of i j i and j in this class.

Now, in the next class the class B which basically inherits the class A. So, class B
extends A and we can see that in class B we declare one variable called the k of type
integer and then class B has its own methods. So, k printing the variable k in this class
and also it has another method sum, it will print the value of i j, which are inherited from
the superclass and the value of k, which is in its own variable.

290
(Refer Slide Time: 02:47)

So, these are this is the inherited class B and as you know class B therefore, by virtue of
inheritance have the access of both ij and the method. So, I j which are declared in class
a as a default access specifier as there in the same file they are readily accessible by
virtue of inheritance as well as default access specification. Now let us have that main
class the main class here we name as demonstration_6 1 and in this class, we create 2
objects of type class A and class B namely super Ob and sub Ob.

So, 2 objects of 2 different classes are created and in the next statement we initialize the
values of i and j in the superclass objects and then also print, I call the method of so ij or
the superclass object. And in the next statement we see we initialize, the subclass object
ij and k as 7 8 9 and then we display the values of show i j, show i j as it is accessible to
sub Ob ib by means of the inheritance and then also we call the show k method of thus
subclass objects sub Ob and then we print it.

Now, let us have a quick demo. So, you can see that this is all legitimate access, we can
use this thing and it will give that results that we have initialized and finally, it will also
display the value accordingly. So, we run this program as using javac and then execution,
so fine. So, it will work because there is no error in the program and it will print
accordingly. So, this is the value that this class will print for us ok. So, this is the first
example showing how the simple inheritance in Java can be done.

291
Now, our next demonstration is based on the initialization of the subclass object by the
constructors that are there in the superclass.

(Refer Slide Time: 05:01)

So, this demonstration will tell will go show us how we can initialize a subclass object
using the constructor which is defined there in the superclass. Now let us have the
program where we can see the class Box is a superclass class having 3 data width height
and depth they are declared as double. And, the box is the constructor it is a superclass
constructor default constructor and in addition to this default constructor there is one
more constructors is initializing the different values in the class objects and also it has
one method volume it is a simple multiplication of the values of the objects.

292
(Refer Slide Time: 05:49)

So, this is a class superclass. Now we derive one class give the name as box weight it is
an inheritance of the superclass. Box here in this case and in addition to w h and d which
are there in the box class we define another data weight of type w see this is the data of
its own and then we declare a constructor in this class box weight which we pass the
value there and then initialization if this one.

So, we can create an object of superclass as well as subclass here in the means class we
can see. The main class is demonstration_62 a. So, we create an object my box 1 of the
class box and then also we create another object my box 2 of the type box weight which
is the subclass in this case passing the values 2 3 4 and 0.076 as an argument we
initialize the object. And then finally, we print the volume for the object.

So, there we can see we have created a subclass object, we have created a superclass
object; although no problem. For the superclass object, there is 2 constructor. So, in this
example, the default constructor will be called whereas, for the initialization of the
subclass object the constructor only constructor here that will be called. So, this program
will be executed and let us see the execution of this program. So, this program (Refer
Time: 07:22) you successful compilation and execution. It will print the volume of both
objects my box 1 and my box 2 which we have created yeah.

So, we can see that 2 objects are successfully created one object is that a subclass object
another is the superclass object. Now, we have shown in this the example that how the

293
subclass object can be initialized. Now we are going to have another illustration where a
subclass object can be initialized with the help of superclass constructor. So, this is the
one program in this direction it is simple as usual earlier the superclass remains the same
wherever we just redefine the sub superclass subclass object in the following let's go
down yeah.

(Refer Slide Time: 08:33)

So, here you can see we just have the 2 constructors, one is the default constructor in the
subclass object subclass the box weight the default and another is the width some values.
Now in case of default constructor we see we call super within this one, this basically
called the superclass constructor in the superclass namely box ok. So, it will call this one,
so it will initialize with the 0 0 0 values to the members.

294
(Refer Slide Time: 09:03)

Now, again the super w h here basically it is the superclass constructor, which has the 3
arguments that is required and then we call this superclass constructor to initialize this
using the box weight constructor here.

Now, let us have the same demo here it is the same thing we create 2 objects, my box on
for the superclass object my box 2 for the inherited class objects and then it is the same
program as earlier, only the thing that we have initialized with the help of superclass
constructor. Now, so in this demo, the superclass constructor is basically, super with the
certain argument. The argument which will fit with the superclass constructor will be
used herein the subclass constructor.

So, let us have another demo. It basically super use of the super keyword that basically
how we can refer a subclass object with the help of superclass variable. Now let us have
the demo 6.3. Now, in this case, we will see how the superclass variable can be referent
to the subclass variable like this one. We can better explain this now this is the subclass
definition class box, it is the same as earlier it has 2 constructors, the if the class
definition is same already that we have discussed here. Now, let us come to the
superclass object. It is also same, it basically has the weights and then the only
constructor here in this case.

295
(Refer Slide Time: 10:43)

Now, let us see the main class method here. This needs to be checked very carefully.
Here we define one object of subclass box weight, the namely weight box is the object
passing the parameter for it. Now in addition to this also we declare here another object
plain box of class superclass box here and volume is the volume to hold the volume of
this one.

Now, if we call the volume method for the weight box. So, it will call the volume
method in which is defined in the subclass and accordingly the volume will be calculated
now. So, it will be printed now so, that is all. Now let us come to the next one. Now here
we can see the plain box is equal to weight box. So, it is possible, here basically we are
referencing a subclass with the help of superclass. The plain box is a superclass object
and weight of box is a subclass object. This kind of assignment is quite legitimate; that
means, we can reference a subclass object name with the help of superclass object name
and next statement is also quite valid volume will be obtained for the plain box there.

Now, again you can see which method will be called here. It is basically the volume of
the weight box method will be called here. Now let us run this program 6.3. So, we can
see the volume that we can print here is the volume of the subclass object, but it is a
reference to the superclass object ok. So, this is the 1 demo. Let us have another demo,
this demo is basically planned to explain using the usefulness of super to avoid the name
namespace collision. So, basically, we can write overcome the name hiding using the

296
super construct. Let us 6.5 the demo yes, so this is the one simple program that we can
check it.

(Refer Slide Time: 13:09)

Now, here let us look at the program class A is a class declared here having an integer as
a variable in it and class B is inherited class from A and also see i integer is declared of
its own. Now here whenever by means of inheritance, the value the variable i both that is
there in the superclass is also accessible to the subclass, then it becomes a problem it is
called the collision, collision means both i is there ok.

Now, of course, according to the inheritance, it basically overwrites that mean the scope
according to the see this I, which is declared in class b is basically i of this subclass
objects not that one. So, this i, which is declared in class B in fact, heights the i which is
already there in A; however, we can refer both the variable and this reference is possible
using the super keyword.

Now let us see the constructor which we have defined for the subclass object B is like
passing A and B as the arguments. Now if I mention super.i this refer to the variable I,
which is there in the superclass object and similarly I, if we do not mention anything it
basically refers to the variable i in the same class itself that is here in the B. So, this way
we can refer to some superclass variable as well as the subclass variable this way.

297
So, super can be used to resolve the collision that is what happens in this case. So, the
rest of the program is very simple. So, this method we will print all the values those are
there in the subclass as well as the superclass to print statement is used for that and these
is the main() method, a sub-object subclass object is created and then we call the so
method, it will print the 2 values there ok.

So, for example, 1 and 2 will be painted here, 1 will go to the eye, the superclass values
and then 2 will go to the value to the subclass ok. Let us run this program quickly so that
we can see exactly whether it is running or not and then we can have the understanding
then that superclass can be used to resolve the name collision. So we can see that ok, so
it is it basically is successful so far execution is concerned. So, it works. Now, our next
demonstration basically to see how the coat shearing is possible, it is also a very good
example of the dynamic binding concept that is there.

(Refer Slide Time: 16:07)

Actually, it is a runtime polymorphism concept, it is they are during runtime it will


resolve which method is basically called here. Now here we can see first we declare one
class the name of the class is a cat and it has one method speak and then it basically print
this meaon statement here.

Now, another class which is basically inherited from that class cat is a subclass pet cat of
superclass cat. It has also the method speak and this method has this statement meow.
Now here you can see the 2 methods are defined, but it is a method overriding. Thus the

298
speak method in pet care overridden then, then the method that is there in the subclass
method cat. Now we declare another one class also an extension of cat it is basically
multi-level multi multiple it is we can say that 2 inheritances, 2 multiple single intents
we can say here because we another inherit another class magic cat from the class cat
and we can define one variable is a Boolean type no one.

Now, void speaks if no one, if it is true then it will call the super speak. Super speak
mean in this case, it will call the cat class to speak that is there in declare method
meaning in discussing it will spin meow and if it is false then it will call this simple
message. Now let us see how dynamically we can bind to this.

(Refer Slide Time: 17:47)

Let us have this program, this is a little bit tricky. You can see how these statements are
here. So, demonstration_66 is basically giving the idea about runtime polymorphism in
this case, but we will resolve it using the super concept here. So, here we create an object
of a subclass pet cat c 1.

So, that is very simple. Also, you create another object c 2, the magiccat and so C2 no
one we mention true; that means, if it is no one, it will spin the superclass method for this
c 2. Now, again c 2 speak. So, it will call the method here. Now c 1 speak if we call that
it will call another subclass objects that is the B met one. Now we can mets c 2 noOne as
false. So, it is now false and if we call again C 2 speak, then it will call another method.

299
So, it accordingly it will print meow meow and then hello cat. Now let us see the run the
program we will see exactly how it will work yeah ok.

Now, you can see this basically print according to the different states depending on the
concept it is there. So, this is one example here basically we can see how that 2 or more
classes can be inherited from one superclass. This also example signify this fact. Now let
us have another instance of multi-level inheritance.

(Refer Slide Time: 19:33)

Multilevel inheritance means if we can derive from one class subclass sub from subclass
we can derive another subclass. So, like this one the example of multi-level inheritance,
now, here let us see the class box which is already the same as we have discussed in the
earlier demonstration and also we used the box weight another subclass derived from the
class box. So, it is more or less the same as we have already discussed, now, here the
simple inheritance of 2 level.

300
(Refer Slide Time: 20:01)

Now, in the next level we inherit another, so we define another class shipment it is
basically subclass of the class box weight; that means, box weight is a derived class from
the class box and shipment is another derived class from the box weight. So, this is the
shipment is an example of multi-level inheritance. And again for the same concept, it is
also applicable here, the multi-level inheritance can be initialized by calling its
superclass constructor, in this case, box weight constructor.

So, super wh dm basically called the constructor that is defined there box weight, it is
like this way and it is initialization. Now let us come to the creation of objects.

301
(Refer Slide Time: 20:47)

So, demonstration 6 7 there is a program, here we can create 2 objects shipment 1 and
shipment 2 and then we can call this method it works and then, so let us run this
program. So, that you can see them in the different for the 2 different objects, which are
derived in a multilevel way can be used to create objects and then the different methods
in those objects can be accessed by a Java program ok. So, this is an example that we can
verify with the court, so that it is working correctly.

So, this is an example of multilevel inheritance. Now let us discuss the abstract class.

(Refer Slide Time: 21:31)

302
A class is defined as an abstract class, all the classes that we have discussed earlier
superclass they are they are with the access specification the defaults So, they is a
default, there is no other access specifier it is used here; otherwise, we can use some
other access specifier depending on its application. Now here we use one keyword called
abstract. If we specify an abstract keyword before a class then that class is called abstract
class. So, in this case, the base class is declared as an abstract and also one method if a
method is specified by a specifier called abstract then the method is called abstract.

So, in this case, a class is an abstract and in this class, one method is declared which is
also abstract. Even we can also declare a method without any abstract also is called a
non-abstract method, but in this case, let us have the method is now an abstract class. So,
what is the meaning of this abstract class? As we have already know learn about that, if
we declare a class as an abstract class this means that no object can be created for this,
but this class can be used to inherit some other class; means that an abstract class can be
used for superclass, but no object can be created for this kind of class abstract class.

Now, let us have the one example here, we can see class derived is a subclass of the
superclass base, so it is quite and if there are any abstract method, then in the subclass
the method should be declared and defined properly. So, the method if you see abstract,
whenever you declared abstract, no code need to be mention there, so there is no code, so
it is a blank. Now here you see in the subclass declaration we fully declared the method
fun and this basically includes on system pin statement it will basically pin this one.

Now, let us come to the main method here demonstration 6 (Refer Time: 23:40) now 6 8,
so here we can see, so here we can see, if we uncomment the statement like base b, new
b then, let us uncomment the statement and then try to run it and we will see what is the
consequence. So, this will give an error, because the base class here is an abstract class
and we are not privileged to create an object. As we can see the state the error during the
compilation base b, newly derived it is basically saying variable b is already defined in a
method mean like this one.

So, basically, abstract class cannot be instantiated you can see an abstract class cannot be
instantiated because it is like this one. So, let us uncomment comment it again now have
the next one base b, newly derived this is quite yeah. So, now, see we can have the
reference of base type by means of this kind of upcasting is quite possible there. So, now,

303
we create an object of type derived class but reference it through a base class object this
is quite possible and then we call the b.fun as it is there. So, this fun is basically the fun
method, which is declaring the subclass method. So, this program if it is run, then it will
give the output, so this is working correctly. So, this is a concept it is there, so far the
abstract class is concerned. Now again here that whether abstract class we have
understood that no object can be created.

(Refer Slide Time: 25:11)

Now, whether abstract class, can have any constructor or not. So, our next example
showing this thing that yes an abstract class may have its own constructor.

304
(Refer Slide Time: 25:25)

That means abstractor can be used to initialize the member elements if it is there if it is
not an object creation event. Actually, this constructor will be useful to initialize the
object of the subclass of this class because for an abstract class subclass can be created.
Now, here is an example where you can see how an abstract class can have its own
constructor and how the same constructor can be useful to initialize the subclass objects.
So, here we can see the base is an abstract class constructor here it basically prints the
same statement and the next is basically an abstract method namely the fun here. And the
see derived class is a subclass of the class base here and derived is a constructor of its
own it derives is there and void fun is the method which is basically an implementation
of the abstract method that is there in the base class.

So, here derived is there, although this constructor is not called; that means, superclass
constructor is not called here. I will tell you how this can be called here anyway. Now let
us have the demo about it so; that means, the constructor it is there we can call it ok. We
can just little change this program whether base class constructor can be called here in
this method in the derived class. So, you can do that yeah this program is running fine
yeah, so it is running.

305
(Refer Slide Time: 26:51)

Now, let us come to the code again switch to the code. Now we can call the base class
constructor here. So, in the derived class got not yeah yes kind. So, right next statement
we can add here before right yes. So, you can write super then within this one. So,
basically superclass constructor namely, the base constructor will be called here right ok,
then save it compile it. So, here you can see both the derived class constructor, as well as
superclass constructor will be called here, illegal start of type ok.

(Refer Slide Time: 27:39)

306
So, can we write base here, simple base. Let us try whether the base call concern can be
called in this method or not. In this case, super it does not work here, anyway so, the
superclass constructor cannot be used here, but we can use in the derived class
constructor base class constructor right system. yeah, you can just comment it yeah fine.
Then within this derived class method constructor go there right here right, then go to the
2 statement right one is that super yeah, super within write yeah construct not 0, right oh
yeah they're fine.

(Refer Slide Time: 28:09)

Now, we call this constructor a through the derived class constructor. Let us see whether
it works for us or not yeah. So, in this case, it works that mean a constructor can be
called by means of the subclass constructor only now let us run this program. It will call
the superclass constructor as the base class constructor ok. So, this is basically we have
understood that a constructor can be declared in an abstract class and that same
constructor can be used in the derived class objects. So, this is one example.

Now, let us have another example, as in the last example we have discussed that an
abstract class with an abstract method, but an abstract class may have the non-abstract
that means without any.

307
(Refer Slide Time: 29:03)

So, that method also can exist, but this method can be accessed through the subclass
object. So, this is the one example that we are going to give a demo, here the class base
is the abstract class defined as an abstract keyword and then it has the method fun which
is basically non-abstract method.

Now, we can call we can create a subclass object derived here inherited from the base
class and then the fun method is here it is basically overridden method here because we
have overridden the fun method there it is like this one fine. Now let us come to the main
class here demonstration_6 1 0 main class, we basically create an object for the derived
class derived the new derived. So, in this case, you can understand d.fun we will call the
fun method there ok.

So, let us run this program we can understand how it works for us yeah. So, it is derived
is called here ok. So, derive constructor is called and derive phone is called, so it is like
this. Now let us see how we can access the fun method which is defined they are in the
base class method lets come to the object here no yeah here.

308
(Refer Slide Time: 30:41)

So, now not here these as the previous program you have switched to the next one yeah.
So, this fun method which is defined they are in the base method is basically it is allowed
that abstract non-abstract method.

Now, my question is whether we can call this non-abstract method here in the derived
class or not. We can use it here we can use as a super right, you can use the super
keyword. For example, in the fun method or somewhere right we can write super. fun,
super.fun right and then this one. Now we can understand that we used the fun method in
the right. So, by super keyword we can refer to the member which is there in the base
class; although the object is not created, it will be accessed yeah. So, it is right yeah we
can understand this one.

So, now non-abstract method may be there in the abstract class, like non-obstructive data
may be there in the abstract class they can be accessed using the super keyword that is
there in any subclass objects.

309
(Refer Slide Time: 32:07)

Our next example: basically demonstrating the final keyword that is there. Final keyword
is a very strict keyword if you declare a class as final; that means, this class cannot be
inherited in any other class, that means no subclass can be created from this one.

So, this is the one example where the bike is the one class we have declared as a final.
So, final means, no inheritance is possible. Now, this code definitely it is not a valid code
because, we are attempting to create a subclass called Honda 1, extending bike class,
bike class and then definitely if it is not possible. So, the next statement main class is
also not a valid one, now let us run this program, see whether this program gives a
compilation error or it works ok. So now, we can see it gives an error that that cannot
inherit from the final bike. So, this means that we cannot do this one ok. So, this is the
one.

Now, this question that arises that then what is the use of the final? Sometimes we can
have a stick restriction that this class is a stick class that no on class can be derived
because derivation means is an accessing some member in the superclass. So, if we want
to protect it, so we can fix the final keyword. Now a class can be made as a final like a
method also can be made as a final, a variable also can be made as a final. Now, here in
the next example that, we are going to give a demo 6.12 a, showing that, how a method
can be declared as a final. If we declare a method as a final that means, this method
cannot be overridden in any way.

310
(Refer Slide Time: 33:55)

So, this is one example that we can see. The class base is the abstract class, that’s fine
and there is a method fun which is declared as a final. This means that no overheating is
possible. Now here derived is the derived class, extent base class it does not have any
other method or members is ok. Now we can create an object of the derived class, but
referencing to the base class and then we call the b.fun. So, it will basically call the apps,
the final method which is the fun method derive declare in defined in the base class. So,
this fun method is basically system.out.println final fun is called.

Now, let us run this program, we can have the quick demo so that we can see about it
yeah. So, fine, so this is running. Now let us have to see whether we can override it or
not? This is an attempt to override a method, this is the next demonstration, please. So,
we can see, we are trying to override it at one method which is declared as a final method
in a base class and derived class we are going to overwrite it in.

Now let us have the quick look at the program here. So, here class based abstract method
and then fun is also final. In derived we have the method derived is the constructor no
issue. Now, void pan here is basically our attempt to override the method which is there
in the base class. Now let us compile this program. If it compiles then means that over it
is in successful. Now let us run this program, compile this program it is 62b yeah fine
right. Now see it gives compilation that derives cannot overwrite fun in this. So, we have
understood that a method if it is declared as a final, in super class then, it cannot be

311
overridden; however, it can be accessed in the subclass object by referring to this either
super or this course ok.

So, this is the demonstration about the inheritance and the many features in inheritance in
Java program. And we have discussed, so many things are there. It is adviced that you
should practice all the program that we have this used in this demonstration, so that, you
can understand more. And if you have any doubt, any confusion you are you can feel
free to approach at posting your doubts in the forum so that, we can answer to your
question.

Thank you, thanks for your attention.

312
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 15
Information Hiding

So, in this module we will learn about Information Hiding in Java. The concept
information hiding is a very interesting as well as important concept. So, our today’s
basically the information hiding; that means, what are the different way that a
programmer can control the access of different elements, different elements means the
method and the members that belongs to a class.

(Refer Slide Time: 01:01)

So, for this the Java developer has coined a number of modifiers, they are called access
modifiers. So, in this lectures we will try to understand the different access modifiers and
then their usage. Now so far the access modifier are concerned there are 4 types, they are
called default, public, protected and private. So, if we fixed one access modifier before a
member for example, before a field or a value or a data or a method then according to the
access specifier that value or the method will be accessed. So, if it is public then it should
be visible to anywhere so; that means, any other class from any other class or any
method belongs to any class can access that kind of members.

313
On the other hand, if it is protected then that member cannot be accessed by all classes
that member can be accessed by any method that belongs to any inherited sub classes.
On the other hand, if it is a private then that member cannot accessed by any other
method other than the method in that class itself. So, these are the three; public protected
and private and then default, there are possibilities that without making any specifier
explicitly then it is called the default access specifier. That means, if we do not use
public protected private, just keep it blank void then the access specifier is called the
default. If it is a default then that members will be accessible to any class that belongs to
the same directory, where that class belongs or it is basically belong to the same package.

So it is basically, either same file or it is a same class belongs to the same directory the
access will be available otherwise, it cannot be accessed. So, these are the 3 4 different
access modifiers and we will just discuss about all these modifiers one by one with
examples. So, then you can understand about it. So, we can say in other words that
access modifier specify the scope that a member have, whether scope is within that class
or scope is within that directory or scope is anywhere. So, this is the concept that is there.

(Refer Slide Time: 03:41)

Now here, the scope can be understood from this table, we have mentioned that access
level and the different modifiers that we have discussed 4 modifiers. Now so far the
public is concerned as we see any class, they have the access to public member, any
package also it has the access to that member any sub class and it can be from anywhere.

314
So, if it is a public means it is a global look like. So, anybody can see it, can use it, can
print it, can change the value whatever it is there. On the other hand, if it is a protected
within the same class any method can access this protected data then protected member
within the same package, the protected is accessible within the sub class the protected is
accessible; however, protected is not accessible, other than these 3 things from anywhere
it cannot be. So, if the two class files are same package then protected member can be
accessed in any class, it belongs to that same package.

Now, let us come to the private as I told you private is the stricter access specification, it
is accessible a member which is declared as a private is accessible to that class only
where that member is declared as a private outside this class that member cannot be
accessible either it is packaged or it is sub class or anywhere. Now the default as I told
you, default member is accessible to the same class, where it is declared as a default and
also in the same directory it is called the package, where that class is that member is
declared as a default access specification. So, this table I suggest you to remember it is
very informatic table, it can give you the whole summary of the different modifiers.

(Refer Slide Time: 05:45)

Now, let us have a quick look over the different modifiers one by one, first we shall
discuss about default access modifier. So, it is a default means we do not have to
mention any access specification explicitly before a member that is a data or a method it
is without mentioning these things it can be and as I told you if the default is an access

315
specifier for a member; that means, it is accessible only within the same class or within
the same package; that means, package concept is little bit not known to you, regarding
this package our next lecture has been planned.

So, there we will discuss about the package, package is a collection of Java files actually.
So, there maybe all files belongs to one subdirectory or a directory. So, a directory we
can say roughly as a package, but package has many more other implication. So now,
you can understand a package, if we refer to it means that a package is a set of files,
which are belongs to a common directory, one directory.

(Refer Slide Time: 06:53)

Anyway so, the default access specifier, we are going to discuss about it, let us have a
quick demo a quick look of the two classifies that we have discussed here. Now, here we
discussed two class file and in one class file and we say that it is the on one class file, we
declare one class this class is called class A and it is stored in a file, let us name of the
file be A.java.

So, this is the one class, we have declared and stored it is in the form in the file called
A.java. Now this is a very simple one class that we have discussed for only
demonstration or you can say for illustration. So, actually this class can be very complex
anyway. So, this a simple class A stored in A.java file and here is the another file another
file, we can say the name of the file as B that B.java and here the class B is declared
here.

316
Now here, you can note two things here, the class that we have declared here and these
does not have any specifier nor this or also does not have any specifier. So, here we can
see both the class a without any access specification. So, what I want to say in other
word is that, access specifier can be prefixed before the class declaration, before a
method and before a data member as in this case only the class and then one method
belongs to this. So, we can specify the access specifier either here or here or both
whatever it is there.

Now, in this case as we see there is no access specifier mentioned. So, if no access
specifier mention then it does mean that the class A is declared as a default similarly, the
method message which return type is void does not have any access specification this
means that it is default by default. So, access specification for both class A and method
msg belong to that class A is default access specification.

Now, let us come to the class B again, here there is no access specification. So, there is
no access specification, it means that class B is also by default it is a default access
specification. Now this is the user method that public, static, void as we have already
discussed about it and here always we have to mention that public access specification,
this is obvious and without any hesitation you have to do it, because without these things
no one can run the program particularly the main class, if it is there.

So, this is the public access specifier by default is there and thus rest of the things are just
simply the accessing of the different. Now in the first statement, we see we create an
object of class A here and in this method main, we call the method msg, which belongs
to the class object; that means, which belongs to class A. So, if we run this program it
will print Hi I am in class A, this kind of message is there.

Now so, if these are the two files belongs to the different directory then access specifier
will not work for you, if they are in the same file, if we maintain these and these in the
same file say B.java then access specifier default acts will work for you then in this case,
these two will give will not give any error, but if they maintain in the different file, but
not in the same directory then it will produce an error. So, these will be an error.

But if again, it produce into the same sub different sub directory, it is an error and if it is
in the same directory there is no error. So, there are two things that you should consider
default access, where if both the classes are belong to the same file. So, there will be no

317
error, if they are belong to the different sub directory then there will be an error, if they
are belong to the same directory then there will be no error. So, these are the 3 things that
you should consider with access specification. So, this is about the default access
modifier.

(Refer Slide Time: 11:31)

Now, let us have another example of this one and here we can see we have little bit
different concept I have introduced here ok. So, here is a package my package as I told
you, in which directory this class belongs, we have to specify this one. So, that is why
this concept is there this indicates that this file that mean A dot java belongs to one sub
directory called pack 1. So, that is why the package now regarding package statement,
we will learn a lot later on. So, this in these case, what we have done is that this program
is shaped as A.java in the sub directory pack 1.

Now again, this is another program same save this program as B dot java, it is in the sub
directory pack 2. Now, as you see this program and this program, they are belong to the
different sub directory that mean default access specifier, this one or this one will leads
to a compilation error. So, this is the things that we have already discussed earlier. So,
this is the concept.

318
(Refer Slide Time: 12:41)

So now, access specification is all about this one. Now here, again you can understand
that in this case, there will be no error this is because, if you see here this program, we
save A dot java in a sub directory say 10 and here this program B.java is a same
directory as both the class files are in the same directory. So, default access specifier
works; that means, in this case they will not give any error.

So, these are the 3 things that we have to consider about or is the same class files in the
same directory files in different directory. So, this is the concept and then access
specifier will work for you.

319
(Refer Slide Time: 13:17)

Now, let us come to discuss about another modifier, it is called the public access
modifier. Now so far, the stricter since is concerned public specifier is basically in a very
strict access specification very weak. Next after public the protected then private and
finally, default is basically sorry public then protected default then private in that sense.
So, as you know private is a most stricter access specification compared to the public,
public is the weakest access specification in this range, you can consider the table that I
have already discussed that table, you can follow it.

Any way so, if we declare any class or any data method as a public this means that that
class will accessible to any other class, whether this class belongs to the same directory a
class into the same directory or belongs to class in any other directory. So, that is the
concept it is here. So, it has the scope among all it has a weakest scope among all other
modifier.

320
(Refer Slide Time: 14:35)

Now, let us consider a simple example first here or we can see this is the class A we have
declared A.java and in a sub directory say pack 1 and here we can see we have declared
the class A as public and now another class B, which is an default access specifier say
and these class is the save as B dot java in another directory say pack 2. So, there are two
classes class A and class B both belongs to the different directory whereas, class A
having the public access specifier.

Now, if it is like this then let us come to this one accessing of the members, which
belong to the class A. So in that case, this will not be an error because, this is public and
this method is also declared as a public as the method is public, whatever then this
method is accessible by any class which belong to the same directory or any other
directory outside that directory. So, this is the concept about the public. So, public is the
weakest access specification as we have already mentioned. So, in that case you can see
this is the output that it will give, I have to the obvious. So, there will be no compilation
error.

Now again, if there is a what is called the restriction, which is not met then this will be
reported not during the run time rather during the compiled time; that means, you will
not be able to compile this program successfully, if it violates some access specifier as
per the rule.

321
(Refer Slide Time: 16:21)

Now so, this is the public access modifier, let us come to another example here again, we
declare class A as a public and there is again another class B both are declared as a
public. So here, we create take two class classes class A and class B and in class A, there
are public data member and then public method, this means that the entire class is
basically accessible to any other classes anywhere actually any classes. So, according to
this if this class is in the same file not necessarily to be same file rather, if it is in the
same directory rather or we can say in the other directory also no problem, all these are
quite there will be no compilation error.

Now again, I just want to mention one more important thing that you may face
sometimes that if we maintain these two classes here, these classes and these classes, in
the same file then the Java compiler does not allow to specify all the classes, which are
belong to the same class by any other access specifier; that means, if class A and class B,
if we type using same program and save as a say class B dot java then that public
specifier, you cannot mention because, in the same file there is no access restriction.

Actually because, you are a programmer, you are writing this class, you are using this
class then why you should mention any access specification, there is no meaning
actually. So, in that case the Java developers suggest you to make it default. So, no
access specific provided that if you declare all classes belong to the same file.

322
So again, my advice is that whenever you write two or more classes and save all the
classes in the same dot Java file, you should have give the access to an default do not put
any access specification other than default that is the concept you will be able to you will
not be able to run this program. In fact, compile this program in fact successfully. So,
these will report an error usually people follow this one.

So, public is not required until and it is a not a good practice actually, it is a good
practice for any programmer is that if you create any class all these class, you should
maintain in a separate file. So, all files can be maintained individually isolated way and
then all these files can be accessed in your main class that is the practice good practice of
course. So, in that case all those access modification matters actually, if you store all the
files in one file, all access modification does not matters too much because, it is public in
any way.

(Refer Slide Time: 19:21)

Anyway so, this is the concept about the public access modifier and here is the same, you
will be able to understand here, we define the class A as A .java in one sub directory and
here the class B also saved as another sub directory and as we main make here is a
public. So, it is a public; that means, from any class which belongs to any other sub
directory, this class A with all it is member will be accessible.

So, this is the concept here so, that is this one is look what like this. So, this is the public
access modification is very easy. So, public if you mentioned it then it can be accessible

323
to anyone there. Now one more thing that I want to mention here is that, if you declare a
class as a public for example, here we declare a class as a public, if we declare a class as
a public and if you have the access the other members under this class without any
access specification; that means, if they are the default access specifier did not mean that
if they are the default they are also public.

So, here for example, it is declared as a public and this method is default access specifier,
this means that this message is also public. That means this method can be accessible can
be accessed by any other class in anywhere. So, this is the idea about the public access
modifier.

(Refer Slide Time: 20:51)

Now, let us come to the discussion of our next modifier, which is the strictest one the
private access modifier. So, this modifier whenever you specify for a class, this means
that any method which belongs to the same class can access it and outside that class no
method can access that member. So, this is the concept of this private access modifier.
Now let us have an example here.

324
(Refer Slide Time: 21:17)

Now, we declare class A and access vision is public. So, public means it is a it can this
class A can be accessed from anywhere; however, if we see this is the member, which is
declared as a private that mean int data is declared as a private. So, being a private
member. So, any method which belong to this class can use it. So, this method message
if I write say this one plus data, if you write say plus data no issue. So, it can use it.

Now, let us consider the class B maybe in the same file, it if it is in the different file in
same directory or sub directory it also equally applicable. Anyway so, this class B also
declared as a public; that means, these class can be accessed from outside to any other
class. Now here, if you see let us declare this class as a class B and this whole the
program is saved in a one file called B dot Java. Now so here, as it is public class so we
can create an object so because, public class is accessible so no problem. So, this is not
an error and here you see system dot out dot print ln obj dot data.

Now here is a problem because, data is declared as a private and you want to access it
from the class B. So, this will not allow you that mean you cannot access the data, you
cannot read the value of data by creating an object of class A so there is an error. On the
other hand as this message is declared as a private pubic because, this is a public and this
is also public then this is also accessible that mean it will give this print message. So, you
can understand that ok.

325
So, private means it belongs to if it is a private then only this one. So, outside this one it
does not have any access that is the concept. Now so, this is a simple example now let us
have consider another example.

(Refer Slide Time: 23:25)

In this example, what we have to do is that again, we declare this is a private. Now class
is private, if class is declared as a private then all the member that is there with the
default access specifier also become private. So, in this case as this is a private and there
is a default. So, by default all these members are private.

Now, let us come to this program again here, class B the main class let us save this
program as a B.java, which include class A and class B file in the same file and here we
create an A object this one, you cannot create because class A is declared private and for
any private class no object can be declared outside. So, this is an error now here again,
System.out.println(obj.data), we are accessing the private data it is an error and object
this is also an error. So, you will not be able to access any method here. So, you can
understand that private, if it is declared here then it is not accessible outside it.

326
(Refer Slide Time: 24:43)

Now so, this is our example that we have discussed about the private access modification
and this is the another example and this is a very interesting example and you should
note it very carefully, what we have done it here. So, this class A is declared as a public
this means we can create an object that is no issue. Now here, this method is public this
means that we can call this method from here because, if the public method can be
accessible from any other class from any other method belongs to any class whatever it is
there.

Now, let us come to the discussion of this one. So, private in data so for so far this
method is concerned this is no error no compilation error, because data is accessible to
any method any private method, which is declared within the same class. Now let us
come here, whether we can use this one, see here fallacy is that the data is a private and
we access this private by means of this method. Now if we can you access this method
then internally basically or indirectly I can say indirectly this data is accessible to this
class B although data is a private but here is actually in Java you can do that.

So, if a method which is in the same class, where a private member is declared access
that one and if that method; that means, this method is declared as a public and then
public can be accessible. So, via this public all the private can be accessible. So, this is
basically accessible. So, here basically we can access the private member in other way
indirectly.

327
So here is a problem is that this method is the main critical. So, if you develop one class,
where you can declare a method as a public this means that you allow any other
programmer to access this. So, it is accessible whatever the data member, everything is
there whatever id you can act, I will you are giving that accessibility to others so that
now, if you do not want to give access then definitely you should declare this as a
private; that means, this is strictly private, I do not want to give acts to any data or any
method belongs to my class. So, this is the concept that is there so for the private the data
is concerned.

(Refer Slide Time: 27:01)

Now, let us another aspects so far the private data is concerned id is a constructor. Now
what will happen, if we declare a constructor as a private? Now in this case, you see this
class is declared as a public. So, anybody should can access this class does not create an
object of this class; however, here you declare as a private constructor is declared as a
private and then this measure by default is a public measure because, it is a public class
belongs to public class.

Now here, if you create a constructor then means whenever, we create an object then
constructor will be called here. Now when the constructor is called in this case as it is a
private, private cannot be executed from anywhere right. So, this will lead to a
compilation error; that means, if you declare a class as a public, but if constructor as a
private then no one can create any object of that class. So, usually this is a very harder

328
one rule, you should if you want if you want to make a class as public; so, better that you
should not create any constructor, which is with private constructor. So, usually we do
not do. So, constructor should be declared as a public like so that object can of that class
can be created any way, but once you can create an object, it means that you can access
all the members those are public or protected or access default it is there. Any way so,
this is the idea about that private constructor is not advisable in actual situation actually.

(Refer Slide Time: 28:39)

Now, I am in the step of discussing the protected access in a modifier as I already told
you that protected access modification is limited to the inherited class. That means, if a
member is declared as a protected in it is super class then that member is accessible to
any derived class or any subclass, which can be obtained from that.

329
(Refer Slide Time: 29:05)

So, this is a concept of protected now here, let us have a quick look about it class A one
class that we have declared here as a public and here one data we have declared as
protected. Now the class B here, if we want to access this protected data then it will be a
compilation error, you cannot access this protected error, but if they are in the same file
in the same then this is there is no compilation error. So, in the same file it can allow, but
in the different file outside or any class cannot access the protected data.

(Refer Slide Time: 29:39)

330
Now so this is a concept as a protected now here is another example, let us see whether it
will work for you or not now class A and here is a public, this is a protected method and
here you see class B extensive that mean B is a derived class subclass of super class A.
So, by virtue of subclass, it can access any methods those are public and protected into
this one. So, here that i which is declared as a public is accessible through this one. So,
this is also correct and as it is a public and then B object new B so no problem B is a
class itself. So, it is also create object.

Now, if I write say A object and A also that is also correct no problem because, it is a
public a public object can be created. However, all the protected message cannot be
accessed outside this one, but it if they are in the same, it can be accessible here now in
this case. So, it is an extent. So, this is a valid compilation is successful as well as output
is valid.

(Refer Slide Time: 30:45)

So, this is the protected access modifier and here is another. So, this is the same example
little bit in a twisted manner, we create this class save in A. java here another class save
in a B .java class a in a different directory and class B is in a different directory class B
extends A. So, class B is the subclass of super class A. So, no problem all protected
members for example, this message is accessible to this and so this is a valid output.

So, this is a concept of protected. So, very simple the protected means only sub class that
inherits a super class can access it whether this is in the same file in thus different file,

331
but in the same directory or the file that is there in outside any other directory no issue.
So, this is the protected access modification.

(Refer Slide Time: 31:35)

So, protected is basically a little bit limits the access specification. Now here again, this
is a simple example that you can think about. In this example, we declare class A and
this is the Simple one extends that is Simple is a derived class of this super class and
within this class the main method is declared. So, you can see if we do it then Simple
object =new Simple( ) if we create an object of this class and we call the object measure
here. So, this will be accessible this one.

So, all these things are there. Now so, class a basically here again one thing you can
notice that method overriding. So, here we see that this message is declared as a
protected in class A and again the message is overridden here in the subclass this one.
So, if it is a protected and if it is a subclass of that; so, overridden is possible, but if it is
not supposed no access specification is there. So, it is a say default and then and then if
you declare as a protected here is a protected then the problem.

The problem is that if it is a default one method, you want to protect it, override it as a
protected one then it will not allow you to do that. So, this is stricter one since, that you
cannot do that. So, all these things if the access vision not allowed, it will not
successfully compile your program. So, during compilation time if any access
specification is violated in your any program so far access is concerned it will be there if

332
whatever the expression that you use it and if they are compiled it successfully; that
means, you are allowing the program to give the access to all those things are there.

(Refer Slide Time: 33:17)

So, we have discussed about the access specification in order to hide the information
here information in the term of data as well as method, the whole class is also considered
as an information. Now our next topic is basically that package, we have referred to
many times package, package, package. Now we will discuss about in Java, how a
package can be created.

So, this is a very important because as a programmer more specifically as a Java


programmer, it is your responsibility to build very large software and whenever you have
to be is very very complex the voluminous large software then definitely you have to
manage all the classes very carefully. So, a package concept in Java gives you that kind
of skill. So, that you can manage very large software configure your software very
efficiently.

Now, if I ask you one question, what is your idea, is it possible that two classes having
the same name, but in two different packages are to be used in another class outside the
package? So, answer to these questions will be understood once, we discuss the concept
of package in our next module ok.

Thank you very much.

333
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 16
Demonstration - VII

So, information hiding is a very important and object-oriented paradigm and information
hiding is also very nicely has been featured in Java program. So, we have discussed the
information hiding in our last module. Now, it is our time to have a quick demo of
information hiding concepts in Java.

(Refer to Slide Time: 00:43)

As we have already discussed at that information hiding in Java is by means of four


access specifier; default, public, private and protected. In this demonstration, we will
demonstrate how the different access modifier will have different access protection for
the different classes in Java program.

And then with this modifier the method overriding also method overloading as well as
overriding how the two things can be there and finally, we will have a quick demo about
having all the modifiers in one program like. So, this is our plan for the demonstration
today. Now, let us have the first demonstration in this series where we were going to
discuss usage of default access modifier.

334
(Refer Slide Time: 01:33)

Let us have the program here so, class A is declared as a default class because, if we do
not specify any modifier before a class name then it will be treated as a default. So, class
A, in this case, is the default and then you same thing the message void is basically is
also a default method because no access specifier is mentioned.

So, as a whole, the class A is a default class and with a default method the message. Now
next is that main class which also defaults class here and it is basically in one file
because both the class A as well as demonstration_71 is stored in the same file. So, there
is no issue of running it now. So, if we run this program so, it will basically run
successfully, but it will run with default access specifier for this program it will run let us
run this.

So, as it is compiled successfully definitely execution will be there and it will give the
execution. So, it is successfully executed now. So, the program is not here actually, but
the program will be seen somewhere else now let us see. So, here basically in one file the
in this case we use the name of the program file as demonstration_71.java. In one file we
store two classes, but for good practice that a Java programmer should maintain a
separate file for the different classes.

So, here is an idea about that class A is store not in the same file as in the main class, but
store in another separate file and name of the file is same as the class file. So, class A
stored in the file call A.java and demonstration_72 is a new demonstration showing that

335
two files they are in two different two classes are in two different files if it is there
whether they are if it is here in the class a file if you go to that you can see that this class
A is declared here with default access specification.

Now, let us switch to the demonstration_72 program file it basically includes the main
file here it is also the default. Now, here we can see these two files are stored where we
assume that these two files are stored in the same directory here_demonstration 72.

(Refer to Slide Time: 04:07)

So, if those two files are stored in the same directory. So, the resolution is not a problem
and if the files are with access specifier so, member or accessing method is also not a
problem. So, here from the main class, we are trying to create an object A as A is the
default class. So, object creation is not an issue and then we are accessing the method m
s g the default method in the class A also not an issue.

So, in this case, if we run the program it will run successfully this means that access
specification is access specification allowed to access within the same file or in the same
directory. So, no issue if they are in the same file or same directory access modification
will work for you. Now, yeah so, this is working.

336
(Refer Slide Time: 05:01)

Now, in our next demonstration we will see if the class file A moved to some on the
directory and then if we can run this program if which is from another directory, but with
access, specifier is a default. Now, here if you see we created one directory
demonstration_73 under we can create a directory 1 where we have stored the file
A.class and A.java.

(Refer Slide Time: 05:33)

The file is there A.java let us see the A.java file here.

337
(Refer Slide Time: 05:41)

So, here the same file, but main stored in the directory the different directory. Now, let
us go to the main class which is again stored in the different directory here, go to the
main method yeah. In this case, the main method is stored in the directory
demonstration_73. Now you see the class A.java file is stored in a different directory
whereas the main method is stored in a different directory. Now we are trying to execute
run this program before going let us compile this now see whether it can compile
successfully or not.

(Refer Slide Time: 06:19)

338
So, if it is an access specifier is the default and the two files are in different
subdirectories then it will not successfully be compiled. Here you can see the
compilation error is that that is basically error cannot find symbol A; that means, A is not
known to this file. So, access specification if it is default then that is not accessible to any
other file outside of this directory ok. So, this is why this error is giving there.

Now, so, this program shows that the last three programs that we have discussed shows
how the access specification default works for us? Now, again we have some other demo
here let us show the 7.4 programs here where you can see ok. So, this program basically
creates a class A file in one directory as you have a directory is also can be termed as a
package. So, we create one directory called pack 1 and under this pack 1 we store on file
A.java let us see the A.java structure here fine.

(Refer Slide Time: 07:33)

A.java is very simple here we just mention that this A.java is in package pack 1 actually
it is a directory this one. So, class and one thing you can see here we made it public. So,
here class A is not accessing default access specifier by default, but it is made as public.
Now in the last example that we have shown if it is default then it is not accessible to
that, but if it is public then this class can be accessible outside to any file whichever it is
whether the same directory or in a different directory. Now, let us have another program
say demonstration program the main class which is stored in pack 2; pack 2 is a another
directory and we will define here.

339
(Refer Slide Time: 08:21)

So, in under this pack 2 we store this program that name as this name is
demonstration_74.java file. And this is basically we have to give an input pack 1
showing that it has the input capability means, whatever the classes which declare there
in pack 1 directive will be accessible to here because of this regarding this thing we learn
about whenever you cover the package concept.

Now, here with this if we run this program earlier similar kind of program was not
successfully compiled, but here you can see this program is all right it will run for you
correctly.

340
(Refer Slide Time: 09:03)

So, what is an error it is here? The message is not public ok. So, it is not working let's
return to the class 1 yeah we cannot access because it is a message is default here. So, if
we make it public yeah just make it public then this error is giving there because
message although class A is public, but its method is not public. So, this is public is
weaker restriction than the default 1. So, the default is supervoid here. So, default has the
highest privilege this one so, that is why this message is not accessible.

Now, let us again go to the main method it’s a compile it so, right yes. So, we have to
compile because you have to changed it and the next go to the main method main class
right run this and now it is successful and it is running fine.

341
(Refer Slide Time: 09:47)

So, this now works for you. So, a public method and with the public the public class with
its public members are highly accessible from outside any class that is the example
explain us. Now, our next example showing on the public access specifier let us have a
quick look another program let us go to the 7.5.java here yes. So, hah just load it yeah
fine yeah. So, in this program we can see so, we have declared the two classes class A;
where class A is declared as a default and it has members, 2 members, though both are
declared as a public.

So, it public means as we know that this class is accessible to any other class belongs to
the same directory; however, this class is not accessible outside to any file belongs to
other directories that are fine so, but here this class a as it is in the same file of this
demonstration_75. So, no issue we can use it and here we can see we just create an
object of this class here and so, object creation is and we also access the method here.

So, a public method is accessible anywhere, in the same file, in the different file, but in
the same directory or in the different directory in the different file no issue. So, in this
case, it is no issue. So, if we run this program it will run it correctly. Now, let us compile
first this program and after the compilation will execute it.

342
(Refer Slide Time: 11:51)

So, that it will a run it yeah so, it is running. So, fine it is running successfully yeah. So,
it is running now let us switch to the program again I just want to do little bit
modification. So, that we can see it a twist is here. So, A class which is in the same file
whether we can declare with some other access modification, for example, the public let
us specify the access for class A as public ok.

Now, let us see what will happen if we try to run a compile this program what will
happen, we made it public and as you know the public is public. So, it can be accessed
anywhere, but what will be the problem you can see yeah. So, here you can see here
class A is public and should be declared in a file named A.java; that means, if you
declare a class public then that class should be stored separately in a different file name.
But, if you want to store in the same file name do not specify any other access specifier
other than the default. So, it is not required here ok.

So, if you use two or more classes in the same file you should have the access specifier
as a default no other access specifier is allowed there, but in the separate file then you
can specify any access specifier. So, this is the example that we have discussed regarding
the access specifier and then public specifier and let us have another example about the.
So, private access modification let us go to the program 7.7 here we use the private
access modification.

343
(Refer Slide Time: 13:49)

Now, let us have the program here yeah we can see one class yes ok. So, class A here is
declared and it has 2 members; one method one method and 1 member the data is a 40 as
a declared as a private and then the message is declared as a public. So, 2 members data
and method one is private another is public. So, and then class A is a default with default
access specifier.

Now, in the main method main class demonstration_77 is the main class name here we
create an object A. So, it is because a is accessible to its own file and then
system.out.println() object.data. .Now, here the comment is that compile-time error this
is obvious because the data which is declared in class A is a private and then private data
is not accessible outside this class A it is accessible to the class itself, but not outside. As
the demonstration_7 sees an outside class of class A so, we cannot access so; this is why
it will give an error.

344
(Refer Slide Time: 15:17)

Now, let us run this program and we see it is giving an error yeah .Now, here you can see
error data has private access in A. So, as it private access so, we cannot access it this one
if we comment it then definitely it will work go to the program and comment it yeah,
comment it yeah fine no this one no system.out.println().

So, its comment yeah then it is work it will work because we are not accessing any
private members to any other class fine. So, this actually shows that how private
members access specifier is work there, let us have one more example of private access
specification 7.8 please go to the 7.8. Now, this is an interesting program a program on
you just note it.

345
(Refer Slide Time: 16:11)

It is the same problem as in the last program one, but it is a little bit different is there the
same problem in the sense that class A has the same specification private and public a
message method. Now, let us come to that main class demonstration_71. .Now, here this
is the private int data 2 1 private member is declared here we can declare a private
member here no issue that is fine. And also we declare 1 public member data 2 whatever
it is there now fine to let us see let us first declare about private int data two uncomment
the private one uncomment this one ok.

Now, what we have done here is that in this class main class we declared one main
method is there and then one method on data is that which is declared the private and we
int data 2 ok, you know private is a comment there no that is not correct. So, let us a
comment it private fine now. So, data two is declared as a with access specifier default.
So, default and an object A is created here. So, object creation is not a problem because
the default class is used here.

Now, system.out.println() class B data no issue because is public to this method and obj
message is also not an issue because is a public method here. So, here, but here you can
see if we run it then see that message m s g is basically accessed a private data no issue,
but it is basically accessing a private data indirectly in the main method which is in class
other than the class A.

346
So, this is quite now this is the one important point that you can note it there let us switch
to the program again I just repeat it here again here you see the message being public is
accessible to any other method. So, we can have the obj.message in the main method. As
the message is public it accessed, but the message this message even accesses the private
data which is private to class A, but here the as we can object message we can see the
result. So, that 40 is now accessible to a method which is outside the class A actually ok.
So, this is the idea about.

Now, here again, let us switch to the program here. Now can we declare a private method
in this main method here now let us see integer data 2 may comment it please comment it
and we declare public here. So, fine now let us declare here as public and let us see
whether we can run this program or not yeah fine .Now, here it is an error you see why
the error it is there. So, the error is that public int data 2 things cannot be declared as
public only we can declare as the access specifier default because in the same file we
cannot declare a method any member as public. So, public int, in this case, is giving error
as it gives the public as an error a private should give an error also.

So; that means, we cannot declare one member in the main method or is the main class
without access specifier any other specifier. So, let us see again private. So, private data
now what is the lesson that we have learned from th

em in the demonstration is that in the main class if we declare any member this should be
declared with default access specifier. No others access specifier is allowed to declare
any member in the main method that is the important thing that you should note it ok.

So, this is the concept about public access specifier and in some sense the private access
specification. Now our next demonstration is basically a constructor whether a
constructor can be declared as a private or some other access specification other than
public.

347
(Refer Slide Time: 20:37)

So, our next demonstration 7.9 includes this clarification here we can see one right yes
7.9 here we can declare a class as a default class, but its constructor is declared as a
private. Now, we if we declare a constructor as a private what will happen that it will not
be able to create any objects in any other class although it is accessible to some other
class in the same program may be. So, here in the demonstration_79 here you can see we
are trying to create an object A whose constructor is private it is giving compile time
error because the constructor is private. If it is a private constructor no object can give
can be created in any other class.

So, here is the error is a compile-time error showing. So, this basically gives an error
because a constructor is private if we remove this constructor private may say a public
right here public is are not required fine you can run it then save it and then run it first
you have to compile yeah then compilation is successful so, it is running yeah. So, it is
running there is no object new oh you do not have any free in the method. So, the
message is there object right obj msg here.

Now, so, we can create an object which was not possible by means of private
constructor, but if it is public it can be accessed here fine. So, this program shows that a
constructor cannot be declared as a private in any class if it is there then no object can be
created. Now our next demonstration showing the protected access modifier in a class, as

348
you know the protected access modifier is basically access limitation it limits its access
to only the subclasses inherited classes.

(Refer Slide Time: 22:43)

Now, here is an example class regarding the access modification called protected. So,
class A is default but, with its 2 members, the protected as an integer roll number and a
message as a protected message. So, this is the one class here now have the main class
say demonstration_710 now so, far object creation is concerned. So, it is not an issue
because it is a default class, but accessing the protected message obj msg or accessing a
protected member value. So, roll number is a problem, let us run this program as obvious
this program should not pass the compilation task step.

So, it will give a compilation error yeah as we see an object or roll number it giving say
compilation error because cannot find symbol look like this one. So, it is the error is
there, but the object is created, however. And another important thing obj.msg, it did not
give any error report actually if a method is declared as a protected and if it is in the
same file then protected is also accessible, but the protected member is not accessible via
this one fine. So, it is not working, but here again, we have done some mistake actually.

Now, here obj roll number you just see a roll number it is the method you have given not
method just gives an obj roll number right. System.out.println() obj roll number just give
a system that is the same statement you can call it there. System.out.println() just copy

349
the object roll number is not a method yeah correct you can type it here that is fine in
yeah correct here and then commented object or roll number this is not a valid one.

Now, see what we have done here class A is a default class with protected, but if the
class is in the said axis in the same file whatever it is a protected it will be accessible. So,
so protected members are accessible in this program, in this case, this program will not
give any error it will compile successfully what is the problem you have not run it
successfully compile it. Roll number you object obj.roll number right obj.roll number
here yeah obj.roll number yeah there is a simple mistake is there let us we have corrected
it now let us run it.

So, it is now running correctly. So, what we have understood from this demonstration is
that in the same file the protector members are accessible to different classes that are all.
Now, again if we make this class in a different file then definitely it will not work as it
works in this case. Now, here is the one example showing the same thing here the class a
file is kept in the different file if it is a different file that this will not work for you let us
have the second demonstration illustrating the protected member is more there what is
the 7.12 program let us load it.

(Refer Slide Time: 26:31)

We have mentioned here protected void display and then yeah. So, this will work for us
no issue protected method will be accessible to the same class, but if we store in the
different class if we store the class A in a different class then it will not be there. Now,

350
let us see the inheritance whether we have through the inheritance we can access it or not
let us go to the program 7.14 I think this is right we have to skip it go quick.

(Refer Slide Time: 27:07)

Now, so, the protected member has its more implication in the context of inheritance this
is one example; so that how the member protected can be access to the inherited class
derived class or subclass. So, class A is a superclass in this case where j is a private as is
private it cannot be accessed to any other class other than this method in this class. And
so, this is a method to initialize the object i and j in discussing. So, it is not an issue
because it can access it on the member.

Now, here B class extends A so, here and it has its own member one total as an integer
and its method sum .Now, here total I plus j as you understand that j being a private. So,
this is and compilation error this leads to a compilation error. So, it will not a work here
so, a private method cannot be accessible to any derived class right here. So, this will
give an error ok.

351
(Refer Slide Time: 28:15)

So, it is giving an error because the j is not accessible there. Now, if we make it protected
for example, so, instead of private let us go here protected now see this error can be
eliminated here in this case because protected member is readily accessible to the derived
class here. So, run this program and now this program will work for you.

So, this program works correctly and we can see that a protected member is accessible to
the inherited class. Now, let us have a little bit bigger one example who which includes
many other methods with many access modifier 7.15 is the last demo last, but one demo
fine let us see the program here.

352
(Refer Slide Time: 29:15)

Little bit large program here, but the program is readily understandable here. So, we have
declared one class called the base class which its members public one, private and
protected and integer is a default. Then here is a method public declare as a public getX
and then another method setX is also public and another method getY to private it is
basically initialized to private value it is a private method and setY is also another private
method that basically to initialize the private elements in it. And then getZ is a protected;
that means, dealing with the protected members there and then setting the value and then
getA return A.

(Refer Slide Time: 29:59)

353
A is basically the one default values are set default here. So, we have declared four
members public, private, protected and default and then eight different methods
regarding they are accessing.

(Refer Slide Time: 30:19)

And here is basically if we remove the comment then those are the comments basically
creates a problem. Now, let us have a quick look about the main method in this main
method we create an object of the class base class r r and then r r.z as you know z is a
default 1. So, rr.z is accessible here so, this is not an error so, it will first.

Now, we create another object of the main class method say demonstration 71 subclass
object new this one and for the subclass object we are trying to access the different
method get to set all these things are there. So, for the access modifier is public is
concerned system out.println() it is not an issue it will access because public method
public values are accessible to here. So, setX is being a public method it will accessible
here similarly getX also will be accessible here. So, this is not an issue.

Now, so, far the access modifier public is concerned they are accessible; however, there
will be an error if we removed the following comments in the following line right. For
example, system.out.println() value of y is subclass object y y here y is a private as if the
private cannot be accessed by any subclass object here. So, that cannot be accessed here.
So, if we remove this comment so, it will set an error. So, in that case, subclass object
setY also not a privileged a method for this class and then we cannot access it here.

354
Then so, far the protected is concerned. So, as it is a derived one so, extent because you
see demonstration_715 extent base class. So, derived class this means that all the
protected member and the protected methods are accessible. So, they all will access here.
Now so, far the default access specification is concerned in this class default is in the
same file. So, it will not be an error so, it will execute successfully.

So, this is the understanding of the different access modification. So, far the program in
Java is concerned now I will just conclude this demonstration with the last example this
is related to the method overriding; whether you can override some method having some
access specification which is already specified with some other access specifier.

(Refer Slide Time: 32:37)

The basic concept is that a method can override it by one weakest one if it is by if an
access specifier is weakest one then the strongest one then it can be specified by the
weakest one, but the reverse is not possible. So, this is the concept it is basically upward
compatibility it is there.

Now, so, far the different access is concerned private is the strongest and after the private
protected and after the protected default and the weakest is the public there. So, if we
declare a public, later on, we can method override as a default if we declare is a public
overridden as a private can be possible. But if it is a protected and then accessing that is a
default it is not possible because the default is weaker then the protected and vice versa

355
similarly public is weakest. So, public default is there then may overriding as a default is
possible, but the reverse is not possible.

(Refer Slide Time: 33:49)

So, this demonstration has a quick one example that giving the same notation here. Here
we declare one class here the class A s class A and in this class, we have the method
message one as a public msg 2 method as a private and msg 3 is another method as
protected. So, the three different methods with three different access specifier we have
not used any default access specifier here in this case, but we could do that anyway.

So, let us come to the inherited class extends a now by virtue of inheritance in this class
all the method is available except the private method protected is available and then the
public is also accessible there. Now, in this method, we have declared one method is a
default method message it is not an issue. Now, here if you see msg one which is
declared in its base class as a private, but here we are declaring as a public.

So, that overriding the method you go to the previous class the base class please
message 1 yeah. So, message 1 you see message 1 is declared as public. So, if it is a
public overriding is quite possible public to public same access level method overriding
is possible let us go to the main class here main method main class yeah so fine.

So, message 1 overriding is possible, .Now, here msg 2 in base class this method msg 2
is coming as private right go their private method. So, here we are going to an override it

356
as a private we can override it, but other than private we cannot override because it is the
highest access phase one it cannot be overridden. Now let us go to the next one yeah. So,
msg 3 which is a protected declare as a protected, but here we can override as a what is
called the public? So, that is possible.

Now, so, with these things we can override it and then once the overwritten is there, we
can create the object of these classes and then access it. Now let us compile this and let
us see what is the output this program it gives you. So, this basically gives a hierarchy of
access overriding method overriding with the different access specifier.

(Refer Slide Time: 36:15)

So, actually for a so, here you can see you know there is a problem you can just see there
is a problem in the 716 compile is successful. Now, what I want to mention as the last
notice note is that access modification is not a critical job for there you specify which
method which member you want to give access to for which one. But the compilation
itself take care of all this invalid or illegitimate any access specification. For a Java
program, it is a great relief that if we have wrong things and then the program is built up,
but this is not a violation because compilation time only it will resolve if we specify
according to one.

So, this is the demonstration about the access specifications and we have learned about
how the information hiding in access specification is can be done. And; obviously,

357
practice will improve your understanding I advise you to go for rigorous practice for this.
So, with this, I want to stop it here today.

Thank you very much.

358
Programming in JAVA
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 17
Packages – I

While, we are discussing about information hiding several times we have discussed
about the pack, we have mentioned about the Package in Java. Now, package is basically
a very important concept in Java. So, in today’s module we will discuss about packages
that those are possible in Java programs. So, concept of package will be discussed first.
Now, what exactly the package it is?

(Refer Slide Time: 00:45)

In fact, there are very two powerful and very innovative features that is contributed by
the Java developer, is called the packages and interfaces.

So, that is why Java is so versatile and Java is so popular now-a-days because of this
concept actually. So, these are the two unique features packages interface. So, today in
this module we will learn about the concept of packages, interface will be discussed in
other modules.

359
(Refer Slide Time: 01:19)

Now, a package is what? So, so far the technical term the package is concerned as you
know package, package means it basically a container. So, it is basically container of
what? Is a container of classes? So, in other words a package is basically is a collection
of is of a set of classes. So, it is basically an idea about the space compartmentalization;
that means, we can write we can compartmentalize all the entire space, the programming
space into the different packages. The idea it is that because Java can be used to solve
many problems and suppose you are a programmer in your organization which basically
dealing with only the graphics related program.

The other programmer may be related with other team of developer may be related with
networking related. So, all the classes those are related to the graphics they should be
compartmentalized into one place that is called the package. On the other hand those are
the teams the team members who are working with say networking they should
compartmentalize their space by making their own package. So, this concept is called the
package there and as we know you can recall Java JDK, the Java developer kits itself
includes a large set of packages also. So, these are called API, that Application
Programmer Interface or built in Java packages are there. So, they also develop based on
this concept.

360
(Refer Slide Time: 03:03)

Now obviously, why packages? It has many advantages. So, definitely it allows
flexibility to give same name, but too many classes that is to avoid namespace collisions.
Because, say suppose your package is graphics you can give a name class a, another
package who are working with this one they should not have be restricted giving the
same name; they can give same name to their. So, basically name you can give the name
of your son, same name can be given by other parents to their son like this one. So,
namespace collision if you want to avoid it then definitely the concept of package should
be allowed.

Now, here also as we already told you that concept of package allow, it is basically a
mechanism for partitioning the class name space into a manageable chunks. Because, all
related things are to be placed together. Graphics related all programs all classes should
be placed together. So, is a better practice and it also help naming and visibility control
mechanism, visibility control something is accessibility. So, some if we use a package
some accessibility can be automatically imposed. And then this is a last, but not the least
is that it supports reusability and maintainability. If a package, if it is there you can
create one package of your own considering, the reused of other course those are
declared they are in other packages.

So, reusability and maintainability this means that if you want to maintain the previous
versions let us keep them in one package, the newer version can be maintained in another

361
package. So, package concept give you code sharability, code maintainability other than
visibility and namespace collision. So, these are the so important process services that
can be obtained from the concept of package that is a package is very important one
features in Java programming.

(Refer Slide Time: 05:09)

Now, so package using this package as I already told you the code reusability can be
achieved. It helps resolving naming collision, it also help us to control the access
specification, information hiding access can be controlled. And, nesting hierarchy a
package can be defined within another package. It is in fact, consideration for the
maintainability or expansibility otherwise it is there version from one version to another
version. So, we can make one sub directory or sub package under a package. So,
hierarchical concept of package also can be extended here. So, that more flexibility for a
programmer can be obtained. So, these are the several advantage that the package can
give to the Java programmer.

362
(Refer Slide Time: 05:59)

Now, I just now mention that built in package called the API Java. So, there are many
built in packages are known in the Java program itself. So, here the built in packages for
example, java.lang is a one built in package as that means, related to input, output, some
maths function and everything. Those are automatically pushed into that directory called
the java.lang. Likewise javax.swing is a very powerful on package for graphical user
interface programs programming.

(Refer Slide Time: 06:39)

363
So, these are the several packages are there that it is there. Now, all these packages
basically to ensure the code reusability. That means, you can use the classes those are
define in this package in your own class, and you can access it without writing the
program of your own. So, it helps a programmer a lot because built in packages are
really very powerful boon to the Java programmer, help to the Java programmer.

Now, all the packages those are called built in packages are bundled in API and then
there basically JDK. And, whenever you install JDK automatically all these package will
be installed in your working directory or bin directory. Bin directory is an executable file
the all commands javac, java, java h, java doc all these commands are there. It is stored
in the same directories there. Obviously, you have to discuss the setting of class path. We
will discuss shortly about this one and then package is basically not only that classes, it
also another concept of encapsulation. It is called the interface, it is also collection of
classes and interfaces; interface will be discussed after the packages cover.

And so, API is the built in packages; now what I want to say is that other than API user
can maintain their own packages. So, user defined packages so, built in package versus
user defined package. Now, all the user defined package suppose you developed one
code, that code you can share with other team members. So, you can maintain one
package and then shared it. So, these are user defined package.

(Refer Slide Time: 08:19)

364
Now, first we can discuss about built in packages and then we will discussed about how
user can defined their own package. So, here is the total taxonomy of all the packages
those are there in Java programs and as I told you Java can be used for many purpose.
So, mainly two purpose the core packages; using this core package one can develop any
application using java dot lang, input output, util. These are the different data structures
and then networking related different methods those are discussing java.net package. So,
these are for core programming the Java core programming, called Java core packages
that can be helps to the Java core programmer

Other than this core programming, the graphical user interface related programming
those are basically done by using the package called AWT :Abstract Windowing Toolkit
in AWT image peer multimedia so, many things. So, many classes are there and then
java.applet is also another very powerful package related to the applet development.
And, other than this thing javax.swing is also latest inclusion in the windows toolkit and
applet packages. So, these are the total the packages, 9 packages I should say are
available to the Java programmer. Here one packages also miss, it is called the java.sql
for that is also Java database connectivity anyway. So, these are the so, many packages
are they are bundled in API and then available freely whenever you install the JDK.

(Refer Slide Time: 09:57)

Now, so a package as I told we can use these packages. So, these packages can be used;
that means if that a particular package you want to use in your program and that concept

365
is basically you have to follow the input command. So, input statement we have used
earlier also without knowing the details meaning of that, now you are going to learn
about it. So, input is one the statement that can be placed at the very beginning of your
class declaration or program.

So, input can access the particular package that for example, input if we write input then
java.lang.String this means that we one you want to use string class which is declared in
java.lang package in your program. And if you want to access all the classes which are
declared belong to a particular package, then instead of that specifically naming the class
you can write java.lang.*. So, star indicates that all. So, this we basically access the all
packages that you want all classes belongs to a particular package you will be able to
access it.

(Refer Slide Time: 11:09)

Now, here the other way of around also the package can be accessed. For example here if
you see say, suppose you want to access one class Date. Date is basically the built in
class which is defined in util package in java JDK. And, here you can see with this
statement, what we are doing. We are using a built in class called the Date class and
creating an object of that class called toDay. So, here toDay object is created which is a
class of type Date, the Date is not by defined by a programmer rather it is a built in class.

So, this is the way that it can be used and then whatever the method it is allowable for
this object which is discuss according to this class you have. So, for the programmer on

366
knowledge that is required is that, if you want to use the built in package you should
know what are the classes belongs to this package. And, what are the methods belongs to
this package and what are the constructors belongs to that class. So, landing all these
things makes a lot for a Java programmer actually, but it is very difficult job because it is
a huge. So, many 9 packages are there; in every packages around 20 classes if we take
approximately.

And, in every classes there may be around 4-5 average constructor. And, in addition to
these there may be around 10 methods and all the methods are having the different
arguments overridden method like this one. So, learning but with tedious, but anyway
constant involvement in programming and using makes a programmer habituated to the
different method. And, it basically gives a lot of skill to the programmer. Anyway it is a
matter of practice actually, you should have enough practice then you are the master
programmer in Java actually.

Anyway so, this is the idea about that how one can access a class who is belongs to an
API and this is also another way right import. And, then using this import we can create
an object that is also alternative method by this also. Whatever the way we can access it,
if you know that this class belongs to this package that that understanding is important.
Once this understanding is done with you then you can use this thing, as if it is your class
defined in somewhere in some directory like. So, this is the concept is very simple in that
sense actually.

367
(Refer Slide Time: 14:01)

Now, here we will discussed about user defined packages; that means, we know that API
packages are there we can use it, learning is required that is all. Now, I will discuss about
that how a user can define his or her own packages in its program. So, this is the defining
packages in Java program. Now so, as I told you package is a directory, is a directory,
subdirectory whatever it is there. Now, you have to create one directory where, you can
store all the files. I mean file means the Java file not only the Java file, Java file in
addition to all the Java file the they are corresponding class file.

If you store dot java and the corresponding dot class then you can put all those things
into a directory and then that directory become a package. The things appears very
simple is not it, but actually there are many more things to be considered. It is not so
simple, but in a simple word I can say like this, if we want to create one package of your
own. So, create a subdirectory first. Now then to mention, that this is your package then
before going to declare the class. So, you should use one keyword called the package.
So, here package is the keyword and myPackage is the directory where, you want to keep
all your class file and Java files into that.

Now, this statement is basically tell that this is the class that you have built it, is basically
belongs to the package myPackage. So, if you is these kind of common for all class that
you have created and giving the corresponding package name, then automatically all the
packages will be created. So, a package can contains any number of class file, any

368
number of Java file there is no limit. Absolutely theoretically there is no limit, you can
go on putting whatever it is there, but one thing is that it is obvious two classes having
the same name not allowed.

Because, it will not allow overwritten latter one will overwrite a previous one. So, you
have to very careful whenever you do it and is in fact, it will not help you. Because, after
once you create one a dot java next time whenever you create a dot java definitely at the
time of saving the system will ask that ok; do you want to overwrite. Then you
overwriting means the previous Java file. So, it is basically the in the same package the
two files having the same name is not allowed. However, in two different package the
same name can be allowed two different classes.

So, this concept is that that how user can create a package. This is a packaged what is the
statement I can say, the package statement is used for declaring one package and then
this class then will put into these packages. So, concept is like this.

(Refer Slide Time: 17:05)

Now, so this is the idea about it and hierarchically also package naming can be there
using by dot core; you know directory under the directory subdirectory, under the sub
directories sub directories all these things also quite possible. And, if you want to access
one particular class into particular sub directory so, dot periods is sign is called. So,
basically the concept as it is there is an operating system concept x dot y dot z that mean
x is the root.

369
Then under x y is a directory under y z is the sub directory and in this z there may be
some file say dot a. So, x dot y dot z dot a specify which is a basically location of a
particular class belong to that directory like. So, this is the periods that can be used to
have the resolution of the; or we can say that location resolution that ok; we can specify
which is the location of a particular class or particular package. So, this is the concept of
hierarchical definition is basically concept of sub packages in that sense.

(Refer Slide Time: 18:13)

Now, so here again so far the naming of the packages is concerned there is no rule of
course, but the rule is that the way you define directory you should do it, but that space is
not allowed. So, whenever you declare a sub package usually all small capital small
letters case right, small lowercase characters should be used better to avoid the
uppercase. But, sometimes the past is small I am upper a lowercase letter and then maybe
say myPackage m So, myPackage we can write.

So, myPackage so, my and then P is the capital letters and this is also and that I can write
as the package. So, it is like that that kind of con set it is there. So, this is also you can
declare about it anyway. So, the naming is very for example, all the API you see the
name is I think 3 to 4 character dot net, dot lang, then dot io this kind of things and
names should be small enough but, it should be unique of course. So, this is the concept
that so far the naming is concerned.

370
(Refer Slide Time: 19:29)

Now, we will discussed about in addition to these things few things are very important to
remember; I just mention this. This slide is very important in that sense, now user can
define their own packages, and if a user define a package then that package statement
should be first statement in the class file creation. So for example, if you want to create a
dot java a class and it is belongs to a package say my package. So, first statement should
be packaged MyPackage and then public class a.java whatever you can write it like that.

Now, so if you define a class which belongs to who should belongs to a package then
that class should be declared as a public. So, it should be declared at a public because,
you should give the access to other classes rather other programmers to access this one
otherwise there is no concept of packages coming. So, all class file belongs to a package
should be declared as a public. If you declare private you cannot use it protected cannot
be declare any class cannot be declared as a protected class of course, and you should
create a subdirectory under the working directory; this is very important with the name
same as the package name that you have mentioned.

So, working directory where your program will run all the packages should be under that
working directory that is important. Now, regarding this thing you can set the class path
environment variable in the setting of the system or your path setting also you can do,
regarding this thing we have already discussed very beginning. And another important
thing is that you create a file containing a class that is the dot java and that file should be

371
compiled successfully. That means, dot java should be stored along with its compiled
version; compiled version is bytecode. So, all the dot java as well as the dot bytecode
should be there. So, these are the essential condition so far creating the package is
concerned. So, these are the 5 points agenda is very needs to be adhere to very sincerely.

(Refer Slide Time: 21:41)

Now, another design guideline is that the package should be organized very efficiently.
So, that all related class related to a particular project, related to a particular application
development, related to a particular utility all these things should be placed into on
package. It is not that a very large package all the package does not have any limit can be
put there it is not a good practice although it will work it, but so far core maintainability,
reusability is concerned this is not the good practice. So, this is the one thing that you
should follow it is here.

372
(Refer Slide Time: 22:15)

Now, again repeating the same thing, you can declare a package by breaking the package
name. It is basically the directory working directory under working directory we can say
here is an example. If this is the one your dot java file you can put it into a package, let
the name of the package be elevator and then this is the declaration. And, as you see it
should be declared as a public. Those are the things as I have already discussed, I am just
repeating because it is very important right concepts.

(Refer Slide Time: 22:47)

373
So, packages declaration follows this kind of systematic procedure. We have discussed
about and naming can be done in that way as we have already discussed about. Now a
class in a named package can be referred in two different ways that we will discuss
shortly after discussion of few more important things here.

(Refer Slide Time: 23:13)

Now, here is an example let us consider. This example is basically is an attempt, this is
this example is an attempt to define packages. The name of the package is MyPackage,
as I told you two different way that you can define it I am telling you fast way. So, this is
the one I have declared in one package here one class in a package. The name of the
package is myPackage and name of the class is MyClass, I can use this way it will work
for you actually no problem. So, here the subdirectory myPackage is created and in the
subdirectory all dot java and class file is stored there.

Now, another way here one this package is created and then the same package can be
used in other class. Here is that if you consider this is the other class where you want to
use it; so the import statement is there. So, import then if you want to access a particular
class so, MyClass. So, import myPackage.MyClass that mean this basically gives you as
if this pack this class is in the same file where this program is there. So, this is the idea
about that how the package can be utilized.

So, there is two concepts so far the package is concerned; package to build a package and
import to access a package in your own program. So, this is the concept it is there. Now,

374
so far this accessing is concerned there are a few more things are to be learned about; all
these things we will discussed in details in our next module. We have planned our next
module also to cover packages anyway.

(Refer Slide Time: 25:03)

So, as a summary again so, in a Java whatever your bin directory; that means, all Java
executables are there you can keep it there. And, if you want to plan your package then
you if this is your working directory under this working directory you can create your
myPackage and all these Java class file belong to this package can be put here. And, and
as a parent directory of this one just hierarchical up right; so, this class file where your
program will include. So, working directory so, this is basically working directory, this is
your package directory and all these things will be the bin directory is there.

So, this is the common concept of hierarchical way the package it is there because, you
are going to learn many topics in this course. So, you have to maintain many programs
those are under demonstration and illustration in the slides and everything. So, my
suggestion is that you make a very nice organization of all the things may be say
inheritance, one directory working directory. Related to inheritance all the classes that
you can you can put into the package and then used your program, use the input
command; all the package can be accessible to this either import the package name.* or
import package name .particular class you can use it.

375
So, this is the basic concept that you should follow. For a good programmer should a
systematic a meticulous method needs to be followed.

(Refer Slide Time: 26:31)

Now, user can define more than one class belongs to a package and it is also not good
practice is that all the class should be declaring one dot java file because, you have to
compile it an individually and separately. So, basic idea is that all class file should be
created in a separate manner. So, here is an example for example, so here class A if it is a
component in a package P. So, you can create this one file as it is.

So, A.java and A .class and then the next another class see suppose B you want to create
so B you can create as another right. So, this is basically another class we can say this is
another class we can say that is belong to the same package P. So, class A and class B;
now two classes are created and then they are placed into one package called the P. So, P
is the package here in this case.

376
(Refer Slide Time: 27:45)

So, it is like this so, more than one class multiple classes can be mentioned in the same
file. So, these are the simple step that you should procedure. First you have to create a
directory called P and all the classes should be saved dot java with their name and then
they should compile the class file. And, both all this dot java dot class file should be
stored there. And finally, if you want to use any one class belongs to a particular package
use import. So, this is the usual procedure that is there so, for the class package
maintenance is concerned.

(Refer Slide Time: 28:21)

377
Now, we have discussed about how you can defined declare your own package in Java.
Now next obviously, question that it is there; if packages are there how I can control the
different access specification in it. We have we have an idea about how the information
can be controlled by using for access modifier in our one module discussing this course.
Now, we will discuss about that modification those are applicable two packages also.

Now, so this thing will be discussed in our next module. Our next module will cover
package again, but package mainly we will discussed about the naming convention, the
setting of the different variables so, far the system variables, environment variable is
concerned and finally, the access modification. So, this we will discuss in our next
module ok.

Thanks for your attention.

378
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 18
Packages – II

So we are discussing Packages in Java. In the last module we have introduced the
concept of packages; that means, how the build in of a API packages are there in Java
JDK and then how a user can define their own package. Now today we will discuss much
more information about Java packages. This is regarding access and then maintaining
and then specification. So, today basically discuss mainly we will discuss about how a
package can be accessed, and so for the access is concerned, how the different access
specification works in case of packages it is there.

(Refer Slide Time: 00:58)

So, first thing is that how, whenever you are running one program, how your runtime
environment runtimes manager, Java runtime inward interpreter can understand that
which package is located where. In order to give this information, it is better is that you
can set the 6

classpath. Classpath is basically a system variable, environment variable in any operating


system windows, in Unix or in MacOS Mac OS, whatever it is there, there is a way of
setting the path.

379
So, the classpath is one variable, the environment variable is where you have to set it. So,
classpath basically should tell where your packages are located. So, whenever you refer
to a package, the Java runtime inverter the interpreter will consult this classpath name
and then get the exact location to locate it. So, this is the 3, there are 3 ways; in fact, by
which you can specify the explicitly you can specify the location of a package. So, the
first is that it is a default of course that it considers that all the packages are under your
working directory.

So, Java runtime interpreter, if you do not mention any classpath in your environ very
well. We will try to find by default any directory which has the same name as the
package name that you are mentioned in your import statement and that directory if it is
there under your working directory.

So, these are the first method very trivial method of course. So, if you maintain one
package under a working directory of your program where you want to run it, then it will
work. The second method is basically setting the classpath environment variable, this is
the way and this is the more sophisticated way I should say because all that is in you may
not maintain all the package directory under your working directory.

You can maintain here and there and here. So that is fine, but if you can explicitly
mention that this is the name of the package and this is the classpath it will work for you
to access this package from anywhere, it is not necessary that all package should be
under your working directory. And the second third is explicitly you can call a particular
package by the Javac or command. So, the Javac suppose you want to run one program
which is there in say xy; z package which is under abc.

So, you should write at javacabc.xyz.the name of the class file that is there. So, it will
run it. So, this is the Java and javac, next we explicitly mention there. So, these are the
three ways it is there, so you can use it.

380
(Refer Slide Time: 04:08)

.Now, here again as an example, so that I can discuss about that suppose MyPack is the
user-defined package is there and you can mention that this my pack is under your
working directory, immediately after your working directory or you can use the 2 other
method classpath setting or explicitly mentioning while you are invoking Javac or Java
that this is the location.

Now, if you mention the classpath set; So then MyPack and then you just mention the
classpath as C My programs under Java and then name of the directory. So, it is basically
to mention that in which root directory or parent directory under which the path that only
needs to be mentioned in your class. So, basically, Java runtime interpreter will consult
this classpath in one variable and check that whether in the according to that path your
package is there or not. If it is not there, it will that package does not found or no class
file available.

381
(Refer Slide Time: 05:14)

So, this kind of command it will be there. And here is an example of a very simple
example that we can consider it. Here we have declared a 1 class, the name of the class is
balanced and then it is declared in package MyPack. So, we are basically creating 1
package, the name of the package is MyPack and in this pack package the class is class
balance and one thing that it is not here although, but you should consider that this as I
already told you that all the class which belongs to a package should be declared as a
public.

So, here this is required, so public. So, public access specification it is required, if you do
not do then you will not be able to use it. And here again, this is if it is a public and all
the access, specification by virtue of default access specification is also public. So, these
are all basically it is a public class, it is a public class and in this under this public class,
we decide we declare name as a data type string balance, ball is a type float and there is a
method the this is also public method is a constructor and as it is public this is also
public.

So, it is a public constructor and it also has a void method, show method also public like.
So, this is a typical look of a class basically it will create an object of type class balance,
containing all these fields and the methods. So, is basically the package the class is there,
once this package is created, we can use it, you can use this class file in any program and
this is the one class you can define, it is basically this my pack can be created under this

382
directory where this, this class is defined. So, this is the class file under a working
directory and this is the file in a package.

Now, this is the typical look of the program is basically this is the class file account
balance main class because the main method is there and it will able to access all the
members which are there without any error because this is a class all methods are class.
So, it is accessible to any class um from anywhere it is like this because of the plus
access specification. So, this basically gives a simple example that a class can be created
can be stored in a package and that package, that class can be utilized in any other Java
programs as if it is your own defined class like.

So, this is the concept and then classpath if we say the classpath of this MyPack, then
that there is an import statement that you have to do it. So, here; obviously, the import
statement is missing. So, import MyPack in this case, import MyPack and then use it, so
you can use it like that on ok. And this import MyPack once it is mentioned, it will
consult that Java runtime interpreter will consult that this MyPack is a package it located
where, so it is like this; otherwise the second way it is that instead of this one, we can
write import and then full setting x.y. This one and then we can write balance. That
means, this means that this is an x is a root directory, under this y directory under that
directory the MyPack and then under that directory, this balance file is there.

So, this is also one way by which you can specifically tell other than the classpath setting
is there. So, these are the way that you can use it to define the different way so that the
location of a particular class belongs to a package can be specified.

383
(Refer Slide Time: 09:25)

Now, again, in a nutshell, we have to create your own program. The name of the
program as you have discussed earlier that account balance.Java and put it in a directory
and that directory before the MyPack directory whatever it is there. If you put into the
same directory as the package also it will work no issue.

Then we have to compile the file so that, that class file is there and then try to execute
the account balance class file using the command whatever it is there, and then you can
get it. So, it is the basic idea it is there. .Now, here you see in this case, in this example
that I have discussed here account balance is your program.

384
(Refer Slide Time: 10:12)

So, it is basically if you see the program here. This is the account balance is the user-
defined one class, we have created here and this is the package class, but they can be put
into together in the same class directory, so no need to specify explicitly the location of
the import statement is not required.

If you want to put all those things in the same directory, actually no import location is
there, but if they are in a different directory and then, then import statement is a
must. .Now, here fine, so here again ok, so there containing this discussion. So, account
balance the class that we have created as an application Java program, we stored into the
same as a package directory MyPack and then compile it, it will work absolutely no
problem no need to this one.

Now, see here account balance the class that you have created is now part of the
MyPack. That means, any other program can use it, but again be careful. The main class
can be used in any import statement only once. If you want to access one class which is
in the package having the main class, in addition to the main class in your own
application then again it is a compilation error. So, you cannot do that you should not do
that. So, usually it is good practice that the package should contain only the non-main
classes; that is what that thing it is there and you can use it like that ok.

385
So, this is the concept that we have discussed it. Now regarding importing a package, we
have to consider a few more cases, a few more steps to be considered very carefully
which we are going to discuss now.

(Refer Slide Time: 11:52)

So, for the import statement is concerned, there are two ways that import can be
explained. So, import only the name of the package, it is possible if you decide that
package in a classpath setting. If we do not do then you use the.comma.a statement
that.dot.explicitly specifying the location of the particular package it is there.

In this example, as we can see, so if package 1 is the name of top level and then package
2 is the sub package and under this package a particular class that you want to access it,
then you can write it using import package 1,.package 2 then.class name. So, is
a.common.the periods actually can be used there?

So, either. as a particular class name explicitly or.star all classes belong to that package
whatever it is there; otherwise here this is also one way if you can specify as an example
right. So, this is basically is an illustration of this concept is basically import
Java.util.date this means that I want to use that date class in my class now and this is also
basically I want to import all classes which belong to.io packages that are there in JDK.
So, these are the basically util and io are the two API packages and we can access it ok.
So, this is the import statement is very simple that import statement is there we have to
specify it.

386
(Refer Slide Time: 13:28)

And also we can mention using your own package you can just import package name.the
class name the same concept, whenever you build a package whether it is an API
package or it is a user-defined package. There is no discrimination, you can use you can
access, in the same way, it is API or it is a user-defined package.

So, the concept is similar is generic rather no difference concept have to be followed.
Now, so we have discussed package, maintenance and then how we can access it. Now I
just want to discuss the access protection for a package this is very important and needs
to need to be learned also very carefully, because if it is not maintained properly then
either is a compilation error, you will not be able to build your program successfully, so
many concepts are there.

So, access protection, already we have discussed while we are discussing the information
hiding by virtue of 3 4 access specifier default public private protected. Now all these
access modifiers are equally applicable to the package classes also. So, we will discuss
how the access protection in the context of packages is.

387
(Refer Slide Time: 14:50)

Now, so here is basically the idea about that, because a package can play in between the
different classes. So, it is basically interplay between classes.

So, Java should have a very good visibility control and naming convention equally. So,
subclasses, as you see Java, addresses 4 categories of visibility for class members. It
basically visibility for subclasses, which are in the same package; that means, a class is
declared and a subclass is basically inherited class is also declared, and if they belong to
the same package, this is the visibility one type of is there. The no non subclasses in the
same package that is; obviously, the package is there, there are many classes not
necessarily subclasses of other classes like this.

Subclasses in a different package; one class belong to say package p 1; whereas, from the
class which belongs to p 1, there may be a subclass in say q in other package q another
subclass of the class belong to p is in another sub packages r like this one. So, subclasses
in different categories, so how the visibility can be controlled and then classes, those are
neither in the same packages nor in the subclasses are there.

So, these are the 4 different ways, the visibility needs to be controlled and obviously, for
this visibility, things are there, access specifier public private protected it is applicable.
Now, the default is not a useful access specification so far the public is concerned. This
is because the default is applicable to all the classes either in the same program file or in

388
the same packages is there. So, usually people avoid a default access specification, so,
far the package is concerned.

So, if we use that default access specification, then you only limit to that package into
that a limit to that classes into that directory that packages only. So, all classes belong to
the same package can use the default classes that are there. But anyway, so we will
discuss more critically all this access specification namely default private public and
protected obviously we can follow some example to understand the concept it is there.

(Refer Slide Time: 17:22)

Now, again the table that I want to place it so that all 4 categories of visibility that can be
including the same class as you know if it is the same class any method can access any
member belonging to the same class. So, visibility is basically true for all members to
belong to the same class. So, it is the same class visibility is true for whether the access
specification you specify, it does not matter. Now if it is the same package subclass; that
means, a subclass which belongs to the same, except the private member, all other access
spaces does not have any limitation.

So, if you specify the private then no subclass method can access the private member.
However, if it is a default it can no modifier mean default and then protected and the
public can be accessible to the subclass. So, this is obvious, the same package non
subclass. That means, it is not a subclass, but belong to the same package, so private
cannot access, default cannot default can access, protected can access and then public;

389
obviously, it can access. So, if it is the same package, but not subclass then it can access
it.

Now, different package subclass, so a subclass, but that subclass if is belongs to the
different directories different package. So, private no way, a default will also no way, but
protected it can, because it is a subclass and then public it can because it is public and
then different package in subclass. So, private cannot access, default cannot access,
protected cannot access; whereas, public it can access. So this is the table, it is a similar
table that we have discussed in the context of the information accessing it is there.

So, this is the way you can think about it and then it will work for you now ok.

(Refer Slide Time: 19:28)

So, after having this kind of summary of different access modification it is better to
discuss about using some example. Now, this is the one example although little bit
complex example because it is really difficult to maintain one simple example to
illustrate all the features regarding the access protection in packages. Now even I have
tried it to make it as simple as possible here. We consider is 2 packages, MyPack age 1
and MyPackage 2, they are different is not that in some same directory a subdirectory
whatever it is there.

Let us consider 2 different subdirectories are there MyPackage 1 and the MyPackage 2.
In this MyPackage 1, we plan 3 classes, class X, class Y, class A, which belongs to the

390
MyPackage 1 directory and class Y is a basically subclass of class X and as I told you if
all their member of a package, they should be declared as public. So, here these are all
public class, I have not mentioned explicitly a public class.

Similarly, here the two classes which belong to another package MyPackage 2 also
public and Z is basically a derived class subclass subclass of class X. X is again super
class belongs to the package 1. Fine, so this is the organization of the 2 packages, the 2
packages contain 5 different classes actually X, Y, Z, A, and B, out of which Y and Z are
the subclasses. Now having this organization, let us have certain simple what is called a
structure of the 4, 5 different classes 1 by 1.

Let us first have the idea about the first class X, which belong to the plus package 1.

(Refer Slide Time: 21:22)

So, we are we are defining we are the creating or building the class X belong to the
package MyPackage 1. Here just note it, the class X contains 4 members including its
own constructor and class X is public as I told you, it should be declared as public. .Now,
here int n, n is an integer type variable which is declared as public because the public is a
default.

Now, p is a private member, q is a protected member, r is a public member again. So,


default int is basically a default access specifier by default as if public. So, it will be
public-private p is a private, q is protected and r is public. So, 4 members are declared

391
with 4 different access specification. Just np, qr we have to remember, that default means
it is a public, private, protected and r is public. Now, if I ask you, r is public; this means
that any class whether it is a subclass of this x or it is any other class belongs to any other
r is accessible.

So, regarding r it does not a problem. .Now, here is the problem regarding either, default
access specification in this case n and then p q all these things. So, n is a public, so no
issue, the default is no issue, but again there is an issue, of course, we start discussing.
Now let us save this class as.Java file x.Java and then compile it and then save it and this
public X is basically constructor which will basically call this and you see a so far this
constructor is concerned it is a method actually automatic method and this constructor
will attempt to access all the members that mean n, p, q, r in this case.

So, far the accessing of this is concerned as it belongs to the same class, all these are ok.
So, no compilation error it will put whenever you want to compile X.Java file. So, this is
the class X file, and I hope you have understood it clearly. Now let us come to another
class file and this is the subclass of class X.

(Refer Slide Time: 23:42)

So, Y extends X, now so far this class is concerned. You see it does not have any own
member of its own, so no issue, but it will try to access the member which basically
belongs to its superclass X.

392
.Now, here, here you see .Now, here is basically the constructor is basically by using the
constructor I want to discuss it as there is a default, so it is public. So, you can say public
it is and this is also public constructor know ok. So, this basically X, so derive it is
basically is a derived class subclass. This means that all public members will be
accessible and then all protective member will be accessible, but any private will not be
able to access, this is the concept right and as this class Y belongs to the same directory
as the class X is apart from this one. So all that default member there the default member
is n is also accessible.

Now, so far this statement is concerned this is ok because it is default access in the same
file accessible. .Now, here p that is declared as a private p is declared there as a um
protected right, so it is also a private. So, private is you know p is declared let us see,
what is the p is declared anyway. So, here let me just remind it how we have declared the
p it is there.

So, here exactly if you see p is declared as a private and then q is declared as a protected
and r is private that we have to remember somehow to understand this concept it is there.
Now let us come here, so here we can see so n is the default, so it is accessible. .Now,
here p is declared as a private, so there is a problem because private cannot be accessed
by any other class this one, so that is why this statement will give you a compilation
error if you put it common then only the compilation successful; otherwise it is there ok.

And then here if you see the q, q is a protected and as a Y is a derived class of this one,
so this is and the r is a public, so it is accessible. Now in order to run this program
successfully, this statement should be commented. So, that you can run it, if you do not
comment it, it will give you a compilation error and compilation error will report the
compilation at this point here only ok. So, this is the idea about the derived class subclass
of class X, which belong to the MyPackage one.

Now, let us come to another class that we have already planned, which belongs to the
package MyPackage 1 is the class A here.

393
(Refer Slide Time: 26:50)

So, here is the declaration of class A here ok. So, this class A belongs to this MyPackage
1, we have included whatever the other main classes are there anyway. So, class A, we
have also do not declare any other explicit member of its own, it has the only constructor
and our objective is that whether this class a can access any other members belong to this
class, belong to any other class either X, Y into the package or not as, Y does not have
any member, so no question, it will consider only any members because that belongs to
X.

Now, here look at this one, so we create an object X of class X; that means, we want to
access any members that belong to the class X or not. Now, so far this one it is not an
error, because it will work because n is defined as a default access specification by
default it can be accessible to any class belong to the same directory, as this class A is
belonged the same directory, it is possible. .Now, here see this p, p is basically is a
private and we want to access a private member from other class A here. So, this will
report an error. So, it should be commented to successfully right.

And q is a protected, protected cannot be X less by a non subclass, as A is a non


subclass, so it is an error and then r is a public member, so it is ok. So, this will work for
you. So, here, in order to run this, so this and these 2 are to be commented. So, that it can
successfully run it ok. So, this is the class 3 classes that we have discussed with the 3

394
different modifications it is there. Now let us come to another package called the
MyPackage 2.

(Refer Slide Time: 28:40)

And in the MyPackage 2, as I discussed it has 2 classes the class Z and class B, the class
Z is basically is a subclass of class X.

But it is in a different directory. Now let us see what will happen, so for this class Z is
concerned. Now, so it is a Z, it does not have any members, so fine only the
constructor. .Now, here this is the default accession, default class member cannot be
accessed outside any other class from the class which is there. So, if it belongs to the
class MyPackage 1 and this class Z belongs to MyPackage 2, it cannot access this default
class the that. So, this is why, it should give an error, so it should be commented.

Next is that private. As you know private member cannot be accessible other than the
class member itself. So, private p cannot be accessed from the class Z, which is in the
other directory or in other packages, so it should be commented as well. Now q is a
protected as it is a derived a subclass of x. So, a protected member is accessible by
inheritance, so this is correct. Now the public is accessible, so for the Z class, which
belong to another package is concerned. So, it can access other than these 2, it can access
other all other things are there. I hope you have understood this concept.

395
Now, this is the Z class, now let us come to the discussion of another class which
belongs to the B, it is not a subclass of this one is a derived class, so a class B.

(Refer Slide Time: 30:20)

.Now, here B again, we do not have any members. So, it is b method is here only, .Now,
here. So, B is basically here we MyPackage p 1, I am explicitly specifying that I want to
create an object. So, X.X new package I create a X and for this X object, I want to create
n p I want to access n p q r, where n is default in the class.

Now, here as it is in the different directory as you know x.n is not accessible. So, the
default variable is not accessible in this program, so it basically is an error. So, it should
be commented and then here X.p, p is a private member cannot be accessed by any other
class belongs to anywhere. So, it is there it is should be right and then q also protected, it
cannot be accessed anywhere. So, it should be a commented; however, r is public, so r
can be accessed from anywhere.

So, we have discussed the different access modification, if it is placed for some class in
one package. And then how the distance classes belong to some other package has the
limitation, so for the accessing of the member is concerned. Now then fine we can have a
demo of this right.

396
(Refer Slide Time: 31:43)

And then the demo is basically you can run this one from the MyPackage one and create
the object then, you will see whether these objects are created successfully or not.
Whatever the comment I have mentioned here, if we put it then this statement will be
correct.

But if you uncomment all the statements, then it will report the errors where the access
specification is violated by the rule of the access protection. So, the thing is for your
understanding, if you run this program and then you will be able to understand more the
things clearly. Now, this is regarding the packages. So, for the MyPackage one concern
and one demo program that you can think about it. So, we will discuss the demo in
details, when we will discuss it. Now another demo program that belongs to the
MyPackage also you can run and you can create it and then you can find it.

So, it will create the 2 things and you can. .Now, here I want to mention one more thing
is that, so here in this demo program I just a limit the accessing of all the package that
those are there, but in that case see suppose I can use import MyPackage 2 and here also
import MyPackage 1 then all the things that are there and here also we can include both
the things are there.

So, I can create 1 class file 1 demo file, so it is a demo 3, which basically import
MyPackage 1 and MyPackage 2 together and then run all the program and then you will
see exactly what will happen.

397
Basically, all these things will be there and then the report or that error will be due at the
time of compilation. So, all the class file if you are not able to successfully compile, so
you cannot build the package and once we are not able to put the class file prior, I mean
after the compilation. So, no way of creating this one if you can successively create it
then demo program will successfully run for you. So, this is the thing that you should
consider on the way whatever it is there. So, this is all about the packages I want to
convey it to you and that is the concept of the packages that you should have in your
hold actually.

(Refer Slide Time: 33:51)

Our next discussion is basically inheritance related much more. We have discussed the
simple inheritance and we have also mentioned at the time of that discussion that
multiple inheritance is not allowed in java. But in some situation, you know multiple
inheritace is not avoidable. It is obviously, erroneous or gives a lot of ambiguities while
debugging your program, but it is also sometimes not avoidable and it makes the
programming easy if we can do it.

Now, the question is that; although technically the multiple inheritances is not possible in
java, if it is required can I do that that how the multiple inheritance is possible. So, we
will discuss that concept. And then polymorphism is also a very important concept,
polymorphism means the same thing, but in different places are there. Now, this multiple

398
inheritance and polymorphism are the 2 concepts which can be achieved by means of
another concept interfaces.

So, in our next module, we will discuss multiple inheritances and polymorphism in the
discussion of the interface. So, the interface is our next topics are to be discussed in our
next module.

Thanks for your attention.

399
Programming in Java
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture – 19
Demonstration – VIII

So, in Java package is very important concept. That we have mention explicitly in our
last module that we have discussed on packages we cover this discussion of package in
two modules. Now this Demonstration we will completes the understanding of the
package concept in Java.

(Refer Slide Time: 00:40)

So, in this today’s demonstration we are going to explain how the built in API package
can be imported in your Java program. So, importing a Java built in API packages. Then
we will discussed about how we can create our own package and use this package in our
own program and then package with access modification is really a big job. So, we will
discuss about the packages with access protection.

And then packages which are there and the classes are there in this packages whether
they can be used in our inheritance procedure. So, we will discuss about inheritance
mechanism with some classes which are there in the package. And then finally, we will
clear our concept about the different access specification that we have known in the
context of package only.

400
(Refer Slide Time: 01:42)

So, let us have the first demonstration in this concept of package our first demo says that
how we can access an API package. So, we know Java have 9 API packages all packages
are readily accessible to a Java program to access a package we have already used one
statement call the import. So, if we write import then the name of the package then the
package will be imported into this program.

Here for example, import Java dot lang dot star java.lang.* this means that it will import
all the classes which are declared in the lang package will be there will be accessible
here. Here accessible means it is like this that in one the same file all the classes those
are there in dot lang package will be pasted here like. So, it is the concept you can thing
like that. So, by means of import it is basically this concept ok. So, you will be able to
paste all the classes which are already define their in the long package they are the
classes test it and compile successfully because, if we want to may store one class in our
one package we should test it compile it then store it this is the concept actually there.

Anyway so, in this case as we see we import one class which belongs to lang package
and actually this class as you see in the program the name of the class is Math.sqrt() Now
here this is the simple class declaration calculator has the two members i, x and one
method p; the p basically use the method Math.sqrt(); a square root is a method which is
defined in the math class. Now, one thing also you can notice for the math class we do
not have to create any object because this math is a static class which is declared in this

401
lang package as you know if a class is declared is a static or a method is declared is a
static.

So, no object needs to be created see basically is a class method, is a class variable
instants variable we have discussed similarly, the class method and instants method. So,
here sqrt in fed is a class method. So, for a class method need not to call create any
object here. Anyway so, math dot square root is basically pass an integer i if it is like
this. So, it will a passed any value i then it will calculate the square root and then it return
the result and store in the value x. So, this program here and running is successfully fine
it is the obvious that this program will run it is there let us run this program 20.0 square
root it will give you the result.

(Refer Slide Time: 04:31)

So, you can understand about it. So, these examples shows a very simple one so, that any
class can be access there that class may be any method also belong to that class also
readily accessible in your program. So, this demonstration is there. So, 20.0 is the value
that has been passed to the Math.sqrt() giving the square root as 4.47 this result is there
ok.

So, this example show that how we can access the package which is there like this the
many packages all packages method in any packages is also can be access.

402
(Refer Slide Time: 05:15)

Now, let us have to another demo that we can explicitly mentioned here java.lang.*. That
means, the entire package will be entire a package is very heavy very large; so not
necessary to include the entire package. So, in lieu of the entire package we can
explicitly mentioned a particular class if we know that it is required in our program.

Here these example includes this fact here you see import java.util.Vector you can
understand what it does mean it is basically accessing one class the name of the class is
vector and this class is define in the package util. So, in Java there is a package called
util and there many class like vector array list array all this things are there it is there.

Now here, if you see. So, in this program in this class the demonstration _ 82 here we
can see the vector class is imported once it is imported then this class can be used to
create any object as we see Vector newVector= new Vector() . So, basically we create a
create and object of class vector which is basically in util package and then this vector
can be used for many other function that code is not here given.

So, this is a one example that a particular vector can be created. Now import is not
necessary limited to only importing one class in our next example we can see that we can
create without importing some method also.

403
(Refer Slide Time: 06:44)

For these things we have to explicitly mention the location of that class. So, without
importing also we can have an accessed to some method which belongs to a package. So,
this example includes this fact again. So, let us see the class here demonstration_ 83
where we can see here we have created one object the name of the object in newList. But
this object of type ArrayList .ArrayList is already define in the class util and here you
can see how we have done it explicitly mention by means of dot that java.util.ArrayList
=new java.util.ArrayList () this means that we want to create an object which belongs to
util the class type is array list.

So, this is also way here you can note that we did not use any import statement. So, these
are the things are there, but the good practice is that import statement to be used in your
program. If we use import; obviously, program will learn little bit slowly that you cannot
understand, but if you do it explicitly this is first or of course, for this speed is not so
important and it is a negligible the speed improvement if we say so. Now, our next
example that we can already have a demonstration that we can instead only one package
we can include many packages.

404
(Refer Slide Time: 08:01)

For example Vector and ArrayList both of the classes if you want to include it. So, what
we do we can do two things import java.util.Vector, import java.util.ArrayList like this.
But instead of this .* is a short form if we do this all the classes belongs to these package
will be accessible to this program here we can see vector new vector similarly array list
new list we can access it.

Similarly, all other methods all other classes which is declare in this util can be access
like this one. So, this is not a complete program quote related to dealing with Vector and
dealing with ArrayList can be included here to make it complete. Our next extra
demonstration is most important that is how a user can create his own package.

405
(Refer Slide Time: 08:57)

This is very important concept because, if we have to develop your own application
software you have to built many packages of your own and maintain them this things.
So, next discussion next demonstration onwards basically emphasize on this fact there
how we can create our own package, how we can maintain them, how we can access
them and how the different protection can be maintain in there all this facts.

Now, here you can see the simple program here where we want to maintain one class in a
packages let us have the demo of first from in this line 8.5 open these one.

(Refer Slide Time: 09:31)

406
So, first now here you can see we have created one class name of the class is myClass
and this class I want to put it into a package the name of the package is myPackage. So,
for this thing we have to write the statement that package myPackage a indicating that
this class will be moved to the package myPackage. What is myPackage? A myPacakage
is a directory that mean we have to built a directory the name of the directory should be
myPackage and under this myPackage you should store this file the name of the file
should be myClass that is the class name myClass.Java.

As we see here we have created one directory myPackage here and then under this
directory we have store myClass dot Java it is not finish, we have to also compile this
myClass and then store this myClass into that directories. So, we have created myClass
dot class the compile version of this Java file and store there.

And one more important thing is that if we want to create if we want to store one class in
a package then that class should be declare as a public access specifier. So, here we can
see we have given the access specfier as a public class myClass. So, these completes that
one class is ready to be put into a package called the myPackage here. So, this class this
class is now after show computing.

So, many steps is now one package is created I hope you have understood that how a
package can be created. So, you have to create a file access specification should be
public and then keep this file and compile this and store this in a subdirectory
myPackage. And finally, put the package statement the package myPackage. So, this will
completes to creating your own package.

Now, once this package is created then we can access this package in our own other
program. So, this is an example showing little bit [FL] it is a [FL] fine. So, here we can
see we are just attempting to access the packet in order to access this one we have to use
again input, it is just same as the user concept we have already learned, but in this case
we want to access the package which belong to the myPackage and the name of the
myClass.

So, import myPackage.myClass and then this is the rest of the things accessing this
myClass object create an object this one. So, this is complicit, but another important
things that you have to note it where this package should be stored.

407
Now, this class the demonstration_85 if it is store in working directory let it be
demonstration_85, then your package should be under this working directory that mean
your myPackage is under the directory demonstration_85 then only you can access it.
Now let us see whether this program that mean demonstration_85 is the main class is
compilable and then executable. So, it is compile successfully and then running also
successfully ok. So, this classes.

(Refer Slide Time: 12:48)

Now, we can see how a package can be created and a component which is belong to a
particular package can be accessed in one file that is also this is basically creating a users
own package here now our next demonstration. So, I have shown an example about that
how we can create one we can place or put one package one class file into a package
similar extension can be done if we want to have more than one file.

408
(Refer Slide Time: 13:22)

Same things can be repeated again like here in this demonstration let us see we create
one package called the myPackage there. So, let us the myPackage directory here, now
here we can see in this my package we have store two class file myClass 1, myClass 2.

(Refer Slide Time: 13:35)

So, all these things again repeated just like myClass program there. So, myClass 1 here
just package statement compile and then shape in the same directory. So, this completes
the putting the myClass 1 class into the package similarly myClass 2 class into the same
package there.

409
After creating this package with two files or more files we can access them into one class
file that is class file should be a root above this myPackage.

(Refer Slide Time: 14:10)

Now, here the working directory here is demonstration_85 under this is just above the
myPackage directory. Now here we can see myClass 1 object is created myClass 2 object
is created and this classes are imported from the myPackage packet. So, myPackage.*
means it imports all the classes.

So, here again I repeat that myClass one as if pasted here myClass two class as if pasted
here as if all the classes are here and all classes as you see that declare there in the
package as a public access specification. So, this way two or many more classes can be
put into package and package can be builder package can growth as the programmer will
at many more component into the package. So, this concept is basically how a user can
create the package here.

Now implicitly as we have already told that implicitly using import statement a package
can be accessed just like user package also know a exception that a package also can be
explicitly located and then there can be access in a program. Our next demonstration
regarding this one let us go to the 8.8 demonstration here which basically explain
everything here these program is basically here.

410
(Refer Slide Time: 15:32)

Here we can see a dot 88 (A88) is the one class file which is already there in myPackage
that is all now let us go to the main program here which basically accessing this one. So,
here so, let us go the demonstration yes.

Now, here we can see after importing this A88 as if it is one class right. So, we can
create an object obj for example, for the class A88; as if A88is declared in this class. So,
this is the explicitly A88can be access as if the package the class it belongs to the
programmers one class look like. So, package gives the access so, easily to the
programmer.

Now, let us have the next demonstration 8.9 using the same concept as the explanation it
is there, but using the method it is there. Now let us have the 8.9 demonstration it is little
bit twist about the 8.8 extension. As if the 88 A88class is already stored their which one
method it is here and we want to access the same method here. So, that method will be
accessible here ok. So, this is the A88method and we are accessing this method by an
application program class the main class here and then we can use it and using the fully
qualified name here we can use myPackage.A88.

So, that mean fully qualified name because A88 is belongs to the mypackage here we do
not have any import statement included here we have commented it without any import
also explicitly we have given the similar demonstration earlier also. So, that explicitly we
can mention the name or location of a particular class and by means of that we can

411
access the class and then object can be creator of that. So, this example; in fact, a
concludes this one.

(Refer Slide Time: 17:44)

Now, let us have the another demonstration about it basically utilization of package in
Java application there mean how we can use utilize this one now for this things let us
consider one class first this is in the package let the name of the class we balance.

(Refer Slide Time: 17:55)

Let us go to this one we have created one package called the myPackage; under this
myPackage there is a one class as you see name of the class is Balance dot Java and let

412
us have a quick look of the class this Balance.Java here. So, fine and we have declare
this class belongs to a package myPackage and this class is very simple the Balance has
the variable name as string and balance has a float.

And then it has one constructor the balance and then it is initializing the members and
also it has one method the show method declare as a public and as you see the method all
are method is public and then construct is also declare as a public and then this class is
also declare as a public. If we do not declare as a public it will compilation error because
non public any method cannot be access to other outside classes it is there because public
is accessible ok.

So, this is basically the class lets have the main class that is your program main program.
So, if this is the main program import this myPackage dot mean balance class is
imported here after this imported here we can create objects as we see we can create a
array of objects size of the array is three here. So, we have created initialized and then
we can display the different elements in it for example, the show method we can call the
show method for each object and it is.

(Refer Slide Time: 19:37)

Now, let us have a quick run for this program. So, that it can the objects are created for
this package class, and then the method belong to that package class is now accessible to
the method. So, we can see that objects three objects in this case are created there
initialized and their methods there members are accessible through there method. So, this

413
basically shows that how we can utilize the different methods, different classes are there
in the package if there in your custodian ok.

Now, our next example is basically give the concept that whether same class name can
be given to two different classes into belong to two different packages. Now, here let us
consider one package say myPackage 1, now here you see under this demonstration 8.1
there are two packages myPackage 1 and then myPackage 2. Here we can say
myPackage 1 and myPackage 2 are the two packages under this working directory and in
myPackage 1 there is a class called myClass.Java same name, but may be structure
different it is the same name with the method msg 2.

Now, let us go to the myClass a message myPackaged 1 method here also same name,
but the different method; so two classes, but the two classes have the same name and
there define in two different packages.

(Refer Slide Time: 21:20)

Now, let us come to our main class main class is here demonstration_811. Now here we
can see I just want to access the two classes which belongs to the two different packages,
but having the same name problem is here we can import it. Now I show import
myPackage1 my dot class there now here is a problem. As I told you this import will
paste or merge two class myClass.

414
Now, in one program you cannot give same name two different class. So, this way if we
give this kind of import it basically leads to a compilation error if we run this things you
will see it, will give an error because it will not take this kind of things because it is
syntactically not valid. So, it is given an error that a type with the same simple name is
already define by this.

So, what is the way out? Way out is here the remedy is that we should stop import here
we cannot do that, but instead of import we can have the full qualified name I have given
the full qualified name by say myPackage one dot myClass. So, it will result that
myClass this myClass is belong to myPackage 1 and we can then successful to create an
object a for that class.

Similarly, for another class myClass, but belongs to my package 2 we can create
successfully able to create another object b here, now if we run it after saving.

(Refer Slide Time: 22:58)

Let us compile and then we will see the a.msg1() ,b.msg2() is resolved although they
belong to the different classes having the same name, but accessible here. So, the
compilation is successful and then we run it also successfully this is the way out.

So, we can understand that the same class name can be used, but while you have to use it
in your program we have to use the full qualified name to avoid the collision. So, this is

415
the one example that we have discussed about it now let us have another example about
this example is basically discussing example 8.12 right.

(Refer Slide Time: 23:36)

We can whether a class which is defined in a package can be used to inherit I mean can
be used as a super class to derive some sub class. So, this demonstration we will clear
this doubt here.

(Refer Slide Time: 23:42)

Now, here let us consider a myPackage package which includes one class belong to this
myPackage the name is Balance class. So, a class is already there in myPackage

416
directory the name of the class is Balance. Now our objector is that we want to derive
some classes from this class Balance as a super class. So, let us have the main class
where we can try to inherit this one. So, let us go to the main method. So, this is at
demonstration_812 is the main class here. Now in this main class you can see we derive
a sub class the name of the sub class is savings; Savings it basically inherited from the
super class balance.

Now, whatever the member elements are there in the balance namely string name then
float balance all this things are readily available here, because of the public it is there,
because this class as made public and all methods. And then member are also public
there otherwise we cannot access through package anyway.

So, Savings and in the Savings class we can declare one member as a branch and another
integer as customer id. So, to fields are declared here in addition to this the constructor is
also declare here to initialize the object of type savings and then a method. So, definitely
this method is basically overriding method, because the show method that is there to
display only two elements, but here we have to in addition to earlier two balance and
name we have to display a branch. So, show is basically also overridden method. So, this
completes the inheritance.

(Refer Slide Time: 25:29)

Now, we could inherit it now we have to do it at whether we successfully inherit it or


not. So, to understand these things our task is to create three objects of type inherited

417
class. Now in this see the current is an array of objects of type savings and we have
created three objects in this case. So, three objects are created and initialize subsequently
those are stored are current 0, current 1, current 2 like this. And now for(int i=0;i<3;i++)
for int i currents to 0, i less than 3, i plus plus we are trying to run this method so, for the
savings class object displaying the elements.

(Refer Slide Time: 26:12)

So, this completes the complete class. Now, let us have the compilation and subsequently
execution then we can see that a method a class which are there in a package can be used
to inherit into some application package application class. So, here we can see 81 fine.
So now, we can successfully compile and execute that inheritance is possible. So, what I
want to emphasize it again that a class if it is there in a package.

So, inheritance is not an issue, and if it is public all this things; so all members will be
accessible if it is private they are then obviously private member cannot be accessible.
But those are the protected those protected member are accessible in the inherited class,
those are the obvious concept we have already learn. So, I do not want to explain it
again.

Now, let us have the next demo. So, our next demo is basically that if the same class
name, but in two different packages. And the class are then referred in a Java program
that we have discussed already right not is there 8.12 we have declared that is 8 point our

418
next demonstration is basically combining all access modification in one file and how it
works.

Now, this program is bit complex and little bit large actually. Now here let us consider
two packages myPackage 1 and myPackage 2; now myPackage 1 composition is that it
has three classes; one class A class X and class Y and Y is a derive class that mean Y is
an inherited class from X. So, the combination is like this.

(Refer Slide Time: 28:04)

Now, we will see the three different classes there in this package one by one. So, let us
first have the class X declaration. So now, this is the class X as we see in this class X n is
declared as a default axis specification p is a private, q is protected and r is public and so
no problem.

So, constructor is made as public the class itself X is made as public. So, that we can use
it in other classes, other application through package concept and then these are the
simple concept that we can print it in this case all members are accessible because they
are belong to the same. So, whether is a public private protected it is accessible within
the same class. So, this class X is successfully compliable and it will executes no error.
Now, let us go to the class X after the class is declaration is over class Y as I told you
here class Y is basically derived class from the X.

419
(Refer Slide Time: 28:59)

So, we made the class Y is a public and then extends X and constructor also a made it
public Y and then we create the things when here now we have put some comments there
because, if we remove the comment then these class will not be executable. Here we can
see that System.out.println attempting to print the n which is the default value there. So,
default is accessible to any class because it is derived one. So, default is accessible to the
derived so, it is not an error there.

Now, let us come to the p; p is declared as a private there in class X. So, now, if we want
to access it in the derive class. So, private is not accessible so, this will give an error.
Now member X is not access now System.out.println q here q which is the protected by
virtue of protected because it is an inherited class so, q is accessible. So, this is ok. So,
protect is accessible and r being a public so, public is accessible. So, after commenting
so, this program will run successfully; that means the access is fine.

420
(Refer Slide Time: 30:22)

Now, let us come to the class a here the class A if we want to print the different members
which is there in class X whether this is accessible or not. So, we import the myPackage
dot X, in this class A because it to access it now public A we can declared a constructor
class A and create and object X of type X. And through X we can see here the default is
accessible two because it is in the same file same folder same directory. So, no issue A
dot X x dot n is accessible.

Now come to the x dot p it is not accessible via A because p is private. So, it is an error;
however, protector is also not accessible because Ax is not an inherited class here it is X
class is there through X the protected class cannot be accessible public is accessible. So,
public is there so, this completes the working of the different classes in the myPackage 1.
Now, similarly go to the myPackage 2 it is little bit different, but in the different sense
that myPackage 2 is has two different classes B class B and class Z.

421
(Refer Slide Time: 31:26)

Class Z is an inherited of class X. So, myPackage 1 inherited like this one. So, if we can
inherited this concept using myPackage 1 so, import myPackage 1 extends this one.
Now, so, for this Z is concerned; here we can see as it is in the different file, because this
myPackage two in a different directive can say. So, the default axis is not accessible so,
it will give an error. So, dot n is giving an error and then the protected is also not
accessible private is not accessible; however, public is accessible. So, in under this only
the r is accessible others are not accessible.

(Refer Slide Time: 32:07)

422
Now, let us go to the B class B object; class B object is same here we can see default is
not accessible, private is not accessible, protector is not accessible, only public is
accessible. So, these will give the idea about the different access specification. So, for
package is concern, now once after creating this package we can use this package if they
are successful in the package form then they can be accessible here the demo program
here.

(Refer Slide Time: 32:32)

So, in this demo we are trying to access the different classes those are there in different
packages and we can creates the objects here the objects are readily available because,
the classes are successfully compile, and then and legitimly accessed here. So, this
completes the access specification so, for the package is concern.

423
(Refer Slide Time: 32:56)

So, there is no different issue; so, so for the access specification is concern other than
information hiding concept. If we have understood the information hiding concept
clearly then you will be able to understand about the concept those are there in package.

(Refer Slide Time: 33:05)

So, package is basically is a more advance version of the information hiding there is the
information that is there ok. So, this is the complete discussion about the package;
obviously, package can be matured the learning about this package concept can be
matured. Once you are involved in the developing of large software, but this is the basic

424
the beginning of this package concept and that is fine. So, this is ok. So, this is the
program I advise you to go for further rigorous practice with the demo program that we
have used here in this program. So, that you can completely you can get more confidence
about this programming. Thank you.

Thank you very much.

425
Programming in JAVA
Prof. Debasis Samanta
Department of Computer Science Engineering
Indian Institute of Technology, Kharagpur

Lecture - 20
Interfaces – I

So, in the last module including the demonstration; we have learned about packages in
Java. Now there are two things in Java which makes the Java programming a unique is a
package and interface. And this is why the Java programming is basically more popular
compared to the other programming languages in particular to build very large and
complex software.

So, today we will discuss the concept of interface in today and in the next module.
Actually, the things need to I mean lectures hours to discuss complete the discussion so
we will take the two modules to complete it. Anyway, today we have some basic concept
of interface and then other some other concepts also will be discussed in the next module
anyway.

So, let us start about the interface, but before going to take the lesson about the interface
we want to start with the abstract class. The abstract class concept we have already
discussed while we are discussing inheritance.

(Refer Slide Time: 01:31)

426
So, a class can be declared as an abstract class as we know by defining the keyword
abstract. Now, let us consider a very simple example this example, say, we declare a
class says geometry as an abstract class. And then we want to have some classes
inherited from this abstract class namely circle, rectangle and ellipse.

Here, geometry basically says that a set of objects geometrical objects rather and then
there are different special objects belong to this all geometrical objects namely circle,
rectangle, and ellipse. Now, let us have a quick look at how such an implementation can
be done in Java using the concept of abstract class.

(Refer Slide Time: 02:21)

So, here we can see we built a built an abstract class namely class geometry here. And
then we put this class in a package. The name of the package as we see MyShape is the
package. And under this package, so there are so this class abstract class is defined by
these three members. One is PI declared as a static and final and then area and
circumference are the two abstract methods that we have discussed.

As you know an abstract class can contain both abstract methods as well as known
abstract method. In this example, we include only two abstract methods here. So, they
are declared as a public abstract double area, public abstract double circumference. So,
this is the declaration of an abstract class. Now, what is our objective is that our
objective is to create the other classes which can be inherited from this abstract class.

427
So, here is the one code what we can see here the circle class which basically inherited
from the superclass geometry. It has the constructors of its own. Here are the dipole
constructors and there is another constructors is only one argument. So, the two
constructors will define the method area here and then the method circumference. And
some method which is unique in this class itself. As we see these are the two methods are
the implementation of the method abstract method which is there.

So, whenever some abstract methods are there in abstract class it is a responsibility of the
programmer to implement it fully. If you do not implement then you will not be able to
create any object of this class that we have created just now. Anyways so this completes
the creation of the class circle which is an inheritance from the class abstract class.

(Refer Slide Time: 04:51)

Now, after this class is over and the next is how the ellipse class can be again inherited
from this abstract class. So, we are going to inherit the three classes from the abstract
class namely circle. And now we are going to discuss we are going to discuss this is the
circle class. And next is it is an inheritance from the circle another is the called the
rectangle class. So, this class has this kind of form we see this is the one member that is
declared as a protect it; that means, this l and w will be accessible to its inherited class.

And these are the method the constructor in this case. And this is another constructors
with the two arguments to pass it is a dipole constructor and this is the special
constructor. So, this is the class declaration and as we see here this is basically

428
inheritance from the geometry class. So, it is an inheritance of the geometry as a
rectangle class.

Now, next class that we are going to discuss this class has come other methods which are
not put into here. So, this is a other method as we see the area which is again declared as
an abstract in inheritance. So, it is defined here for this class, and this is a circumference
which is for this class it is the redefinition and these are the two methods of its own that
are special to this class. So, this completes the declaration of the class rectangle which is
an inheritance of the class geometry.

(Refer Slide Time: 06:24)

Now, our next class is an example this is an ellipse. So, we again derive the ellipse class
inheriting from the geometry it has the methods like this. And it is another constructor
there are few more things are also here. So, this is basically completed the declaration of
this class as we see here area is redefined for this class circumference and the two
methods that are of its own.

Anyway, so we have a full what is called the declarations of three classes namely circle
rectangle and ellipse which are derived classes from the superclass geometry here. And
the geometry class, in this case, is an abstract class. Now, after this definition of these
three classes is there then we are now in a position to create the object of these classes.
Now let us see how we can create the object of these classes.

429
(Refer Slide Time: 07:25)

So, here is the one application program that is basically the contain the main class; so
that we can create the objects of the classes that we have to define Now, we give the
name of this class is GeoDemo and we can see all these classes that we have declared we
have store them in the package form and the name of the package is MyShape. So, we
have to import all the classes that we have stored in the package MyShape and this is the
import statement.

Now, so this is the main program as we see we create a geo object of the abstract class
here. So, this is basically is a basically container we can say geoObject is a container
which holds the different objects of type geometry like this. Now then we create three
different objects of three different classes like circle, rectangle, ellipse. And we store all
this geoObject into this container like this one. So, it is basically an array of geoObject
we can say so this is stored.

Now, let us see how we can process. So, suppose whatever the objects that we have
created in this case we have created three objects with these are the different parameter
pass to the objects. And we want to create the total area consumed by all three objects
that are there. So, we can have a very simple for loop; so we can create the total area
these are the total area is the some of all the areas of the objects this is there and then it
will print.

430
Now, here we can think is looks very simple. What we have done? We have created an
abstract class for this abstractor we have derived three sub classes namely circle ellipse
and then and then we store this thing in an application and then used them process them.
Now here, few things very important to note in this here: now geoObjects.area so for if
you do not thing about this code. Now only this code now geoObjects i.area. So,
whenever the loop will role it will basically bind itself that which area corresponding to
which object.

Now, whenever i equals to 0 this area will bind to the circle objects whenever i equals to
1 this area will bind into the rectangular object, whenever i equal to 2 this area will bind
to the ellipse object. So, geoObjects i and it is just automatically binding with a
corresponding object this is an example is called dynamic binding or it is also called run
time polymorphism.

Because this geometric object polymorphically works for any area irrespective of the
type of the object it is. Now, this is one very good example of usage of the abstract class
so we have used earlier. Now like this type of concept we are now going to discuss other
things. So fine, this we can see from the geometry object we have to derive three classes,
but this derives by means of single inheritance.

(Refer to Slide Time: 10:43)

But in some situations you know we have to have the concept of multiple inheritance.
Now how this concept is there now regarding abstract class and everything as we have

431
discussed this thing that those things are already discussed. So, I do not want to repeat it
fine. So, the abstract method is automatically abstract itself, and then if a class may be
declared as an abstract even if it has no abstract method also this prevents it from being
instantiated. Now here instantiation regarding this instantiation we will discuss the
details and then we should have a good demo on it.

So, that you will be able to understand it and a sub class of an abstract class can be
instantiated if it overrides each of the abstract methods of its superclass. Otherwise, the
subclass object cannot be created that is what I want to say here. And here is basically if
a subclass of an abstract class does not implement all the abstract method which is
declared then; the abstract class then the sub class itself created as an abstract because we
cannot create any object of that abstracts. So, these are the few properties of the abstract
class it has a hold.

(Refer Slide Time: 11:52)

Anyway, now let us see about the concept that is the multiple inheritance is our objective
then how the multiple inheritance is possible. They consider multiple inheritance is like
this say suppose circle object should have characteristics from the geometry object that
we have discussed. Now in addition to this, it will create some other characteristics from
some other classes which are defined there in their draw shape.

So, suppose you want to create the circle with different what is called the colors, with
different shading, with different zooms like this one. All these things suppose it is

432
defined in this draw shape method. This means we want to define one circle which take
advantage of both the geometry classes that we have already learned and then also in
addition to draw circle.

So, this is the concept that if we are able to do; that means, if you able to inherit the
characteristics from two or more classes then it is not a single inheritance it is called the
multiple inheritance. However, Java does not support any multiple inheritance then how
we can achieve this thing? So, there is an alternative way of doing these things; this is
possible using an interface. Now, so here is the task is at what exactly an interface it is.

So, we are going to discuss the interface. In fact, I have introduced I have started this
discussion we giving an introduction I mean discussion on abstract class this because you
will learn about that interface an abstract class is in many ways very similar is very
difficult to find a difference between the two. But the difference is that abstract class
allows only single inheritance whereas, the interface which is very similar to an abstract
class, but it supports inheritance multiple inheritances. So, this is the key difference
between the abstract class and then interface in Java.

(Refer Slide Time: 13:47)

Now, let us have a full concept of the inheritance for multiple inheritance rather and the
interface. As I told you so an interface is basically very similar to a class it is very similar
to an abstract class more specifically. This means that like classes an interface can

433
contain members and methods. However, the difference between the class and interface
is that in case of interface all members are final and all methods are abstract.

There should not be any members which are nonfinal and any method which is non
abstract. Now, this is the difference between the class and then interface whereas, if you
see the class abstract class and then interface as you have already learned that the
membership will be final. And then inter abstract even can container abstract method as
well known abstract method.

This is also on the difference between the abstract class and interface concept and
another thing is that for both abstract class and interface no object can be instantiated.
So, this is a similar this thing we in that sense there are two things are similar. So, the
difference is like this and then the similarity is also like this ok. So, this is the concept of
interface in a very broad sense.

(Refer Slide Time: 15:06)

Now, let us have a more detail concept about it. As you have already discussed what
exactly an abstract class is or rather what exactly an interface is. Now, as we see so what
is the usage of abstract class or interface if you cannot instantiate an object, if you do not
build an object of that class what is the use of it. Actually, all abstract class or an
interface in Java basically gives a template for a class.

434
A framework for a class: so it basically gives a profile or a view that; how a class that
you should have if you want to create your own program; if you follow the concept
according to the abstract class and interface. So, abstract class and interface give a
concept rather it gives a protocol of behavior that should be implemented by your Java
programs that you want to develop it. So, it gives basically the rule of thumb about
creating your own class taking the rule from the abstract class or interface this is the
concept.

And as I have already told you an interface defines a set of methods but does not
implement them, because they are declared as an abstract it is just like an abstract class
also. And a class should implement that methods which is declared theirs as an abstract
method in an interface. That means, the interface is a structure, and then if you want to
create a class with support of interface then it is a responsibility of that class to
implement.

That means, clearly defined all the method that if there in that sense. And as you have
already told you all methods those are there in an interface they should be declared as a
public and abstract. And by default, if you do not declare any access specification then it
will be considered as a public and abstract. And otherwise so it is a thing and then static
methods cannot be declared in an interface. So, that is one important restriction so far the
thing is a concern there in.

But however, in the abstract class also you can declare a static method as well as.
Anyway so interface it is like this all methods will be abstract more clearly all interface
will be public and abstract and no static method should be declared there. However,
members are a concern they should be declared a public final and also static. So, these
are the thing that is equal so for the interface is concerns are there.

435
(Refer Slide Time: 17:44)

Now, how an interface can be created. So, in order to create an interface, Java provides
say keyword it is called the interface keyword. So, it is this is just similar to like the
abstract class to create an abstract class we use the keyword abstract. So, it is like this,
but there are syntactically a few more things are different that we should discuss it. Now
here is an example; so you can see we have declared an interface the name of the
interface is called.

So, interface keyword followed by the name of the interface and as it is similar to the
declaration of a class with in the curly brackets. And then inside this as we see here it
contains one method void call int p and then semicolon, As we see after the method
declaration the immediately there is a semicolon this means that this method does not
have any definition anybody any code.

So, this means that this is an abstract method and again I told you that as it is the default
that this method is a public and abstract. So, we do not have to specify any keywords
explicitly we mean you do not do it. So, compliable understand that this calling method
is a public and abstract. That means any class can implement this interface.

436
(Refer to Slide Time: 19:13)

So, this is the syntax for declaring an interface. Now regarding interface if you have an
interface using that interface you can build any class from that interface; that means.
Here, for example, the interface is a class here we see the interface is you define one
interface. Then this class 1 and then class 2 are the 2 implementations of this interface in
the two different ways two different codes two different programs.

Now, so, this is one idea about it likewise here if we see if we have two or more
interfaces like say interface 1, interface 2, interface 3. Like then a class you can plan or
you can create you can build. So, that it can implement all this interface. Now we can see
this is just like inheritance. What means this class inherits from this all the methods all
the variables that are declared here it will be inherited here or like this one.

So, it is just like a multiple inheritances looks like that is the multiple inheritance concept
in Java it is coming on the way. That if it interfaces you can do it, but if it is an abstract
class you cannot do that all these things should not be an abstract class or any class rather
ok. So, this is the idea that we will discuss more the multiple inheritances in Java using
the interface in due time.

437
(Refer Slide Time: 20:44)

Now, let us have an example quickly; so that we can understand the concept of interface
more clearly. As we see here, so this is a structure as we can see and led this structure we
interface. Now in this structure what we have defined two methods draw and resize.
They basically the method declaration, but not the body this means that all these methods
are basically structured a framework a basically template a protocol so this is the
interface suppose.

And then we can create our own class namely circle here which basically implement
draw a resize method which is defined there. Now, it also can implement for the objects
line. So, different methods draw and this one; that means, here the circle and line or
rectangle. If we see the draw method here in circle or line or draw they are the different
way of implementation. So, that is why the different implantation we can say.

So, this way what we can understand is that so, three different implementations, but it
follows the template or protocol that is given their interface. So, this way the interface is
coming into the way that we can use it. Now, further, if it is a class now this class can be
used a normal class like. So, from this class, we can inherit some other class also with
some other method overwriting whatever it is there.

So, all these things are quiet possible makes it more flexible, more versatile, and write
any way whatever you want actually. Anyway, so this is the idea about that if you have
an interface it gives you a I mean structure. So, that you can follow this structure to

438
create a similar type of objects similar to what is called type of objects rather and then
we can use this in our program. Now, so this is the concept that is there and we have a
good example so that we can understand about it.

(Refer Slide Time: 23:00)

Now, before going to have the full code about the interface and everything; let us have
briefly again summarized regarding the interface and its characteristics. As we have
discussed interface must be declared with the keyword interface. All interface methods
are implicitly public and abstract that I have already told you because you know need to
mention explicitly.

All variables those are there in an interface should be public, static, and final this is
obvious; that this means that the variables those are there in an interface they should be
treated as a constant. No class any method in other class which basically implements an
interface cannot change their values. And interface methods must not be static any static
method in an interface is allowed.

And because interface methods are abstract they cannot be marked final. So, you cannot
do it because this needs to be implemented or defined in any other class which
implements it. So, they should not be final then we all methods are abstract, but not final.
And you can find a note that these are the difference between your abstract class and this
interface class again.

439
Now, enter in addition to this and interface class can extend one or more other interfaces
we have already discussed. An interface cannot implement another interface or class that
is not possible. So, interface only a class can implement it, but the reverse is not possible
actually. And interface types can be used polymorphically.

So, this is the concept is that an interface; if it is there is a type then this type can run
timely bind is if in the example of extra class we have shown that circle ellipse and then
rectangular how dynamically or run time or polymorphically bind with the method called
area like this one; so it is like this ok.

(Refer Slide Time: 25:03)

So, now here is a quick syntactical structure about how the interface should be declared
in a program. Now so this is the syntax that we can see the interface should be declared
with the interface keyword the name of the interface and these are the option. An
interface can extend any other interface.

So, these are the name one and everything, but this is the interface, not the class actually.
Anyway and these are the variable declaration as we have declared all this variable
should be declared static final and abstract as well as, and then these are the public static
and final. And these are the method abstract and abstract method, a public abstract
method so these are the methods.

440
Now, so this is basically an example how a variable or a member in an interface look like
and these value once it assigns it will remain this you cannot change it because it is
static. And then this is a return type that is basically only you can see the semicolon no
body it is here. After this declaration that means this method is declared as an abstract
method and as it is public also keyword is by default it is there ok.

So, this is the idea about how we can create our interface in a program the syntax that we
have discussed it and it is an example.

(Refer Slide Time: 26:28)

So, an item is an interface declaration; it has the variable this is the variable which is
declared as static final. And this is the one another variable static final and this is the one
method that we have discussed here. So this is one example that we can understand how
it can be used to create an interface. Now, this is another example so, we can declare
here a temperature an interface this is a similar kind of things so it is basically templated.
And using this interface we can create a class.

Here we can see in this example interface this is the name of the interface is curves and
then extends circle and ellipse. That means, here the curve is an interface which basically
extends circle and ellipse types. That means these curves will include all the features
which are there in both circle and interface. And in addition to this, it has a method all
these things like this.

441
(Refer Slide Time: 27:46)

Now, basic syntax, that after one interface is created how it can be utilized in our
program. So, it is the concept here then how to interface can be used. So, we can declare
a class name which basically extends this one and implements the interface. So, there is
basically a class can extend some other class as well as it implements. So, it is an option.
So, this way a class one interface if it is defined then it can be used subsequently in the
program.

(Refer Slide Time: 28:19)

442
Now, here is a quick example this is a very nice example to understand the concept of
the interface it is in the same line, as the abstract class example that we have discussed
earlier. Now here we can see this is an interface structure as we know it has these are the
members static final abstract. And these are the method abstract and public and we want
to create three types of object like circle ellipse and rectangle using this concept
interface. Now, let us have the quick look of this how it is possible a good program is
there.

(Refer Slide Time: 28:51)

Now, here we can give the name of that interface as a GeoAnalyzer. This has the
methods as we have discussed and circle here you can see this circle implements
GeoAnalyzer. And this implantation means it will implement this method it implements
this method. So, this is the constructor is automatically for this class we have to do it.
And this is an implementation of this area and this is the implementation of this the area.
So, this completes the usage of an interface in order to implement the circle.

Similarly, likewise, we can create another class for the geometrical object like an ellipse.
So, this is a similar way of creating the class object ellipse and this is the implementation
of the rectangle. Now we can understand that using the interface and the implements it
does not extend you can see in case of abstract class we may use extends; that means,
derived class. But here actually an implementation of the interface which is a totally an
abstract concept and then we can have this kind of objects created.

443
(Refer Slide Time: 29:26)

Now, once this kind of object is created we can create the object see our own method. It
is very similar to the abstract class concept in the same line we can see let this is the one
class that we have declared as a main class name of the main class is geometry. It
obviously, input all the classes that we have created earlier so if they are put in a
package.

Now, after these things we create one method which is a special method in this class void
display. It basically x and y value will display it is like this. Now let us see the main
method that we have declared here. So, these main methods create the three objects
circle ellipse they store in the form of this object. And then we create one what is called
it is not an instantiation we just create we declare we define an object of type
GeoAnalyzer that fine. That means, it is an interface type GeoAnalyzer is an interface in
our example. So, here we see the GeoItem and interface item basically we have created.

444
(Refer Slide Time: 28:51)

Now, here once a Circle c is created we can assign this one. That means, GeoItem now
points to c; that means, circle and then the display method which is declared here can be
called you see whatever be the object the display method looks like the same thing right.
If you do not look about this one and this one display a method is basically irrespective
of the circle rectangle ellipse it basically over the same.

So, this is again the concept it is called the dynamically binding or it is a


polymorphically run time polymorphically binding it is. Now, what we can say is that
whatever be the object it is their area and perimeter can be utilized in this program. So,
this is the idea about we have learned about how the interface concept can be used to
build class. And therefore, subsequently, build the Java program.

445
(Refer Slide Time: 31:51)

The same way the idea can be extended for the other, this is another example that you
can consider.

(Refer Slide Time: 32:01)

Now, inheritance with the interface as I told you an interface also can be used to extend
another interface. So, this is one example that inheritance is the same concept as a class.
That means, the interface can be created as a class so, for the inheritance is concern
interface. As we see here the interface is interfaced chemistry extend this one. That
means this is the interface used to extend the constant where constant is an interface.

446
So, this is an interface and here we can see this interface extends interface creates
another interface chemistry inheriting the constant interface. Here, we can see interface
create another interface law of physics inheriting the interfaces that are constant and
physic. So, it is the same concept it is just if you just like it is a class inherits others like
this one. So, it is the concept that inheritance also it is possible.

Now, so this is the idea about a brief idea about the inheritance. And we will discuss
more inheritance in our next module.

Thank you.

447
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 21
Interface -II

So, this is the second part of our discussion on interface, in the last module we have
discussed the Interface and basically introduces the basic concepts that is there in
interface in Java. So, today we will discuss some more advanced features are there in the
interface and finally, we will summarize the lessons that we have learnt so far the
interface is concerned. So, there are like different classes built in classes. So, there are
also some standard interfaces available in Java.

(Refer Slide Time: 00:52)

So, the there are few of course not many. So, the important the mostly used interfaces
those are already defined they are called the built in interfaces like here, Iterator,
Cloneable, Serializable, Comparable, these are the most frequently interfaces. So, in our
subsequent few slides we will go through each interface quickly and then understand
what they can do for us.

448
(Refer Slide Time: 01:23)

So, let us have the discussion on Iterator. So, Iterator interface is basically if there is a
collection of objects right and then how these collection of objects can be processed. So,
regarding these things the Iterator interface which has been defined in java dot util
package. So, in the java dot util package this interface basically help us to manage the set
of objects we can say the collection of objects.

Here the interface the name is Iterator as we see here this is the name of the Interface
Iterator which has few methods as we see here has next the next and the remove. So,
there the 3 standard methods are there in Iterator and you can use this interface to
implement our own class here is an example for example, how these interface can be
used in implement our own class. Here we can create we can just implement using the
concept this is the class this may be say example Iterator implements Iterator and then
here myShapes is the shape of some objects that you want to have it in the shape
geometry and then this is the Iterator iter object is created.

Now here if you see for this Iterator, Iter dot hasNext; that means, it will automatically
check the shapes the collection of objects and then it will check that whether the next in
the list of collection the element is there or not. So, here hasNext is basically the method
that is there in the interface is basically implements it and then this is the implementation
how it will work there. So, hasNext next similarly remove is basically another interface

449
to remove an object from a collection. So, this is the one example of Iterator interface
that is there in java more specifically in java.util package.

(Refer Slide Time: 03:27)

Now, Cloneable is another interface is basically this interface is basically to implement a


class which can create a copy of an object. So, it is a Cloneable means it will basically
make a copy of the objects, as you see here this interface. In fact, is a new application it
does not have any method it is basically empty and it basically helps us to have the copy
of an objects their copy maybe 2 types; one shallow copy and deep copy. If the shallow
copy it will just logically make a copy and the deep copy means physically make a copy;
that means, for all objects reference variables, class variables, instance variable,
everything they will make a separate instances or copy of the same object. So, 2 objects
will be created having the same things are there.

In some situations the duplicate (Refer Time: 04:26) of the objects needs to be controlled
and so, Cloneable interface can be called for this purpose and in case suppose this
interface does not work it throws exception. So, this exception regarding we will learn
about it. So, anyway if there is any mistake regarding the copying an objects, sometimes
there may not be any permission or copy is not successful, whatever it is there in that
case it will throw an exception which is for the preparing the robust program actually.
So, this is the Cloneable interface and then example here.

450
(Refer Slide Time: 05:05)

We can consider one example here this example is basically show how the Cloneable
interface can be used here.

Say for example, here basically the Car is a class which implements the Cloneable these
are the methods in this class Car and then here you can see these objects we create a
objects of type and then clone is the method that we have discussed here and this method
is basically make a copy, explicitly that is mean by the class declaration by the user. So,
this is the one example how the Cloneable interface can be used in Java class declaration.

(Refer Slide Time: 05:44)

451
And the next is Serializable interface, this interface is basically helps a programmer to
build their classes while they want to communicate or send some objects over a network
to a distance objects or distant pc distant server whatever it is there.

So, this basically helps to make the things called the Serializable and here is a quick
example of the Serializable in again from the Car is the class support it implements serial
Serializable interface whatever the methods we have discussed in the next class we can
copy it verbatim here. So, this will complete the class declaration and here is an example
how the Serialization Serializable interface can be used in the machine. Here you can see
we create the object for writing or reading, from the writing from the network channel or
reading into the network channel or writing into some file or reading from the file.

So, these basically all the methods that we have discussed that is there as an abstract
method interface can be redefined here in the class declaration and can be used here. So,
this is an example of Serializable interface and then finally, the idea about the
Comparable interface.

(Refer Slide Time: 07: 08)

So, here is an example of Comparable means sometimes it is required to compare 2


objects whether they are same or different. So, if it is like this. So, Java developer has
proposed one interface called the Comparable interface and here is an example of this
compare interface and we see how it the method that is compared to which is basically
interface method we redefined here in our class declaration.

452
So, this is basically the user defined redeclaration for the interface method and it
basically compare objects. So obviously, it is up to the user for comparing the different
objects how you can compare one objects with other objects belong to the same class
whatever it is there. So, this will written Boolean values whether true or false like. So,
this is the interface Comparable that is defined in the again all these are also defined in
the java dot util dot package.

Now so, these are the few standard interface usually programmer prefer to have their
own interface related to the particular project and use them in their program, other than
using the standard interface those are there in the Java system. Now this basically covers
all the basic concepts about the interface and before concluding this interface concepts I
just want to highlights few more important things which is very important to remember
whenever you are handling with interface.

(Refer Slide Time: 08:45)

So, the defining an interface as you have learnt that an interface can be defined using the
special keyword that is there in the Java is called the interface. So, here basically the
basic syntax is the interface declaration by using the interface and giving the name of the
interface and then this is the body of the interface. Now, so far the body of the interface
is concerned this body includes few things.

453
(Refer Slide Time: 09:10)

The variables or members and the methods and as you have already mentioned that, the
methods which should be there in the interface should be declared as a public and
abstract there; that means, the method should have the only signature giving the name
return type then parameter list and no body of the method. On the other hand so far the
members are concerned the member should be declared as public, final, static and they
can be initialized by some values actually the methods the variables or members which
are there in a interface they should be treated as a global.

So, if any class which implements this interface has the complete access to all the
members that is there in the interface and the methods needs to redefine the class which
implements an interface. And as I already mentioned while I was discussing about the
interface that if you do not declare a method as abstract or is a fine abstract or public by
default it will be taken as a public and abstract and more one important concept is that no
methods should not be declared as a static. So, static method is not allowed in any
interface declaration. So, these are the few rule of thumbs that you should consider while
you are declaring your own interface in your program.

454
(Refer Slide Time: 10:42)

Now once the interface is defined this interface needs to be implemented. So, this
implementation is by virtue of declaring a class, here is an example how an interface can
be implemented. So, the basic rule is that an inter say this is the class name which
basically implements interface and here there are two things are optional extends clause
is optional and then also it can at one time interface two or more interfaces implements
two or more interfaces. So, this basic idea is that a class can inherit from the other class
that is why the extends clause will take care and at the same time it can implements one
or more interfaces so, this is the concept.

So, then now we have demonstration in our next module to discuss about how all those
things works together and as I mentioned there this class that we should have and that
class should be declared as a public there means be this should be public here for
example, declare as a default it is not allowed. So, you have to mention that this is the
public.

Now there are few cautions that needs to be taken care whenever we implement an
interface is that if an interface in if a class implements two or more interfaces which has
the same method and then that methods should be overridden by the class and it has only
one copy. Now, when we say that same method it means that the methods which are
declared as an abstract in the interface they have the same return type same method name
and same list of parameters.

455
If anyone is different the method should be treated as different and then different in
implementation in the class is required. So, this is the important thing that you should
consider and the methods which basically implemented in your class also that needs to
be declared as a public, because these methods should be accessible by anyone. So, no
private, no protected method as an implementation is allowed in the class
implementation. So, these are few thing that you should note while you are considering
the implementing interfaces.

(Refer Slide Time: 13:02)

Now, here is a quick example here you can see that how an interface can be implemented
by a class, in this case the name of the class is Client and here you see this is the
Callback method which is there in the interface and we implement this method as a
public. And while we implement at the assembly we have to consider the return type and
the list of parameter should match these which are there in your interface declaration,
otherwise this will treat as a completely new methods the methods of it is own in this
class itself, what I want to say here is that. In fact, we are to overwrite the methods,
which is declared as an abstract and public method in the interface declaration ok.

456
(Refer Slide Time: 13:57)

So, this is some standards procedure that needs to be follow while we are using the
implementation of an interface by a class. Now here is another example that we can say
again this is a class Client which implements the Callback, Callback is an interface here.
So, this is the method that we have declared in the interface and implemented here and at
the same time the class which implements an interface it may contains, it may contain, it
may include it is own method as well the methods that is overridden in the interface.

So, for example, here this is one method which is the own method in this class client;
that means, it just like an inheritance concept like. So, it is basically one other way you
can say that this class clients inherits the Callback where the Callback is an abstract class
we can say in that sense. So, this is the idea about how a class can implement this means
that implement means the methods should be overridden and it can include its own
methods if required and no variable should be declared with the same name as that is
there in the interface there. So, the method should be in fact, because it is a static and
public declared in the interface. So, we cannot redeclare or redefine the same variable
name or members in the class implementation ok.

457
(Refer Slide Time: 15:31)

So, this is the idea about some implementation of the interface by means of a class and
Java also allow partial implementation. Say suppose in an interface there are two
methods and you implement this interface by means of a class only one method, then this
class can be treated an abstract class; that means, no that means, that means, no objects
can be created for this class until you override all the methods which are there in the
interface. So, you have to override all the methods so, that you can create an object or
you can complete the implementation of an interface in a class.

(Refer Slide Time: 16:15)

458
And in Java also it is possible to allow nested interface, what is the meaning of nested
interface is that an interface can be declared inside a class declaration. This means that
this interface is a very much local to this class itself; that means, no one class outside this
in class is responsible for implementing this interface. This is the concept of it is called
the nested interface, this is a very restrictive use in the program usually we avoid it, but
sometimes we want to make an interface which is a very explicit to a particular class
only then we can think for this kind of implementation otherwise you can ignore it.
Anyway this is an example how the nested if is possible.

(Refer Slide Time: 17:10)

Now let us look at this small program here and this is the class A declaration as usual the
standard normal class and you can see within this normal class we declare an interface
this is the interface. So, we declare as an interface as NestedIf and the method in it is an
abstract method and then we can inside this class as you have the interface, interface
does not have any utilization until you implements it. So, here is the class B which
implements this is the NestedIf and you can see one thing that NestedIf we have
expansion A .(dot), there is a special location specification that A .(dot), means it is the
interface which is declaring the class A.

If you do not do in this case it will work, but in some situations if inside A class there
more than interface then better to do it like this one. So, otherwise if some interface
already in the same name appears somewhere else then it can give a what is called the

459
ambiguity. So, in order to resolve this we have to explicitly mention that this interface
belongs to which class. So, that is why the specific location mention that is A .NestedIf
means that this is a NestedIf inside the class A.

So, this way we can define it and then finally, we can implement the interface that is
there using the usual concept and then same can be used in your main class wherever you
want to use it. So, it is the basic idea about that it is just like a scope of this interface
which is a nested interface inside a class is basically the static scope and it can be
resolved seeing the program itself and is a local, local to this class itself.

(Refer Slide Time: 19:04)

Now, let us have a very simple example about, what is the utilization of an interface?
Why we go for an interface? What is the usage of the interface? It has 2 important
applications; one is that whenever you use an interface it will it may if it includes some
members which are declared as a final, static and then a final static public they can be
used as a global variable look like and this variable can be shared. So, it is just like a
library of different variables that can be shareable from one class to another class.

So, this is a one example and another example; obviously, the great example the most
significant example that we can inherit in a multiple sense as you know Java does not
support single inheritance, but in an indirect way Java also helps a programmer to have
the multiple inheritance implementation. These are the two main usage and one usage
also it is there runtime polymorphism; that means, that will be discussed while we will

460
go for demonstrating the application of interface in our next module. Now let us have the
first example that how a variable can be shared across the classes if they are maintained
in an interface.

This is an example for like. So, suppose we want in this example here we can say we
declare an interface the name of the interface as the shared constants and these are the
different values and by default they are public static automatically there. So, they are
public static int and these are the different value variables and the values are there. So,
these are the basically we can say this as they are basically static variable sort of things;
that means, they are global look like. So, they can be used one instances in everywhere
there. So, these are the global variable look like as you can see in a more simple way. So,
whenever we declared all these value were members in an interface they can be
considered as a global variable look like.

(Refer Slide Time: 21:25)

Now, once these methods are declared we can use them in a program. So, we can just
create a program look like. So, this is the one class the name of the class is implements.
This class is questions which implements shared constant and basically it uses all these
variable names as you can see here. Now here in this class we define one ask method
which has this kind of structure.

So, if you go through the program you will be able to understand what exactly the ask
question is there, it basically takes a random number and this random number is called

461
prob and depending on the value of the prob it basically return NO. YES, LATER,
SOON, all these methods are all these members are which is already declared in the
interface. So, this is the idea about a simple example of course, that all these methods as
they are they will be used here as if there is a global.

Now so, this is the way that an interface can be used in this case and here is the
complete program that you can see how this program can be used.

(Refer Slide Time: 22:28)

This is a simple example another class ask me which implements shared constant which
use the previous asked method and it has it is own body it is there and then this is the
main methods which basically utilization of all the method in the last slides the ask
method in this slides the answer method and it basically code this one. If you run this
program it will be an interesting output which will be discussed while I will go for the
demonstration in the next module ok.

So, these basically shows emphasized that if you declare an interface then all the
members those are there is basically will be used as a shared variable across the different
classes.

462
(Refer Slide Time: 23:13)

And interface can be extended we have already discussed about these that. So, an
interface truly works like a class as the class can extend another class so, an interface
also can extend another class. So, suppose here the interface A and interface B using the
same extends. So, we can extend the class; that means, in this interface all the method
that is there or all the members which are there in the interface will be also inherited in
this one. So, the basic concept is same as the class inheritance also applicable to the
inheritance.

So, again I want to repeat it that an interface in mostly can be treated as a class look like;
that means, whatever the procedure that we can follow for class it can be only the
exception is that for a class an object can be created; however, for an interface no object
can be created that is all.

463
(Refer Slide Time: 24:11)

So, this is the one idea where the interface can be extended and here is a complete idea is
that on the interface extended the inherited interface can be implemented by means of a
class. So, this is the one example that basically explains how the inherited interface can
be implements. So, both the superclass interface super interface as well as the derived
interface can be used for implementation by another class. And then the multiple
inheritance is the significant what is called the use of the inheritance concept here.

(Refer Slide Time: 24:46)

464
So, here is a example that multiple inheritance means one interface can extends two or
more interface, but it is not exactly the extent rather it is basically the implements
actually. So, if we can plan a class which implements two or more interface then we can
say that this class in fact, multiply inherits two interfaces. So, the concept is there and the
concept is there in the class itself the multiple inheritance can be realized.

(Refer Slide Time: 25:15)

Now here few things have to be more few things have to be carefully noted first of all the
class suppose implements 2 interface i1 and i2 and there is a method say m which is
declared in both the interfaces. Then in the implemented class which methods needs to
be implemented in this regard I want to say this way that if the 2 methods are same the 2
methods are same in the interface in the sense that they have the same return type and
then same list of arguments, having the same type then it basically absolute no problem
you have to override only once.

Otherwise, all the methods which are there we have to override in the implementation
class implementation of the interface. So, this way it basically multiple implements all
the interfaces they are by multiple inheritance it is like this one.

465
(Refer Slide Time: 26:23)

There is another also example where we can have the class extends one class and
implements another this is also one example of multiple inheritance in there. So, by class
extends for example, class B extends class A and implements interface i then it basically
is a multiple inheritance concept it is there; that means, it extends class B A means that B
will inherit all the methods and members those are accessible to the class A class B it is
there in addition to the interface methods and the interface variable also accessible to the
class there.

Now, again another important rule that if the two interface have the same variable
declaration then it will give a compilation error that you have to somehow take care
check that the two interface does not declare the same members variables in duplicate in
the two interfaces or more than interfaces which are basically in used in multiple
inheritance and multiple inheritance is not limited to only two interfaces any number of
interfaces can be considered. So, a class can implements two three or many interfaces at
the same time, but extends whenever it come into the picture it can extends only one
class that is the important what is called the things that you should note ok.

466
(Refer Slide Time: 27:47)

So, this is a concept that and if you want to specify explicitly some interface and then
again the super keyword can be used. So, here is an example for example, super method
name is basically in the InterfaceName we can discuss about if it inherits from others
name to resolve the ambiguity if any. So, the super concept it is basically same way it is
basically namespace collision resolution as well as the method resolution. So, this is the
same concept also extendable to the interface here.

(Refer Slide Time: 28:19)

467
Now, we have learned about the interface and then more on the interface will be
discussed while we will have a quick demo on the interface and we advise you to have
the good lessons in the interface demonstration.

Now, our next topic that we are going to cover is very important topic that this topic is
basically to address the questions that I have mentioned here. So, there definitely is a big
question that how a Java programmer a software programmer can develop the program
which is very much robust; that means, fault free tolerant program. And then there are
many errors and particularly it is the concern whenever the program size is increased
from lows low size low volume to high volume because as the code size will increase the
number of errors possibility will increase so, how to deal with this situation. So, all these
things will be discussed in our next discussion that discussion is called multiple is called
exception handling concept.

Thank you; thank you very much.

468
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 22
Demonstration – IX

So, we have learned about the interface in last two modules and this is a plan for this
module plans for an I mean quick a demonstration of the different concepts that we have
learned in our lecture session.

(Refer Slide Time: 00:36)

So, in today’s Demonstrations mainly we have planned that how a user can create an
interface and then maintain it in their package. An interface as we have discussed that it
follows certain specific properties so if all those properties are not satisfied then whether
the interface creation will be successful or not that we will learn it. And then interface is
mainly used for inheritance purpose more specifically it is a multiple inheritance. So,
single inheritance as a multiple inheritance using interface will be discussed. And
another great application of the interface is to provide a dynamic binding in the form of
runtime polymorphism so, that will be discussed.

And then we have also mentioned that the abstract class and the interface has many
similarities between the two. So, what is the difference between the two so, in our last
demo that we will try to clarify further.

469
(Refer Slide Time: 02:04)

So, let us have the demonstration fast this is regarding how we can create an interface.
So, these are the first program that you can think about how an interface can be created.
So, we have to first create a package where we have to store the interface. let us this is
the name of the package, my interface. We have created a subdirectory named my
interface whereas the interface will be stored there. So, let us go to the subdirectory of
my interface and as we see there is one program then you can just open the program.

(Refer Slide Time: 02:22)

470
So, this a program, yes. So, this is the one program that we have developed just this
program as you see the package statement includes that this my interface is the in the
package named my interface and then the name of the interface as we have mentioned
here with the keyword interface the name of the interface is an interface. And in this
interface, we include two elements an as a member type integer and then the method
display or we can type void.

And as we see the member elements that we have discussed here we do not have
mentioned explicitly, but as you know in case of the interface the member element
should be public, static, as well as final anyway. So, these are the default explicitly you
do not have to mention implicitly also if you do not mention anything in an interface if it
is declared they will be created as a public, final, static and the method as we have
mentioned here the method should be public and abstract. So, we have we do not have to
mention it explicitly again. If you do it very it is good if you do not do also the java
compile time compiler will take care of it.

So, this is the interface that we have created and we stored this interface in the package
my interface. Now, let us see the application of this interface in our program.

(Refer Slide Time: 03:56)

So, for this we can write one program here as we know an in interface can be used if you
want to use this interface then a class should implement it is. So, this is a first the class
declaration the name of the class is Demonstration underscore 91 implements the an

471
interface which is in the package my interface we have to input this of course. So, this is
the input statement as we see in the code at the top.

Now, so this method the method in this class demonstration as the implementation of
display because in the interface the method display is there. So, we just implement the
code the display here. So, the code includes a simple print statement, fine and as you do
not have to do anything the member element so no issue it is here and in this method the
main method as we see we create an object of the class Demonstration underscore 91 and
then we call the method display is basically interface method it is here.

And also in the last statement, you can note it is basically the print state statement in the
main method, but it can access the member elements which is already there in the
interface method a. So, this is the way this program compares with use and interface and
let us run this program.

(Refer Slide Time: 05:20)

Here, in this case, the main program is Demonstration underscore 91. So, if you run it,
so, if you run it we will see exactly how it works ok.

472
(Refer Slide Time: 05:42)

So, the program is compiled successfully. So, this program runs it, right. One thing you
can see whenever you create an interface a class file also should be stored there as you
see in my interface both the interface in the form of .java file as well as the .class file is
also stored there. So, it is the customers as we know the process of package creation both
.java file, as well as the class file, should be there.

Now, so in the interface, as you see that thus keywords public then final static void a
method is not necessary. So, if you put it that will work fine no problem, but if you do
not put it also it will work of it is own no problem. Now, our next demo let us have the
next demonstration after knowing how an interface can be created and then how the
same interface can be used in the program.

So, our next to the illustration that the whether we can create any object of the interface
type? Now, so, in this illustration will give you an idea about. Let us consider the
interface.

473
(Refer Slide Time: 07:03)

Let us consider an interface C here. So, this is the interface ok, built it here. It can be
stored in any subdirectory, in the same directory so, this is the interface. Now, our
objective is to if we attempt to create an object of this interface so, what will happen?
Now, let us see the program that we can write it a class program maybe and then we
want to create an object of this.

So, let us have the class program here. So, this is a class program the class file name of
the file is Demonstration underscore 92 and here you see the main method. The main
method is basically in the main method we try to create objects of the type interface there
are many ways we can create. So, in the first statement as we see the C is the interface
type and small c is an object name-new C. Here we want to create an object of the
interface C. As we told you as interfaces is an abstract so, no object can be created. So,
definitely, this will leads to an error.

And, then so, the last two statements you can make it comment ok. So, we will discuss
about the last one. Now, let us see if we do it whether we can do it or not.

474
(Refer Slide Time: 08:42)

Now, as you see here is a compilation error in the statement where we have attempted to
create an object of interface C so, it is not possible. So, now, let us again revise the
program so that we can comment on this statement and then now the other two statement
let us see. Now, the other two uncomment it so, other two statements uncomment,
nowhere again. So, here C is an interface type and it create an object c 2, this is quite ok.

Here basically we so, there is two difference between the first statement and the this
second statement. The second statement basically creates an object and instantiation by
calling the constructor, but here we just simply declare an object c 2 of C type. So, this is
quite possible we are declaring only, but not creating a new object, no instantiation is
involved. In our second case also we can declare an array of types C through an array of
the interface object, but not any instantiation. So, what we can say is that instantiation of
an interface type is not possible however, declaration of interface object is possible.

So, in that sense the last two statement is correct. Now, let us see if you run it. So, this
program run successfully this means that we can create it. Now, we will see the usage of
this kind of declaration in our next example we will discuss it, not now ok in due time.

475
(Refer Slide Time: 10:30)

So, now we have discussed about the interface; how a interface can be created and then
how the same interface can be used in our class program. Now, as you have told that an
interface should be implemented and in the process of implementing all the methods
which are there in an interface should be implemented successfully. If you do not
implement any method or if we implement one method as a private or something other
type then it should give an error.

So, now, let us have the complete program here. Here in this code we see the first few
declarations about Interface I1. In this interface, we declare one field called PI and
declared public static final that is ok. Also, we declare another member element lambda
the floating type. Now, so, this is fine and then also in this method in this interface we
declared on a public abstract method by default namely the void method 2; method I2
here ok.

So, all these things are perfectly it will work because is as per the specification of the
interface declaration. Now, as we know in the case of the interface only the member that
will be declared as a static no instance variable is not possible. Now, let us see if you
want to declare a variable say x of type integer and it is declared as 100 and so, these
basically considered as an instance variable. So, this leads to an error if we run this
program. Fine, we run it, later on, let us have a few more discussions about it here.

476
(Refer Slide Time: 12:12)

Now, here class A1; class A1 implements I1 and this is a simple implementation where
we have the class A itself its own member A1 and then method 1 it's own and then
method 2 is an implementation of the interface method. And as you see as the class A
implements I1 all the elements those are there in an interface are readily accessible to
this class A. For example, PI this is accessible via the method of its own method I1. And
now the main class as we see in the main class here we just create an object of class A1
and then all the methods which basically implements the A1 including the class A1 own
method is invoked here.

So, this will run successfully, but before running this program that definitely we should
comment the int x. comment int x should be commented here no next one, now fine. So,
this program compilable, as well as executable so, let us quickly compile it and then we
will come back to this program.

477
(Refer Slide Time: 13:25)

Again making the x as an instance variable and then see whether it work or not. So,
compilation is successful, no error has been reported and then this is the execution of the
program. So, it basically calls method I1 and method I2 from the program itself. As you
see method I1 can access the pi which is defined in the interface now let us come back to
the program again and here we are in the process of creating the instance variable here.

So, in int right now. So, here int x equals to 100 as we know that this is basically if you
do not specify the keyword that is basically public what is called the public static will be
default there. What about the int x declaration so, this comment keep it here no problem.
this one. Now, let us see that is what this basically creates an instance variable basically
run compile.

478
(Refer Slide Time: 14:46)

Now, here we can see int x without any initialization it indicates that it is basically as it
works as an instance variable. So, if we declare without any public static final keyword it
will automatically specify this one but this is only applicable after the initialization. You
should if it is a static variable you should initialize this one. As there is no initialization it
is as an instance variable and no instance variable declaration is allowed in an interface
method. So, this example explains that we cannot declare any instance variable this one.

Now, here so, we have learned about that a class can implement an interesting and
interface. Now, it is interesting to note whether an interface can implement another
interface or not.

479
(Refer Slide Time: 15:38)

So, here is an example as we see here I1 is an interface declared with its own member I
as 555 and its own public abstract method namely print interface and here is a second is
there I2 interface basically attempts to implements I1. In fact, all the entire course is
invalid code because I interface I2 cannot implement another interface. Now, if we run
this program then it will report a compilation error.

As you see in the statement interface I2 implements I1 it basically is an error indicated


here. So, instead of interface I2 if we write class I2 implements I1 it will work possibly
and another thing is that in the last statement print interface if we made it we have to
make all the method that needs to be implemented as a public. Suppose if we declare as
default the print interface method in class I2 yes, just write public term remove ok, fine.
So, here it is a default.

Now, let us see no default method implementation is allowed or method implementation


with any other access specifier is not allowed. As we see here in the void interface it
gives an error so, we have to make it public there then only it will be there. Now, a class
can implement another interface if a class implements any methods which are there in an
interface that methods should be declared as a public that we have learned it here ok,
right. So, we can run it.

480
(Refer Slide Time: 17:52)

Our next example, whether an interface implements an abstract class? As we know an


abstract class in many ways similar to instant interface that abstract class also can have
the abstract method that means method without any code and then it also can include the
static variable. So, here you can see in this example a class C is an abstract class as we
have declared and here the static variable is declared as a and it has one method print, but
in case of abstract class we know it can include both abstract method as well as non-
abstract method; in this case it is non-abstract method.

Now, if I if we attempt to implement interface this class C that abstract class by using
implements it is basically invalid. Now, if we run this then you will see this program will
not compilable actually. It will give the compilation error as we see interface I2
implement C is basically it is not allowable to implement this one ok. So, no abstract
class also can be implementable using any interface, but a class can be a plan to
implement this one.

481
(Refer Slide Time: 19:19)

Now, one thing is that no method or any variable can be declared final in case of
interface it will lead to an error. Here is an example. Here we can see interface I1 which
has one static variable public final it equals to 55 by default it is final and now, the
method here we can declare you can see we have declared the method as a final and
static. Note, these two keywords are not applicable to any method declaration in an
interface only public and abstract is applicable. So, by default it is abstract so, final static
is not possible. So, this code will work only if we remove the final and static from this
one.

Now, let us have the final static and learn it and one by one if you execute it will see it in
the next code basically class C implements I1 it basically declares its own method public
and then implements the print interface here. As you see there is an error so, the error is
the modifier final not allowed here. Now, let us remove this modifier final and run it
again keep it static ok. Now, run it again and let us see whether a static keyword is not
there. Here we can see it also reports an error missing method body or declares abstract.
As you have declare the abstract it is not taking this one. So, if we remove this static
again it will now final, public it is basically, abstract we can write it or not write now it
will work. So, void printed you have to declare public so, that is fine.

So, declare the public in the class implementation as we have not declared the public all
the implementation of the interface method should be declared as public here ok. So, fine

482
now this program runs successfully. So, there is a mistake regarding the name of the
class file. So, that is why it gives an error that it did not find the class file. Now, we have
changed it, yes ok. We are compiling; yes, the compilation is success full in this case
running this program anyway.

So, our next illustration anyway. So, the last illustration is not meant for any what is
called a class there, only for the explanation that it will require the few properties to be
satisfied.

(Refer Slide Time: 22:43)

Anyway, so, our next example basically explains the single inheritance. Now, here let us
have the loop of the code interface I1 with it is public static final variable x and then it is
method 1 and this interface I2 extends I1. So, an interface can be extended from I1, but
cannot implements. Now so, extend means I2 inherits I1 and so, as a process of
inheritance so, it has its own members y and its own method which is also abstract is
declared because it is an interface method. Now, class A1 implements I2 so, whenever I2
comes to this picture. So, by virtual of inheritance all the way method that is there I1
method 1 also now inherited to I2. So, here again, see in this class A1 implements I2
method as we see we declare one variable on its own. This is the class A1 variable and it
implements method one which is basically inherited from I1 via I2 and then also method
1 and method 2.

483
And, as you see here x and y are the two members who belong to the interface I1 and I2
and by the process of implementation class A1 has the readily accessible to these values
x and y here.

(Refer Slide Time: 24:18)

So, the main program looks like here we create an object of class A 1 and then we call
the method, method 1 and method 2. So, if we call so, all the methods and then they are
variables those are there in the interface will be readily accessible to this one. So, let us
have a quick execution of this program followed by the compilation.

So, we can see yes, we can see that this program is now successfully executed and
compilation there is no error there. Now, so, this is the idea about single inheritance;
now, let us have the demonstration on multiple inheritances.

484
(Refer Slide Time: 24:56)

Here again, I1 is an interface as we declare one of the static variable I here and print run
method in interface I2 is an again with there is again j as a static variable and print I2
methods are there. Now, multiple inheritance here as we see class A implements I1 and
I2. So, this is basically the idea about how to multiply a class that can inherit both from
I1 and I2. In the last example, we see that I2 inherits I1 then class implements I2. Here
basically class A can implements I1 and I2 here I2 is not necessarily inherited from I1 it
basically.

So, here as the number of inheritance can be implemented by a single class; for example,
class A implements I1, I2 and I3 and so, on we can write this one. Now, in this class
implementation as we see A value is the value of the class variable A and then print 1 is
an implementation of class interface I1 print I2 is an implementation of interface method
I2 and finally, the print A is a class A methods who basically have the full access of the
static variable those are there in interfaces i and j namely.

So, this is the program as we can see the multiple inheritances by the process of multiple
inheritances we can access all methods that are there in an interface as well as all
variables those are there in the interfaces ok. As we see this program run successfully,
now there is an alternative way of doing multiple inheritances our next demonstration is
to explain this one.

485
(Refer Slide Time: 26:47)

In the last example as we see class A 1 implements I1 and I2. Now, both extends and
implements can be added there; this is also one way of inheritance multiple inheritances.
In this example as we see class A is a class and interface I is an interface and will see is
the class B extends class A; that means, it inherits the superclass A as well as implements
I it is also inherited basically the some variable as well as method.

However, this implementation as it is class B should implements I the method print


should be defined here in this class as we have seen the public void where is a print
interface method. So, as we see interface I the print interface method is being
implemented here that print and then call it here and class B basically ok. So, it
implements the print interface method in an interface and then print B is basically its
own constructor who is basically called the class A constructor; that means, superclass
constructor using the super keyword and then also call print interface methods because,
this constructor has the access of because of the implementation. And the main class is
very simple here. The demonstration underscore 99 is the implementation of this where
we can create an object of class B and then we can call the print B the method of class B.

So, this is the one example as we see the multiple inheritances by means of extending I
mean inheriting a superclass as well as implementing an interface. Now, there are other
cases where it can extend on class A implements two or more interfaces at the same time.

486
(Refer Slide Time: 28:48)

So, this example is here class A is a class interface C and D are the two interfaces and
you see is a multiple inheritance form where class B extends A, that means A is the
superclass, class B derived from A as well as is implement C and D that mean class B
also inherits from C and D. That means, that all the static variable those are there in C
and D namely j and k is also accessible as well as the variable which is protected in class
is also accessible. So, we can see this method that is there or this class or main method
we can say can access all the elements by means of this multiple inheritance. So, this is a
one simple main method as we see here we create an object B which is basically derived
based on the multiple inheritance and then call the method print B ok.

So, this is the different way that we can see that how multiple inheritance is possible with
the help of interface as well as class A. Now, what is the usage of this interface we can
do the multiple inheritance, this is the one application. Our next example basically
explains our next example explain that the usage of the interface; in fact, an interface can
help to support the shared variable to use across the many packs’ many packages or
many classes in different packages.

487
(Refer Slide Time: 30:38)

So, here is an example as you see the interface includes declarations of some variable go
to the interface in the package my interface go to the my interface. So, we have declared
one interface here. This interface includes some static variable which is declared here;
NO, YES, MAYBE this one. Now, so once this interface is declared and then stored in
the package, then any other class can use them as a global variable look like so; that
means, it is called as shared variable in that sense.

(Refer Slide Time: 31:10)

488
Now, here is an example of one class which uses basically interface; that means the class
question implements all this shared constant to the basic global variable we can say. And
in this case is basically you see without any declaration it basically used return YES,
return LATER, return SOON all these things and here is a simple code we can use the
random function which is defined in java.util it will basically generate a random number
and based on the random number generation it will print all these values depending on
the random probabilities.

(Refer Slide Time: 31:34)

Now, here this is another class that basically uses the same things here and we define
another method called answer and it basically take the results first do it and based on the
result it will execute this codes are there. Now, let us have a quick method. In this class
is as we see go to the next, so this method basically creates an object of question class
which is declared which use the interface or implements the interface.

And then for this class, we use the ask method. Ask method generate a random number
based on the random number it will print either YES, No, SOON, NEVER, maybe all
like this one. If we run this program let us see what is the output it will give. It will give
the output as it is a probabilistic one. So, different execution will keep you not
necessarily give the same output in this case ok. In this case, we can see this is the
output. If we run the same program again we may see different output like this one if we
run again it can give another output and so on.

489
So, it is basically a probabilistic program by means of generating a random number, but
it will be discussing about how the shared variable can be used across the different
classes. Now, we have to discuss in the ok, what is the difference between interface
object and then abstract class interface type and then abstract class declaration.

(Refer Slide Time: 33:09)

Now, we have let us have the one program here and it is a basic idea about the
inheritance and by means of inheritance we can create many objects there and let us go
to the main class ok. First, discuss about the interface class here. Interface class goes to
the interface class interface go to the interface, fine no not this is the interface right ok.

490
(Refer Slide Time: 33:44)

So, now, this interface is defined in my package in the package myInterface. The name
of the interface is GeoAnalyzer as you see this geo-interface geo analyzer interface has
one static variable namely pi and then two public abstract method areas and perimeter.
So, this method is basically the type and now we want to create few classes which
implement GeoAnalyzer namely circle, ellipse and rectangle. So, this is the
implementation of circle class which implements GeoAnalyzer; this is the
implementation of the ellipses class which is an implementation of GeoAnalyzer and
GeoAnalyzer this is the implementation of rectangle class which is the implementation
of the GeoAnalyzer it has its own this one and this one ok.

So, now, we see the different class implements the GeoAnalyzer interface by the
different methods actually in their own way; circle has its own implementation, ellipse
has its own implementation, rectangle has its own implementation. Once this
implementation is done now we can come to the main program which basically create
the objects of this.

Now, here we can see the demonstration 912 is the main class and there is basically the
method includes a display which basically take x and y, namely the area and perimeter of
the geo objects. And here we can see we have created three objects; one object c of type
class c, another object e of class Ellipse and another object r of class Rectangle.

491
Now, here Geoanalyzer geo-Item the interface and geo-Item is an object of interface we
can just declare. So, we have declared and then once it is declared we see it basically
holds the class c, basically the upcasting c is equal to geo item. Now, if we do this then
we can call the display method which is defined in the main method by calling this geo-
Item.area and geoItem.perimeter. Similarly, if the geoItem holds the reference to the
ellipse object, then also same method can print it. But, in this case, this geo the display
geoItem area for the referencing of ellipse object call the method area which is declared
in ellipse class.

And, then again if it refers to rectangle and then displays area of this one, it also refers to
the methods that are there in an interface rectangle in the class rectangle. Now, here we
can see the display method is basically binded polymorphism. The different the display
methods can display area, perimeter for the different objects as per the references there.
So, it is a great example of polymorphism by means of interface.

Now, this program if we run it will work for us, now again repeat the same thing, but
using the abstract class. So, in the previous case, we have discussed about Geoanalyzer
as an interface we just want to do the same thing by means of abstract.

(Refer Slide Time: 37:08)

Here is basically this abstract class is declared in a package let us have the package it is
there ok. So, this abstract class is declared here go to the abstract class their geo
geometry. So, here we can see public abstract class geometry is an abstract class here and

492
here we define two methods and abstract method abstract as you know the abstract
method means no code is there just look like a very similar to an interface.

Now, this basically example to illustrate the similarity and dissimilarity between
interface and abstract it is there. Now, let us have the second same way of class
implementation it is basically extended because circle should extends geometry here we
can see circle. Now, the difference we can note in the previous case circle implements
Geoanalyzer, but here geometry being an abstract class we cannot implement, we just
simply circle extends geometry. Likewise, Ellipse extends geometry and then Rectangle
extends geometry as a process of extension is basically single inheritance as you know.

So, it basically inheritance or you can say override the method those are there in abstract
method incase of geometry. So, these are the three implementations of three classes
extending the geometry object and finally, the main class here demonstration underscore
9.13 so, this is the main class.

(Refer Slide Time: 38:35)

As you see the main class here it is more or less similar to the previous example user
interface. Geometry we create we basically declare an array of what is called the objects
of geoObjects of type here three array size is three here arrays of the abstract class
method we can say just the interface objects we have created in case of interface in case
of abstract class also the object can be created as we see here. And, then geoObject 0 we
create an instance of the class circle and then it is basically assigned to the location 0 and

493
similarly a rectangle instance and ellipse instance are created and we call the we pass the
parameter to I mean instance share them properly.

So, these are the instantiation and instantiation, but after the instantiation they are
basically referred in the abstract class object like geoObject in this case and here again
runtime polymorphism as we see in the next for a loop. So, here total area geoObjects
i.area. Now, for i equal to 0 so, this will this .area refers to circle objects on the other
hand for i equal to 1, this area refers to the Rectangle objects and then for i equal to 2 this
area refers to Ellipse object. So, again it is an example of runtime polymorphism.
Because it is polymorphically resolved that different method depending on the objects it
is there although it looks like same for all calls actually and if you run it the similar to the
interface it will run and then give the execution ok.

So, this is the right. So, this is the successful execution of the program. So, what we have
learned about here that more or less interface and abstract behaves in the same manner,
then why java developer maintains both the thing? The difference only here is that
abstract class if you declare it cannot be multiple inheritance or whenever an inheritance
interface is there it can be multiple inheritance. So, this is the only difference between
the abstract class and the interface otherwise both the concepts are more or less same.

So, we have learned about the interface and if you have further any doubt you are most
welcome to post your queries and all the programs that we have used in their
demonstrations you are free to use it and then test it so that you can practice it much
more.

So, thank you very much.

494
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 23
Exception Handling - I

So, let us start this lesson with a question. So, suppose what is the big headache for a
programmer, whenever the programmer has to develop a very large and complex
software. So, many questions may come whether we have to design it properly or the
coding should be done by an expert programmer or there should be adequate testing
while this one.

In fact, all three things are very much essential, and in fact is a concern for any software
development team. Now, java is famous and java is basically at the top, because at the
time of coding the programmer can introduce some things into the program itself, so that
the program is fault free, error free, and then robust program development is possible.

Now, this is possible in java using a concept, and very useful one concept which is
basically unique of its kind, and then java only the java language provides its other
programming language C++ in some extent it provides, but it is a very unique, and new
of its kind in java, the concept is called exception handling. Now, exception handling
coming into the way to dealing with errors in the program. Now, before going to have
the discussion on exception handling, we should understand about what it does mean
about errors in a program.

495
(Refer Slide Time: 01:53)

Now, so for the concept of error is concerned, there are two types of error in java
programs. One is called the compile time errors, and another is called the run-time errors.
So, the compile time errors is very easy, because it is not your headache to debug it.

If you write some program which is not seen practically correct that is not written
according to the language specification, then it will report an error. And this report, this
error will be reported by the compiler java compiler java, C program itself. So, this is the
compile time error. And there are many situations in the compile-time error is concerned.

But, I am not so much concerned about compile time error, because if you write a
program according to a right syntax of the java programming language, then compilation
error is no more there. But, if you have suppose some mistake programming mistake
right, then compilation compiler will report an error, and you can fix the error, and then
you can develop the program you I mean successfully compile. Once the successfully
compiled a program, there will be compile-time error, error free compilation, compiler
free program.

On the other hand which is more concern more headache, this is called a run-time error.
This is very difficult, because java program is written successful is compilation is
successful, but while it is running the program that time, it does not give the correct
output or its abrupt termination or there maybe some causes with damage some files
stored in a database or like this there are. So, these are the errors is very critical.

496
And if we do not take care in a very sincere manner, when it leads to a many (Refer
Time: 03:38) there. So, many loss in many resources concern is due to this run-time
error, so that is why java run-time error needs to be checked, needs to be controlled,
needs to be maintained manipulated properly. So, this lesson is basically dealing with
this one.

(Refer Slide Time: 03:55)

Now, let us have an idea about what is the compile time error, and what is the run-time
error. If we see this program, could you check the program, and tell me what are the
possible points or locations there, it gives the compile time error ok. If I can help you,
you can see I am pointing out. So, there is a location of the error, and here is an error,
and here is the error, and here is the error. You can understand why there are the so many
errors are there. These are the errors, because according to the java syntax it is not
written.

On the other hand if we see other program, may that we cannot find any errors here, this
is correct in all sense; maybe that this is an error, because in this class a public is not
accessible, whatever it is there. And so this is the idea here and this is also we can find
one error, you can tell me why this error, because you have declared a method is abstract.
Whenever we declare an abstract, no code should be included here. So, there are few
errors these are called compile-time errors.

497
So, when you try to compile this program, java will specifically state in this line number
this error, in this line number this error, in this line number is this what about the things
are there, in report the line numbers. And for each line numbers, whatever the
compilation errors are detected will be reported to the programmer, so that programmer
can correct it, and then right and then syntax syntactically correct program can be
written. So, this is the idea about compile-time errors.

(Refer Slide Time: 05:35)

Now, let us come to the example of there are many situations, when the compile time
errors are there. From the last example, you can understand that. There are so many only
few of course; there are many reasons where the compile-time errors are there.

In fact, a java program when starts is programming right programming have it is then
usually at the very beginning he faced many errors compiled time errors. And whenever
he become experienced, and then from beginners to little bit advance then next part, then
he will be quickly able to see that this is a compile time error. Usually, do not face
compile-time errors actually in the program.

498
(Refer Slide Time: 06:17)

Now, so this is the compile time error, and then what is the run-time error let us have a
look. Now, this is the one program we can see, and this basically if you see the program
and if you compile, it this will compile successfully, because there is no error in this
program; so, for the compilation is concerned.

But, whenever if you want at try to run this program, we will be able to see that all this
input will be taken this program successfully, there will be no error. So, there will be
run-time error. But, there may be run-time error, whenever we have to give some other
input in the same program.

499
(Refer Slide Time: 06:53)

For example, if we give this example this input, then you will see these program reports
an error. So, this is basically is a unknown format error because of this statements.
Because, this statement only take the integer; but you have passed as a floating point
number and that will not allow. So, this is basically run-time error.

So, what we can say is that so far the run-time error is concerned; the program can run
for some input. But, if it cannot run for all possible inputs, then it leads to run-time error.
So, when you write the program in this case for example, you have to define the program
in such a way that if it works for the integer type data only, then, you have to check it. If
it if a user gives other type of input, then accordingly it will it will check it and then
report it, so that that kind of input can be bypassed, and then program cannot terminated
abnormally. So, this is idea about run-time error is concerned again like compile time
error.

500
(Refer Slide Time: 08:05)

There are many sources many reasons that line run-time error will occur here. I have
mentioned only few some important things which usually occurs there, and there are
many more in fact. We will discussed in our while discussing about that robust java
program writing, then some errors will be discussed here. I have listed few errors, which
are usually common type of errors, but there may be many more errors are possible.

Now, so these are the basically run-time errors. Now, this is very difficult, because while
a program is writing that time program has to take care of all possible checks that this
one. But, sometimes it is very tedious, and obviously the programmers say ability that
programmer cannot do all kind of checking’s, so in that case what is the way out.

501
(Refer Slide Time: 08:57)

So, the as a way out java provides a mechanism call handling errors and exception in
Java program. So, it is basically the who will do it, definitely compiler not do, compiler
only check the syntactical error, which reports as a compile time error. But, this is the
error and exception which basically occurs; I should not say exception at this stage,
because I have not discussed any exception here. I can tell only error. This is checked by
java run-time interpreter environment is our java run-time system.

Now, java run-time system whenever find an error is basically in order in leave of
abnormally terminating the program, then it basically throw an exception, and the java
programmer should have the facility to catch the next session, so that (Refer Time:
09:55) bypass this error. And then for the rest of the part, it can be executed successfully,
if they are correct. So, this is a concept.

So, whenever there is an error or some abnormal things is occurred, java run-time
environment will catch it, and then throw it, and then java programmer will process it, so
that abnormal termination can be avoided. Now, here is an example suppose here is a
method suppose you have declared as integer X and Y, and in some program by mistake
user called this as a this one 1.5, 4 and right. So, compilation error will not be reported
here. But, at the time of execution whenever input is 1.5, it will throw an exception, so
that this method cannot be invoked, and then by pass.

502
As an another example here you can see, whenever we have to perform an arithmetic
operation like this one, and if suppose b and c these are the two variables values is equal,
then it basically gives rise to an error, it is called the divide by zero error. And if you
show in C programming, if there is a divide by zero error, then the programming (Refer
Time: 11:10) without giving any in output for the rest of the programs or whatever it is
there.

But, in case of java if we can catch this one or in this kind of error occur for this kind of
situation, then java run-time environment will throw an exception. And then with the
catching this exception, we can take care about this kind of errors in the program. So,
this is the concept that error and exceptions in java can be handled during the run-time
and then, avoid the errors.

(Refer Slide Time: 11:41)

Now, so for the errors and exceptions is concerned in java program, there is a big what is
called the development. And there in java, there is a package called the java.lang
package, which basically discussed many classes. And here is a class hierarchy as we see
there is a class called Throwable.

And this throw able can throw two type of classes called error and exceptions. And for
the exception there is IO exception and then run-time exception. So, this is a total class
hierarchy or the mechanism dealing with error and exception in java program. So, this is

503
a concept called n exception handling in java. So, there is a class as I told you java.lang
package, which basically define all the classes it is there.

(Refer Slide Time: 12:43)

Now, let us see about little bit details about the different possibilities about the class and
then exception handling mechanisms that is there it is very big story. So, we will cover
this kind of discussion not in one module, we may take two more modules to complete
the discussion with illustration. And then finally, we have a demonstration; so that we
can pin point exactly how the things the mechanism works for us.

Now, first let us have the idea about in general what is the exception handling
mechanism it is. As I already mentioned about that java provides run-time error
management on concept. In fact, java this is the error management, there is memory
management, and there is synchronization management, there are many other
management schemes are implemented there.

So, java run-time error management is a policy is a scheme which basically take care, if
there is any error occurs in the program. If there any occurs, if there is any error that that
may occur in a program, it can catch it, and then this can provide say solution to get the
premature exit of the program, therefore loss of other data or damaging of any system.

So, regarding these things in java or I can say the java exception mechanism handling
mechanism consist of five specific keywords. So, five keywords are called try, catch,

504
throw, throws, and finally. So, these are the keyword likes a class keyword, interface
keyword class, then extent keyword like this one these are the also keyword, we have to
embedded into the program.

(Refer Slide Time: 14:27)

Now, let us see how we can do all this things are there. In general, these are the
keywords that we have already mentioned here can be embedded in a program. So, for
example, so suppose you are declining method, these are beginning of the method, end of
the method.

And if we see this is the possible scope of error, so that obviously as a programmer
should know that there may be chance. For example, here and user should give an input
an integer, but sometimes user by mistake or whatever it is can give other type of integer.
So, we can have a check, so like this on. So, we can put all check.

Now, here is basically try we will take care. So, try can check that these are the possible
sources of error in a program. So, whatever the course those are basically under scanner,
they can be put into this block is called that try block. And then for many errors there are
many different type of exceptions occurs. So, for each errors and corresponding the
exception, we can plan the catch, so if it is a divide by zero error, if it is a null pointer
error, if it is out of bound error, whatever it is there for each error, we can mention the
catch that means, if an error occurs, this block will take care what to do. So, for each
error they are maybe one or more block, we can plan for it.

505
And these are the finally right, so it basically whatever it is error occurs or not, it will
execute this one so finally. So, this is the basic what is called a scheme. So, for the
handling exception is concerned in a java program. So, usually call try-catch mechanism
try catch.

Now, here also in addition to try-catch two more things is a throw, in other sense is
called the throws also there. So, throw can be put anywhere there that mean explicitly if
you have to throw an exception, as I told you implicitly means java run-time
management whenever fine and error, it will throw and exception. But, sometimes you
can the programmer can explicitly throw and exception, so these can be achieved by
means of throw keyword. So, this is the basically in brief the concept of exception
handling mechanism in java.

(Refer Slide Time: 16:57)

But, now it is very important to discuss about each the block one by one each concept
one by one, now we can structure this concept in here is a six different way that is the
exception handling can be done by using simple try-catch that means, only one try and
one catch. There may be also one try with multiple catch. So, so this is the simple try,
then try with multiple catch.

And then they are may be multiple exception, which can be caught by only one catch that
is also quite possible. And they are also possibility that whenever the exception occurs, it
should finally execute some code. So, there is a concept called finally. And throwing the

506
explicit exception so throws or throw in a block. And another is a nested try-catch; there
mean within the try-catch we can defined another try-catch, within the try-catch another.
So, nesting; so try-catch within try-catch. So, these are the different six different way of
handling exceptions in java will discuss all these cases one by one in our nah subsequent
slides.

(Refer Slide Time: 18:21)

Let us first discuss about simple try-catch block. Now, typically a simple try-catch block
looks likely which is shown here. So, this is the method that we are going to discuss
here. As you can note that usually LR occurs in a method. So, we are discussing in the
context of method only, so this is a method declaration.

Now, in this method the statement which is basically the critical statement. So, this
critical statement can be put under the try-catch that is ok. So, eventually in a very
default sense for every statement, we can write one try catch. Then obviously; but it is
very tedious and programs very bulky, looks very clumsy and it is not desirable. Only if
you see that this is a possible causes of error, then we can put that block that coat under
the try-catch.

Now, so this is the try block, we will contain this is the code (Refer Time: 19:22) to
cause and error. And then what that cause at the end of this try, we can put a catch. Now,
here the syntax you should see, try is the keyword. And beginning and ending that
basically called the try block. So, this basically whenever an exception occurs, this will

507
be basically check it, so that is if you do not put this one, if any exception occur, java
run-time manager will not be able to throw it I mean handle it, so that is why we should
put it explicitly there.

And then this is the catch like this try, it is a keyword catch. And it has also beginning
and ending that means, if an exception occurs, what are the next steps the program
should do? So, this basically includes the code, if an exception occurs. So, this is the idea
about the concept of simple try-catch block. Now, definitely it is if you have an example,
so the concept will be understood better.

(Refer Slide Time: 20:25)

Now, let us have a simple example to discuss it on. Now, here let us have a look about
the simple class it is there, we have defined one class the name of the class is called
divide zero. And here one function is declared any function, this has two arguments
integer x and integer y. And here is the code.

Now, and this is the main method it is declared there now ok. Now, you can see where is
the source of error, if you look at this program? Now, here you can see there is a source
of error why, because this method any function can be called for any integer values that
is ok, it will work for any integer values.

However, it will not work properly, if the second integer is zero. Because, if second
integer is zero, they are is basically divide by 0. And no processing unit can deal with the

508
divide by zero error in a program. So, whenever y equals to zero, then if we put all these
things under a try-catch. Then it will basically if that situation occurs that y zero, it will
throw an exception, and then following catch will catch it, and then do it whatever it is
there.

(Refer Slide Time: 21:47)

Now, see this program is therefore not a robust program. So, what is the weather this
program can be make robust. And here is the one possible input that it will work easily
always, but sometimes it may not work.

(Refer Slide Time: 21:53)

509
And here is basically is an attempt to make the program robust, how you have done it if
you see, this is the code which is basically very critical code, so we put this code in the
try-catch block. So, this is basically under try. And if you see, this is the catch is
basically what is basically tell that x y is bypassed, enter y as non-zero. So, you should
passed the input y as non-zero like. So, this basically may send a message or an output to
the use at if this kind of error occurs.

So, here if you see, this code will not execute always. Only if error occurs here, then only
it catch and then accordingly it will execute. So, this is the way that we can build the
program, so that it can in a robust way that means, it will take any input including zero
the second argument as an input also. So, this is the idea about making the program
robust is a very simple example here.

(Refer Slide Time: 22:59)

And here is another example as you can see here what you have done here is that we put
these things in a try-catch block, you know why you have done it. It definitely because
this code will again leads to divide by zero or occur for some input if b equals to c. So,
here after if in case suppose this error occurred for b equals to c is basically report that
this occur there, and then it basically bypassed and this. So, this is the idea about the try-
catch or I can say that simple try catch mechanism in java to handle the errors.

510
(Refer Slide Time: 23:45)

Now, here again let us have the look, this program looks very innocent apparently if you
see that there is no errors. Now, can you tell me what are the possible errors are there in
this code is basically command line input that means, here if you see args dot length ok.
Args dot length is basically if it basically say that number of inputs, when you have
passed as a common line ok.

Now, so here is a possibility that user can run this program without passing any input
that means, this value will be zero. Now, if this value is zero or others or it passes
suppose two value, but argument of this array is much more, then there may be what is
called the is called the outer bound error there.

511
(Refer Slide Time: 24:51)

So, this program if you run it for many inputs, you may check that this program may run
for some input, but not truly for all input is there. Here, is a some instances I have
mentioned here that, this program will work for this as an input, this as an input, but not
this, but not this, now you can understand why this program will fail to run for this kind
of input, but not this one.

Anyways, so as a exception handling mechanism it is our duty responsibility, so that all


the inputs if user gives, then this program still will work that means, for the correct input
it will definitely work correctly. But, for the wrong input passed to the program, it should
take care them and then report to the user accordingly. So, this is the concept of the try-
catch block in your java program. The simple try-catch block in the java program and
here is the ok.

512
(Refer Slide Time: 25:43)

So, earlier program was not robust, because we see we check that this program does not
work for all. And this is an atom, how we can make the program as a robust using try-
catch block here. So, it is basically try catch block to take the full (Refer Time: 26:04) of
the errors that may occur.

And whatever the input we have mentioned in the last execution, if we run this program
with all the input, we will see this program will run. It will not give any abnormal
termination of the program, and then we can say the program is robust. So, this is the
idea about handling exception in a java program. And as an example you can see this
program if you run, it will work for you correctly successfully.

513
(Refer Slide Time: 26:31)

So, this is a basic introduction about the exception handling. There are many more
features many more things to be learned in so for the exception handling is concerned.
So, basically the idea is that we have learn about try-catch, but there are few more
features basically there, which makes more effective way of writing the program. And
there are many more features, so for exception handling is concerned. So, all these things
will be discussed in our next module, and thank you for your attention.

Thank you very much.

514
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 24
Exception Handling - II

So, we are discussing about, Exceptional Handling in Java and in the last module, we
have discussed the try-catch mechanism. In addition to this try-catch mechanism; there
are many more features, so for the exception handling is concerned. So, today we will
discuss a few of them and then other features advanced features also there. So, those
things will be discussed in our next module. Now so, now we have discussed about try
and catch block and there is another, this is simply what is called the exception handling
mechanism. Now, apart from this simple there is also one more mechanism, it is called
try with multiple catch.

(Refer Slide Time: 01:10)

So, there are many features, try with multiple catch is the one. So, here the idea is
basically, the methods, where we are interested to maintain the exception handling. So,
suppose, this is the entire method and then, so try with multiple catch implies that there
is only one try block and there is many catch block. So, two or more catch blocks are
there then it is called the try with multiple catch.

515
Here, if the concept is that in the try block it will catch whatever the exception will
occur, so only one try. So, try block will responsible for two catch all the exceptions and
for each exception, we have to maintain the catch block. So, that the corresponding
exception, for a corresponding catch block, we will take care.

So, this is the concept. So, a try-catch block is basically to indicates that if there are
multiple errors or exceptions occurs in a program, they can be tried it with one try block
and they can be caught with multiple catch block.

(Refer Slide Time: 02:23)

Now, here is an example, very simple example to explain how the try with multiple catch
we will work. Now, let us look at this program. Now, we can see there are multiple
points, where the errors may occur, as you can see in this program. So, it is basically
considering the common line arguments. So, if the common line arguments are there. So,
it basically has the args length; that means it, how many inputs that user has passed
through the common line that will be stored here and after that we can see this is one
point, where there is a scope of error or exception.

Why? This is because if a user does not provide any input, in that case, i equals to 0 and
if i 0, then this is not a valid one. What is call the declaration, is called the null pointer
exception. Now, another here is also if you see, there is also one scope of error, if a user
does not pass any input then args 0 is also a null pointer and there is another also, you
can see here, at this point also one error.

516
So, if i equal to 0 so, it is basically the arithmetic exception namely, the divide by 0 error
and here also if you see there is a possibility of error, if the value of i is more than 2
because here i then an array is initialized with two elements. So, an array index is
varying from 0 and 1. So, size of the array is 2 and then here if I suppose 3 or more than
1; that means, 2 then it basically, gives an error.

It is called the array index out of bound error. So, as you see this program can run for
some input, but not necessarily it will run for all inputs. So, if the program does not take
care about all those exceptional inputs, then it is the exception and this way this program
is in fact not so robust.

(Refer Slide Time: 04:53)

So, there are few input as you can see, if you try this program with all these inputs you
can see these are the; so, this is the one exception occurs in this input, here also
exception occurs and here also the exception may occurs. So, there is a different
exception that may occur for the different input like this.

517
(Refer Slide Time: 05:20)

Now, so, as a way out of these things, so they are basically, as I have mentioned again,
let us specific as there is a one vulnerabilities, here is also errors may occur and there is
also error occurs. So, there are three points where the error occurs, so multiple errors,
multiple exceptions. So, here is the idea about how we can handle with a try with
multiple catch. So, idea is that we can include all the statement where an exception may
occur under the try block and for each exception, we can plan the catch block. So, here is
an idea about these things, which is the program has been rewritten with a try with
multiple catch. Now, let us look at this program little bit carefully, we will be able to see.

This is the program that where we have included try with multiple catch as you can see
here is that, this is a basic methods portion, where the exception may occur at this point.
This is the one point, this is the here and this is the these are the three points at the
exception that may occur and to catch this exception, we have mentioned one catch. This
catch is basically to handle the null pointer exception error mainly here and this catch is
basically to handle arithmetic exception error divide by 0 error here and this catch is
basically to handle the array index out of bound error here.

So, as you see for the different exceptions, we can plan the different catch block. Now,
this is; obviously, not possible with a simple try-catch block, because it will catch only
one exception, but there is a master exception we can consider. This is possible, but if
you want to pinpoint or more specific about what particular errors or exception occurs

518
then definitely we should think for try with multiple catch. Now, so this is the one
features.

We have learned about simple try, try and catch, then we have discussed about try with
multiple catch and also it is possible to catch by means of only single catch block, but the
multiple errors are there. That is what I just wanted to discuss about these things in a
different way, that we have discussed in the last. See, try with multiple catch by more
errors, in the last example that we have seen, but we have planned more catch block, but
here multiple errors, but single catch box. So, this is the one idea about so, here is one
concept, the concept is like this.

(Refer Slide Time: 08:06)

So, this is the method as where the exception may occur and then these are tried, here in
this part many errors may occur as in the last example that we have discussed, but there
is one catch that can handle, whatever the exception it is there.

519
(Refer Slide Time: 08:29)

Now, here is an example that we can see, this is a very nice example to explain this
concept very carefully. Now, here if you see so, this is the method, main method actually
here. Now, under this main method as you see there are many points of exceptions that
may leads. So, here is the one point of exception, because 0 equals to here divide by 0
error. Now, here also you can see as b is initialized is a null pointer and we want to have
access b 0, the zeroth element.

This is also an error and here also you see, here the array c is declared, which size 2 only,
but here we want to access the tenth element, which is also not possible. And, here also if
you see these a string and we want to find the character at ninth position, where is the
string; has maximum up to third location, index is 3. So, here the string index out of
bound, here the array index out of bound, here the null pointer assignment and here the
arithmetic exception. So, there are so many errors that may lead to whenever we want to
run this program.

520
(Refer Slide Time: 09:48)

So, this program, if we run then it will give always this error, because of static error that
is there. Now, let us see what we can do so that this program will be more robust, more
reliable.

(Refer Slide Time: 09:53)

So, this can be implemented with only one catch and then on try. So, an idea it is like
this, here you can see. So, this is basically, as you have mentioned the try block. So, that
whatever the error will occur, it will try to see whether if any exception error occurs or
not and then here we can see a single catch. Now, in this catch, if you see, we have

521
thrown an exception of the class exception. Now, in other examples; in the last example,
we have mentioned the exception of a particular class, say; a null pointer exception or
arithmetic exception or divide by 0 exception or like this ok.

So, here is basically, we will catch-all. This is basically the super exception class. So, it
will catch any sort of exception whatever it is there, but if we write the catch, which says
array index out of bound exception e, then only that kind of exception that this catch box
will handle. But here the single catch will catch any kind of exception that may occur.
So, it is a general, general one implementation and here also you can see for the different
exception, the different messages meant already in the exception class, it is there.

So, this basically will print e.get message; that means, it will tell that ok. It is array index
out of bound exception or what type of exception it is there. So, this is the idea about
multiple errors which single catch. So, sometimes whenever we are not sure about, if any
exception we will occur in our program, then usually programmer will prefer this kind of
things. So, only say one try and one catch that catch will consider or handle only the
object exception e.

So, this is the very simple one approach, of course, sometimes it is, but in some sense
cases whenever we need say details error or exception mechanism, this is not so much
preferable, anyway. So, this is the things that we have learn about simple try-catch, try
with multiple catch, multiple errors with a single catch. Now, in addition to this, there is
another concept, it is called the finally, associated with this try-catch block.

522
(Refer Slide Time: 12:18)

So, the idea about this finally, is that. So, try-catch we have already learned about it, then
it will contains another block is called the finally. So, it is basically, the idea is that if
there is any exception occurs or not occurs. So, in that case the final you will always
execute for you. So, this means that it always execute this code.

So, this code basically helps the programmer that if an error occurs then, what is the
remedy for that error? So, the programmer can have the flexibility to mention or inform
to the user so that if this is the error occur so what the user should do like this and if we
does not occur you can say that, the program is running successfully, this kind of things.
So, this is an idea about finally.

523
(Refer Slide Time: 13:14)

Now, let us have a small example to explain the concept of finally, here. Now in this
program, if you see we have declared an array, the name of array is greetings, which will
be initialized with three strings; "Hello Twinkle!", "Hello, Java!", "Hello World!" and so,
it is basically greetings that have the index from 0 to 2 0 1 and 2. Now, here if we run
this y loop then ok, for i equal to 0 1 2 it will work, but for 3 and after that is, it will
basically give an error or exception, this is, because so i greater then, if i equal to 3 and it
will try to find this one right. For i equal to 3 then greetings, because it is 0 1 2 maximum
so 3, in this case, it will gives an error.

So, this loop if we roll, it will roll for first three input 0 1 and 2, but for 3 it will give an
exception. Now, here the finally, catch is basically for each iteration it will, there is no
exception so catch will not do anything, but finally, we will say that whenever i get less
than, greater than 3 it will basically give that error. So, this is the idea about that the final
you will, finally a block can be added in addition to try-catch block, to give more
flexibility to the user. Now, Java also allows programmers to throw exception explicitly.

Now, all this example that we have discussed that, it is basically implicit throw. That
means, whenever the exception, we will occur the Java runtime management manager
basically, we will check it and then try for an exception, if it occurs and then catch it, but
sometimes we can throw the exception of our own. So, this can be done by a throw
clause.

524
(Refer Slide Time: 15:25)

So, there is a throw clause, it is there. Now for example, here as we see, so this is a
simple try-catch block in a block and here is a throw exception object. So, a different
type of exception and corresponding exception can be thrown by this one. So, this is the
throw clause ok. By writing this throw so far, in our previous example, we have not used
this throw. Now, we are going to use this throw that explicitly, it will throw and
exception objects. Now, this is basically, if you find some error during some input or in
your program or system, then you can throw especially that is why the Java developer
has maintain this kind of concept here.

(Refer Slide Time: 16:11)

525
Now, let us have an example here. So, a throw can, can also throw many exception that
is also possible and so, there is again, in other than this throw there is also in throws; that
means, if it throws multiple exception. So, this is the idea about, let us have an example
so that we can discuss, we can learn this example and then have the full idea about it.

(Refer Slide Time: 16:39)

Now, this is the one simple program that we can just check it. Now, here we have created
one exception, the name of the exception is my exception and this is basically than
inherited, a superclass of exception actually. So, it is a derived class, superclass
exception. As you know the exception class is already defined in this java.lang package.

So, this is the concept that ok, we have to create an exception class. So, it is basically,
user-created exception class and so what message that this exception class can give to the
user is basically, this is the message and this is the constructor that is defined in the
exception. So, using this constructor is basically overloading and this basically is a
definition of the constructor of this, my exception class, actually.

And so, this part is basically declared an exception class of users own. So, it is the user's
own exception. Now, I will discuss about there are many built-in exception classes are
there. Now, this is the user-defined exception class, anyway. Now, once you defined the
user exception class then you can create an object of that class and here is an example.
Now, if we see this example. So, this is a very simple one.

526
So, this is the main method as we see and hear the possibility of causes of error it is
there; obviously, y 0, but in this case, you see y is always 1000 static value. So, no, but
sometimes the user can tell that ok, if this ratio is within not a threshold for example, if z
is less than 0.01 and then only you can raise the exception. So, here actually if z, which
will come from this arithmetic operation, is less than this one, then it will throw, this is
the exception with this message.

So, this is the i use of the explicit, throwing an exception in a method and then this is the
catch, as you see, this will catch the exception of this type and then the message, the
block for the catch. And this is the finally, as you have mentioned, that it will always
execute whenever there is an exception occurs or if not occur if there is an exception
occur, you can maintain the code, what it should do and whatever it is there. So, this is
the idea about, that idea about throw clause.

(Refer Slide Time: 19:19)

Now, here is another example of a throw clause that is the same thing. Here we have
declared one class, the name of the class is throw demo and where there is one method
call the demo proc and in this method, we declare our own try block. Here is try, throw a
new interrupted exception. This is basically user-defined exception and interrupt occur
and whatever the code, there is the demo proc and then this exception if it occurs, it will
catch using this catch block and this catch also can throw another expression, is basically

527
throw and expression to the color program actually, because it is a procedure whenever it
is called, it will throw to the caller actually.

So, now here this is the caller program here which will call this demo to proc and it calls
it. Now, if any exceptions occur, because of some code here, it will throw and this
exception e we will catch. This exception, which is called by this one here also and this
will print like this. So, they are, there are many usages of this throw exception. More
basic concept here is that, it can throw any exception which user wants to, to throw it in
this program so that the program is more robust. So, this is the throw concept there in a
block.

(Refer Slide Time: 20:51)

And there is again throws also possible in exception handling for, to handle the
exception, to handle the exception in a Java program. Now, for this purpose, the Java
program proposes, an idea about it; so, suppose we want to throws an exception,
whatever it occurs in a method. Let this is the name of the method, where we want to
throws multiple exceptions, then you should use throws clause and then whatever the
exception that you have, you anticipate, you can be made it their list.

So, if there is a say array out of bound exception. So, array out of bond exception
comma, if there is a null pointer assignment then comma and so. So, this basic list of all
exception that this throws can throw and so that the corresponding, the catch block will

528
be there, they can catch it. So, the idea here, it is that this throws command; we will
throw multiple exceptions that may occur in a method.

(Refer Slide Time: 22:06)

Now, so, idea it is now, let us have the one simple example so that we can understand
about this one. Yes, now this program, we have once discussed in our demonstration as
well as while we are discussing about the input-output. As we see, in this program there
are many points, where the exception may occur. Now, let us examine one by one.

So, here is basically if you see, in this part there is no point of exception, but here if you
see, here data inputs stream, in this one. Now, here if suppose, it is not possible to, this
program is not able to create an object of a data stream in, then an exception we will
leads because this in is referred in subsequent here in many a situation. So, if this object
is not created then in the subsequent points, it will raises many exceptions are there at,
this is because Java is basically an interpreted manner.

So, if this, this fails then; obviously, it will not stop here. It will try to give, execute it
and then in every point it will point out the exception, anyway. So, there is a possibility
that here an exception may occur in the sense that that in the data input stream object is
not successfully created for some reason and also system.in, it is basically standard input
sum. Suppose, your keyboard is not working properly while you are running this
program or once the input device is not working, which basically may have to system
end than in that case also this object will not be created.

529
Now, so, these are the basic system.out.plus there is no point of which basically clean the
buffer the concept it is there. Now, here you see there is again in read line, if suppose this
buffer is not able to read successfully, for some reason then here also there will be an
exception and here also another exception, if the buffer is not able to read at this point
and here is also another exception if the buffer is not able to read at this point ok.

So, we see there are three different points, where the exception occurs and in this
particular example only one particular type of exception occurs. Now, you can define
that exception of your own, if you defined then you can mention that in this throw block.
So, that is exception, but here without taking any, what is called risk, we have discussed
the throw exception, any type of exception, if it occurs, in this particular code, then this
throws will throw an expression expressively and then this catch, will catch this
exception e.

So, the idea about that any exception if it occurs here, this throws as it is mentioned here,
will throw the exception in the try block and then the corresponding exception, will this
one. Now, here if I do not write this one also and only this part, also it will work. This is
a particular case is that, because there is a; obviously, the responsibility of Java runtime
manager. Java manager will automatically take care this part, whenever an exception
occurs, but sometimes the exception, which is basically, as per the requirement of the
program.

Say some (Refer Time: 25:46) in this case it is not working of course, but in some
situations. Say suppose, I am telling you one example say in .read line it is working
correctly, but I want to see that if suppose I have to enter say two-digit number if user
printer one digit. So, in that case, after reading this one I can throw an exception occurs,
according to my own requirement like this one. So, in that case, this throws or here also
after seeing these things, we can write throw.

So, out of this, there are many ways actually. So, we can write this one and then do all
these things. We can have this one, not required, but this one or we do not have this one
here, but throw here, throw here, throw here. So, expressively there are many ways the
exceptions can be handle actually.

So, whatever be the way basic idea is, that all these things should be catch, either using
multiple catch or simple catch, whatever it is there. So, this is the idea the concept for the

530
throw-in try-catch mechanism. So, we have discussed about many other features
regarding the exception handling in Java and there are many more in this line. they are
basically, we have discussed only few exception handling concepts. Apart from this,
there are many other different exception classes they defined in java.lang package.

So, those things definitely a programmer should know about it then they can use it for a
program in a better wider domain actually if you want to develop it. And there is also
another possibility Java makes more, what is called the flexible in the sense that it allows
a user to define their own exception. Now, in our next module, we will discuss about,
how a user can define their own exception and then those exceptions can be handled and
whatever the built-in exception classes are there in Java program.

Thank you very much.

531
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 25
Exception Handling – III

So, let us learn few more things regarding exception handling in java programming. We
have discussed about the exception handling features mainly the try-catch finally, throw
and throws.

(Refer Slide Time: 00:32)

Now, in this module, we will discuss about the built in the different packages. And
before that we should discuss few more things they are the so that try-catch. So, for try-
catch concept as we have learned about, there is a scope that the nested try-catch can be
implemented. Now, here is an example to include this concept called the nested try-
catch. It is a nested means the try-catch block within another try this is the concepts. So,
and there is no limit of nesting, try-catch block within try, within that try-catch block
another try-catch like this, this. So, and then obviously that what is the reason, what is
the purpose; why you should do that there obviously, it is the questions.

Now, the basic concepts, so for the nested try-catch can be understood here from this. So,
suppose this is a method which is under the investigation of handling exception. And
here if you see there is one what is called the inner try-catch, sorry outer try-catch block,

532
within this try-catch we can define another try-catch is called the inner, within this also
another try-catch block can be define like this. So, if we define a try-catch block within
another try-catch block, then search a try (Refer Time: 01:49) is called nested try-catch
block.

(Refer Slide Time: 01:57)

Now, let us see one example where it can be applicable. This is again simple example
that we can thing about ok. These are very simple program, it has only main method. So,
you want to handle the exception in this method only. So, here is basically a args dot
length, for the args dot length means whatever the input that user past according the
number of input, this value a will be decide. So, if user do not pass any input, a will be 0;
and accordingly the value of a will be there. Now, here if user do not pass any input, then
a is 0; and as we see there is an exception call divide by 0 or arithmetic exception.

Now, again let us see here, suppose user enter only one input, so in that case a equals to
1. Now, in that case also it will give an error. So, it is also the divide by 0 error. Now,
another situation so it is not the 0 input it is not the single input. So, suppose user enter
two input, the in that case if you see if a equals to 2, then there is again possibility of
error, because here we declare an array of integer c with only one element c need, that
means, size of the array at represent is one, but we want to store a value at the second,
that means, this is array index out of bound error is there.

533
Now, so here basically two type of errors. In the first two cases as we see here and here,
this arithmetic exception error; and in the second case is there is called the array index
out of bound exception occurred, so two type of error. Now, if two type of errors, then
we can think for only two catch block. Now, here the idea is that we can write one try
block here. So, this catch block, this try-catch block will handle these are the arithmetic
exception error. Then there is another error that may occur within this, so inside this
another try-catch block we can put, so that it can handle this exception. So, this is a
concept, this is a concept of nesting. So, this is a simple example.

(Refer Slide Time: 04:11)

So, here is a solution for the nesting case is there. As we see this program will not run for
all the input because it will give an error whatever it is there. It will run for this one no
error, but for this one it will error.

534
(Refer Slide Time: 04:26)

Now, so the remedy here we have checked it here. So, let us see this program as we have
see this is the try and corresponding to this. So, this is there is a two try-catch block. As
we see in this program this is the one try and this is the corresponding catch, so try-catch
and this is a inner try-catch. And outside this, this is another try and this is another catch.
So, so it is called the nested try-catch. Now, if we see this inner try-catch, we will handle
the exception, this is the array index out of bond. Whereas, this try will handle the case
this one, and then finally, this is work. So, this is idea about the nested try-catch block.

So, java is basically is a very versatile programming language in the sense that whatever
the possible exception and errors may occur in a program, it can handle. So, regarding
this things, the java developer or jdk package includes a very nice one package java dot
lang package. This package has been planned to, so that it can take care many errors and
exception.

535
(Refer Slide Time: 05:46)

So, this is the class hierarchy that this java lang package has regarding that exception
handling. So, here basically there is a class called object is defined in this java dot lang.
Throwable class, it is called the class throwable. Under this Throwable, these are the
basically hierarchy of the different sub classes of the class Throwable. So, object is the
class super class under the super class Throwable is basically another inter. And this
throwable has many at so this basically Throwable class as the two sub classes Error and
Exception. Now, the simple exception is there, and then runtime exception is there now.
So, so these are the different what is called the class hierarchy that is there in the java dot
lang dot Throwable classes are there. Now, for each classes there are different what is
called the exceptions that may occurs under this classes, so that they can handle it.

536
(Refer Slide Time: 07:03)

So, here is basically let us first discuss about the runtime exceptions sub classes which
basically causes many exception. So, I exceptions are discussed here. As we see here that
five around ok, so around 12, 18th, 18th, 6, 6, 12 ok. So, 12 different type of exception
that may occur during runtime exception sub classes which it can cause.

For example, we have already discussed about array arithmetic exception, array index
out of bound exception, and then there is a many more array this illegal argument
exception, security exception, incompatible class change error index out of bound
exception negative array size exception, null pointer exception, number format
exception, string index out of bound exception, few exception already we have discussed
in our discussion and few more exception that we will learn about while we have a
demonstration on this concept, so that it will clear our idea.

Now, so these are the different type of exceptions that the java developer automatically
these are built in exception types which is already there in the runtime exception
category of the Throwable class. Now, so these are the frequently occur exception related
to the different situations it is there.

537
(Refer Slide Time: 08:27)

Now, other also there is another class exception sub class also there. It is basically in this
exception sub class, there are few more exception that it may handle is a ClassNotFound
Exception, and then DataFormatException, IllegalAccessException, Instantiation
Exception, InterruptedException, NoSuchMethodException and RuntimeException.

So, these are the different type of exception it is usually if you are an advance java
programmer, then he may phase this kind of exception when you are developing
applications. So, in that case all the coming to the picture, but it is very difficult to
illustrate all this exception one by one, because it is too more I mean it is also not
possible in this shortest time anyway. So, these are the different exception. So, for
RuntimeException and then exception sub classes is concern and there is one is called
the Error sub class.

538
(Refer Slide Time: 09:24)

So, in the error sub class also, you can see these are the different exception that it may
occur ok. So, this is the error classes, and this is the exception sub classes.

(Refer Slide Time: 09:44)

So, these are the few more errors that is there in the exception classes as we have
mentioned here that ClassCirculatoryError,ClassFormatError, Error, simple error, and
then LinkageError, InstantiationError, NoClassDefineFound Error, NoSuchMethod
Error, NoSuchFieldError, OutofMemoryError, StackoverFlowError,
Throwable ,UnknownError, UninsatisfiedLinkError, then VerifyError and

539
VirtualMachineError. So, there are many errors that may occur in a program which is
discussed here.

(Refer Slide Time: 10:26)

Now, all these sub classes that we have discussed is associated with many methods. Here
we have listed few methods, and with their description. As you see here they get
Message probably you have run about the getMessage is basically it will tell about a
particular error. So, it is it basically returns a message about a particular exception that
usually it over an encounter. So, it is basically this message is initialized through a
constructor which is defined in Throwable class; this is the main class, super class.

Now, there is again get cause, it basically a return an object of class Throwable to the
caller program if a method in which this exception occur, it will basically throw a throw
an exception to the caller, so that is why get cause it basically tell about the reason for
the exception that it have. So, it has very useful indication to both the programmer as
well as for the user also. Then to string here it basically return the name of the class
where this error occurs. It possibly concatenated if this class is under another class or is a
nested class or derived class or whatever it is there, it will basically concatenated, all the
classes then give a particular location. So, this is particularly very much useful for
debugging, debugging the program and testing the program.

Then printStackTrace it is just like a idea about tracing there that means, if an error
occurs in a particular method. If this method is declared in which class if this class is a

540
derived class or not or implements and interfaces like this. So, it will basically give a full
trace off the location where this particular exception occurs. Or if there is a chain of
exception one exception can propel other exception, then other exception also using this
printStackTrace, we will be able to trace the reason or the location of the exception.

Then stack trace element, it is basically and advanced version of this one, it basically it
multiple errors are occurs, then it basically put on into the stack whenever we writing
same recursive program suppose and there maybe multiple exception occurs in a
different points. And then it will basically (Refer Time: 13:11) all the exception into a
stack, and that is basically the idea about. And then finally, it will use this one.

So, this get stack trace is basically catch all the exception that it may happen in a method,
and it will push on stacking actually it is stacking into a stack. And then fill in
StackTrace also it basically this method returns a object returns and exception object of
this throwable class. And whenever there is an exception occurs, and then obviously, in
the so it basically think that whether stack is able to maintain handle this kind of
exception or not. So, this is the (Refer Time: 13:56) is statement like. So, these are the
different methods which are there in the exception class.

Now there is a possibility, so that depending on the needs of user, user can define their
own exception. So, this concept is basically to make the program, more versatile, more
flexible more robust and reliable. So, this is possible by means of user defined exception,
in other words user can define their own exception.

541
(Refer Slide Time: 14:35)

So, here is an idea, let us see how user can define their own exception. Now, first of all
you have to create a class that class should be a derived class of the super class
throwable. So, it is basically all exception must be a child of Throwable class. We have
already discussed about this throwable class is defined in java.lang package. Now, so this
is the syntax by which we can create an exception which basically type of the runtime
exception that can handle it.

So, here as we see class, myException it is basically user defined class. And extend
Exception, Exception is basically is a sub class of Throwable, we have already learned
about. And sometime the RuntimeException also we can declare, so there are different
type ok. So, so this is the way by which user can define their class, and here the code of
the exception class. Now, let us have an example, so that we can understand how user
can define his own exception.

542
(Refer Slide Time: 15:46)

Now, this is the very simple program. And here we can see this is the user defined one
class. This is the user defined one class. We define the name of the class that we have
define is InsufficientFundsException which basically is a derived class of exception. And
these are the a few quotes of this right. So, here private double amount is a one field, and
then this is basically the constructor of this class, this will take the amount. And this dot
amount it basically initialize. And then there is an another method public double
getAmount( ) and returnAmount().

So, so the class is very simple. Without any exception this class can be considered only
simple class a and then all this course can also be there. But we have to just make it
attend exception class, this one of our own. Now, let us see how we can use it this is a
one application that we are going to discuss in the context of banking transaction and
then we can understand about it. Let us have the discussion so that we can discuss about
it.

543
(Refer Slide Time: 17:05)

Now, so this exception that we have discussed here we want to use it in our application
class. Now, so application class is like this. So, there is a user defined class Checking
Amount, checkingAccount. So, it will take the balance, then number, and then it is a
constructor here. And this is another method deposit amount and the balance will be
increased. So, this is a concept it is there. So, it account will be checked, and then the
amount that will be deposited will be deposited into the account. And there is another
method which is in this class is also there withdraw method, deposit method, withdraw
method. And here in this case we have mentioned one exception throws, throws
InsufficientFundsException .So, if we can find that if amount less than equals to balance,
then balance will be negative or balance will be adjusted, and then if it is not, then it will
throw an exception. So, this exception is basically it is there. So, suppose user one user
wants to withdraw some amount which is not permissible as per the balance is concern,
in that case it will throw this exception insufficient funds exception. So, this is the idea
about.

Then once this class is declared, we can use we can define the main class here. Here you
can see this is an extension of this one just ok, withdraw has this one else and this class
has few more course of course. So, here is few course it is there. And then these are the
simple getBalance and then getNumber, these are the complete description of the class
has it is there, checking account class. Now, on this class is defined, then we will be able
to define our main class.

544
(Refer Slide Time: 19:00)

So, the main class it looks like this the name of the main class is BankDemo, and it has
the main method. And we can see we have created an object of checkingAccount and
then say let there may be 100 plus the account holder is there. So, these are size of the
total customer base actually. And then system.out.println depositing dollar 500, this is a
one method it is there. And then see deposit 500, so it is basically that ok. This for this
object we want to write call the method deposit.

So, now, after this thing try catch is there, and then c.withdraw. So, this is the 100
withdraw one instance, 600 withdraw another instance. Now, in case, suppose there is
any exception occur, then this is a catch block which will take care. So, this is our the
fund exception, user defined exception as you can note it here

Now, so there are few instances that it may occur. If you run this program the entire
class declaration that we have discussed and then run it. And then there are few instances
of the input that we can see depositing dollar 500, withdrawing dollar 100, these are the
things that we will sorry, but you are short of 200, insufficient funds exception at this
one, it basically shows the different situation when this program is executed.

So, this way you the user can define their own exception, and then can develop the
program according to their requirement ok. So, this is about the different cases of the
exception that it may occur here. And we are almost at the final round of the exception

545
handling discussion. Before going to this things I just want to mention few a simple
example, let us see whether you can follow it or not.

(Refer Slide Time: 21:05)

Here is the one program and just took a check this program and tell where is the possible
scope of exception that it may result. As we see here so this is a simple class only one
class which has the main method, this is the main method. Now, let us can one by one
this statement. Now, I am telling one very simple rule of thumb is that if we suspect any
exception that it may results, then that statement that code can be put under try-catch. So,
in that catch, the very simple way that you can handle the exception is that so many try-
catch corresponding this one, but this is obviously, makes the program to so many try-
catch, but ultimately it is a robust of course.

But there are many way that is the rather efficient way that with minimum number of try-
catch how we can handle everything. So, usually the advanced programmer think for this
one that with minimum number of try-catch, whether this is try-catch nested, throws-
throws you, with your own exception, whatever it is there, anyway. So, for a beginners,
the best practice should be that if you see that there is an error so put a try-catch and
accordingly handle it, you can use the finally, if you want if you do not want, then final
is a default one. So, it is not necessary to use.

Now, so here again here if you see this is the one statement, do you think that there is a
possibility of an exception occurred here. Yes, because if the Scanner class is not

546
instantiated, and then create a scanner object, then it may leads to an exception. So, there
is a possibility that an exception occurs. So, this is a one possibility that exception occur.

Now, next is here this statement and this statement as well as. So, nextInt is basically it
check that in the line of input, whether the next input is there. If some regions are there,
whenever this input is not there or not able to read integer rather some string and
everything, then this statement also throws exception. And these are the very simple. So,
there is no exception.

Now, so these are the point here, here, and here. Now, how many try-catch block that
you can think for fine. So, one solution is that, all these things put can be put only try,
and then here is the catch or as it is a try this is the one kind of exception and this is the
only kind of exception. So, nested try also can be plan, so that with minimum number of
try-catch code, we can handle the exception here in this case. So, it is the practice.

So, you can think about how you can put it. It is basically if you put many try-catch
block, absolutely no error, no problem, because if the exception occurred then only it
will be there. But the problem is that if you do not mention try-catch block properly, so
that even in the case of exception occurred you are not able to catch it, then it is a
problem, so that is a things are there.

And one more thing, so if you do not put try-catch block explicitly, but there is a
possibility of exception occurs. So, during the compilation, the compiler can note it and
then compiler can report it. Until you put try-catch in your block, compiler is not compile
it successfully. So, this is the one great advantage for the programmer that ok, if you are
supposed miss to add try-catch construct in your program, the compiler will help you to
do that. So, there are many ways it is possible. So, this is the one example that we have
discussed about in a scanner, and this is simple one example.

547
(Refer Slide Time: 25:07)

Now, let us consider another example. It basically is similar to the Scanner. This Scanner
means it is basically read the input from the keyboard, and then store into an array. Here
is an example as we see. And array list is a one structure data structure defined in
java.util package. Now, let us see here. So, so this is a simple again code, the main
method. And obviously, there is no point of exception, but here is a one point of
exception that if the array list is not this l not built in properly or not created
successfully. If it is not created successfully, then here is an error occurs, here is an error
occurs, and then here is an error occurs. And also here another error occurs that l.size if
you have created an array list, but this size of the array list is very small rather is a 0,
then also it can created, it can creates errors.

Now, we have pointed out few things are there, again another also there is also
possibility that one error is occur here. Now, again if I ask you that ok, how you can
insert the try-catch block in this program, so that this program will be robust or if you
can think about of your own throw, and then accordingly user-defined exception you can.
So, if you want to have your own user-defined one, you should defined a exception
classes which is a child class derived class of throwable or exception, and then according
to that you can write the try, here the try, here the catch or here again try another catch,
so that all the exception it can be handled in this program. So, the many ways actually
that you can do. So, this is the one idea about.

548
(Refer Slide Time: 27:09)

Now, let us have another example ah. So, here is another example. And this example we
have discussed while we are considering input and output to the system. This example as
we see here we have fine, this is again simple method main method it is there. In this
main method, these are the simple declaration of the two objects. So, this is also another
declaration. So, these are declaration. There is no point of any exception occurs here just
a matter of discussion a declaration only.

Now, here if we see here again this one this basically is the one very critical code here,
because we have to create an object of data input stream and sometimes this may have
problem. Sometimes I told you, not always, and exception is like that it can happen in
some special situation like this. Now, in that case, so this statement should be covered
under try-catch block. Now, if there is a problem and subsequently, they are also the
possibility that there is a problem here either it is a readLine problem from the object in.
There is also a readLine from the object in; there is also there and like this ok. So, one,
two, three, four, the four points where we can see the exception occurs here..

And also here, so this is basically this is the one value of changing conversation string to
float value, string to integer to parse in there is also possible scope of errors there. Now,
as we see as they these are the possible, because you have entered some value which is
not possible to convert an integer say 2 0 20.55, then in that case it basically not able to

549
parse into integer, so that error will be there. So, as you see, so these are the four cases
and this also other three cases that error may occur.

Now, once you identify this is a possible location that the exception can be thrown or
exception can occur, then accordingly we have to take care about that try-catch. There
are again many ways are there. First of all we can use the throw statement. So, what we
can do is that, we can write here the throws, throws and exception. Then what about the
causes are there, we can put try and then here catch, so try and then catch, then exception
occur (Refer Time: 29:57). So, this is the one way. So, throws means it will basically
throw all the exception that it may happens and then using this try-catch they can be
exception.

Now, other than using the throw statement itself simply try and then the catch also can be
put here exception. If you can know that this is the exception due to this, this is the
exception due to this, then accordingly several catch block several catch block you can
put it for each exception. So, this is a case of single try with multiple catch. And also one
try with all exception in multiple exceptions by one catch also in that case similar to the
throws also we can use it. So, in the many ways, many ways that you can do only if you
know the mechanism, then all those ways that can be incorporated in your program, and
thus you can make your program very robust.

(Refer Slide Time: 30:56)

550
So, this is all about the exception handling concept in java programming. Now, after
knowing the exception mechanism; our next tasks to learn about how the distributed
programming can be done because java is very famous for distributed computing. So, in
our next model, we will learn about the distributed programming more specifically the
multithreading concept. And then, we will discussed the how java right language can
helps a programmer to develop their internet programs. So, these are the concepts these
are, I mean questions will be answer in our next module (Refer Time: 31:45).

Thank you very much.

551
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 26
Demonstration – X

So, let us have a demonstration regarding the Exception Handling Mechanism in Java.

(Refer Slide Time: 00:25)

And today’s demonstration includes mainly the compile-time errors, and then what are
the run time errors are there, and then how exception handling mechanism can be
achieved by means of simple try-catch block, try with multiple catch, then multiple error
errors with single catch. And there is another block that can be added with the try-catch
is called the finally, so try-catch-finally block in along with the try-catch block, and then
throw and then throw used in exception handling and then nested try-catch block also.

552
(Refer Slide Time: 01:08)

So, let us have the first look at the compile-time error. As you know if you run the
program which is not as per the syntax of java programming language. So, the job java
compiler reports all these things as an error as we see here in this program here. We can
see a lot of errors are there and here we can see in the first statement itself start with error
because java is a case sensitive. So, capital C in the class declaration key work is not
allowed.

(Refer Slide Time: 01:38)

553
So, if we run this program as it is the first execution, so compiler will halt it here
showing this error there. So, we will correct one error at a time as we see the compiler
will report the class error here.

Now, let us quickly remove this error now we can see there is more error and public also
capital P it is not allowed, so let us small capital is there and then again the error is there,
ok. Let us quick to fix it, right. Public and then the system as we see capital S should be
there and then capital S, and then you see all the statement should be terminative
semicolon. So, as there is no semicolon, so we should make the semicolon here again put
the semicolon as we see. So, java compile compiler will compile the program and
whenever it finds an error it will report it and then until this report is fixed, so this
program will not lead to the successful execution of the program.

So, there are a few more errors as we see. Any method should not be declared and
abstract inside a class method as we can see here because it is not an abstract class. So,
there is an error, and then there are few more error as we see those basically compile-
time errors actually.

Now, so after knowing this compile-time error let us have the run time error concept it is
there. Our next illustration to explain the idea is about the run time error. So, let us go to
demonstration 10.2. Here we can declare on class, the name of the class is error and ok,
right.

(Refer Slide Time: 03:22)

554
As we see this is the one class declaration, let us follow let us have the quick look at the
class declaration here. Now here we can see this program is perfectly there is no
compilation error, as we have compiled it successfully; however, this program will run
but will not run for all. Now, if we run with this one we will see it run for all not for all,
but for some.

For example, for if we run this program with input 1 2 it will run, input 1 2 give, it runs
correctly. Now, 10 20 30, as we see these program will gives an, it is 10 30; 10 20 30.
So, this program also takes this input. Now, what will happen if we give only a single
output? As we see it also ok. So, that is a single input, in this case, it gives an error. So,
this error is basically array index out of bound exception array error it is there.

Now, again four 4.5 and 5 the different error it will basically it is called the exception.
Also, we can see the number format exception error it is there. Now, we will see these
are not actually errors they are called exceptions because in some situation this program
not able to handle this, and this so program is there is no error in the program rather these
programs cannot handle all input that is the cases of exception that is why they are called
exception.

(Refer Slide Time: 05:10)

Now, let us see how we can make our program robust using the exception handling
mechanism it is there. So, let us have the first program there. As we see this program
10.3, this program we see there are lot of exception scope of exception as we see for

555
example, in statement x; display, display yeah, ok. So, here we can see in that class
demonstration 103 we see a equals to x divided by y. So, there is a scope of an exception
to occur because if y is 0; that means, any function is called with two arguments with the
second argument is 0 and then again there is a possible job exception in integer.percent
in case suppose if we run this with non integer parameter passed through there right.

Now, anyway. So, this program has that it is, it is if we compile it or definitely there is
no compile-time error this means the program does not have any error there. So, if we
run it for two it is no error, but if we run with see first argument other than 0 then, ok; 10
and 0 for example, as we see here two inputs one is 10 and another is 0, because second
input if it is 0 it will basically divide by 0 or arithmetic exception as we see here
arithmetic exception error occurs here. So, this is a case of exception that we can see and
we see this program is therefore, not so robust.

(Refer Slide Time: 07:10)

Now, towards the implementation robust program, we can use simple try-catch. So, this
is the example to show how the simple try-catch can make the program robust.

So, here the point of exception where we just enclose it in the try-catch block, and there
is another source of exception there a equals to integer.percent they are also a source of
exception there. So, we have just put them in the try-catch. Now, this program will run
for any input whatever the input that was not working in for the previous case.

556
Now, let us run this program with inputs 10 and 0 again. As it was not working there in
this case you see it works there and divide by 0 it reported and then result in 0 returns
this one, ok. So, this way we can; so in previous cases the program was not program was
abnormally terminated rather, but in this case program run successfully, but exception
which occurs it caught and then handle it.

(Refer Slide Time: 08:12)

Now, the next example is basically, so how the robust program can be developed. Again
the same thing, if we run the different cases we can skip let us go to the 10.6 runs the
following program, run the program without exception handling mechanism for some
input.

Let us see have the 106 programs there, yeah. 10.6 program as we see here this program
includes again exception in many regions here in the, for example, string my string, new
string, I, there is a possibility if i is 0 in all points are assignment and then next if my
string 0 equals, ok. We can write it instead of my string 0 you know you just write args 0
if args 0; no if args 0 ok, that is fine it will work ok, if args 0.

Now, let us compile this program and as we see it will work for some input, but not all
output, not all inputs, ok. And again if we run this program first say Java input is capital
J a v a. So, it basically runs this program correctly and I love Java. Now, let us see you
can see this program basically starts at the point here in the last statement. So, an error is
there. It will not work for example, now what will happen if we run this program without

557
passing any input common line. So, just simply run. It is also giving an error because an
array index out of bound error is there. So, we see this program is erroneous.

Now, let us implement this with multiple catch block.

(Refer Slide Time: 10:08)

So, this is an example to illustrate the try with multiple catch. So, all the errors all the
exception that occurs there in the program can be handled using try or that means, try
will check if exception if any occurs during run time and then corresponding catch will
catch all the exception and then handle them with their proper code here. Here very
simple code that we have used system print l n only.

Now, here there is point one where the error occurs, point two also the error occurs and
point three also the error occurs here. And we just in the process of catching this here
arithmetic exception and then if it is there so first catch is to catch the arithmetic
exception, second catch to null pointer exception, and then the third catch is to array
index out of bound exception. So, this way if we run this program again it will run
successfully, again my string 0 you can check it arg 0 that is all. If the statement, is ok,
fine.

558
(Refer Slide Time: 11:12)

So, this program is now robust and whatever the situation happens here in the last case it
was working java all the input it is where, but I love java it was not working there. A null
pointer exception java.lang.nullpointerexception where it is? Ok, you just do my string
whatever it is here, ok. Run this some of here is a program, yeah. So, no compile-time
error, yeah. So, there is an error because no input, if we do not give input one error will
be there, if we just simply java a null pointer java.lang (Refer Time: 12:12), yeah.

So, it was working correctly; there are some marks there we have resolving. Anyway, so
now, again if we run this program java without any input, I mean this program without
any input common line output these also it will catch the exception and accordingly
program will not abruptly terminated. Array index out of bound this is why it gives the
error, fine.

So, let us have the next one. This is also another example that multiple errors by a single
catch. So, this example we can see the multiple errors here in the switch statement
actually, in every switch there is an error is there. And then if we run this program as we
have make the program robust by using single try, but the multiple errors are only one try
and then catch is to handle all the catch here you can see catch exception e because of all
the irrespective of the type of error it will catch it. This is the exception is there.

559
(Refer Slide Time: 13:26)

And this program will; ok. If we run it, it in fact for each switch statement case statement
it will face an exception and this accession will be caught by the catch statement.

(Refer Slide Time: 13:33)

Yeah as we see so all exceptions that occur in the four case statements are caught in the
single catch statement.

560
(Refer Slide Time: 13:58)

Now, so there is another block that can be added with the try-catch block called the
finally,. So, here is the next program that we can see, ok.

(Refer Slide Time: 14:03)

We can see the block with finally, so all the exception that can be caught by try here the
try statement and then corresponding catch, and then we add it finally, statement here.
And as we see whatever the exception whether occur or not this finally statement will be
executed and it will accordingly the code will be, code will run and then gives the output.

561
Now, let us run this program as we see the greetings has the three, so this while loop is
successful for three, first three loops, I mean three iterations 0 1 3, but three for the three
because less than 4 means this loop will roll till 3 and for the last one it will report an
error and then we will see the finally, will print this statement accordingly. So, here we
can see it will print high statements all the time, but the next if i less than 3 it will do
nothing but it will be if i greater than 3, ok. So, as we see this is the output here and the
last statement finally, whenever I loop is there fine. So, here we can see that finally block
if it is added with try-catch. So, for every try-catch occurrence this finally will be
executed, this is the main use of the final statement finally statement.

Now, our next illustration to highlights the throw clause in a program and here is
basically the demonstration of the throws.

(Refer Slide Time: 15:35)

As we see as we have discussed in our theoretical discussion a throws clause can throw
an exception explicitly and that exception then can be caught in the try-catch block here.
Now here is a small program segment as we see the name of the class is demonstration
and the score 1010, and here array is a declaration of size 3 and then try for integer i
equal to 0, i less than 4, so 0 1 2 3. As it is an array size 3 definitely for the first array it
is an array index out of bound exception it will be there. So, for i equal to 0 no exception,
i equal to 1 2 no exception, for i equal to 3 the exception will be there.

562
(Refer Slide Time: 16:27)

Now, this exception will be caught in the try block and then catch will do it and here
actually it will see the different methods those are there in the exception class is invoked
here. For example, getCause, then fillInStackTrace, then getLocalisedMessage,
getMessage whatever it is there. So, it is basically the implementation of exception class
in java.lang.throwable to package and according to this, we can access this method in our
program.

So, this catch whenever it occurs it catch the array index out of bound exception, for that
error it will basically give the all message trace and then regarding the complete
information about the exception that it occurs there via the different methods in that
throwable class. Now, let us run this program and also it has finally method.

563
(Refer Slide Time: 17:19)

And here you can see within this catch block we include the throw statement it basically
throw the exception to the caller. So, this method if it is called here the method is
basically the name of the method is named the here method is ok. So, here is no caller of
course, so it will not return anything to any other, but if this method is the try-catch block
is inside a method, which basically throw then the throw an exception which basically
returns to the caller here, fine.

So, this is the complete methods are there, if we run it then we can see how this output it
will give for us. So, it is basically showing the exception as we see for others it will give
it. Where is a program compilation? It is here, yeah. So, java array index out of bound
exception for 3 and it gives all the detail information about the exception it is there. So, if
you want to scrutinize this program for further details and then the cause and effects and
everything then all those information will be useful.

564
(Refer Slide Time: 18:48)

Now, our next example is basically a nested try-catch example. Nested try-catch example
as we have mentioned that a try-catch block can be put inside another try-catch block, so
it is called the nested here now, this is the one program. As you see this program does
not have any error but when we want to run it, it may leads to some exception. Here this
program if it is run for the three different intention, for example, let us run this program
and give the three intentions as we see and when the exception occurs you will see
exactly.

(Refer Slide Time: 19:15)

565
So, without try-catch this is the implementation and run this program first with 1 2 3 as
an input yeah, so this program is successful at this stage. Now, 1 2 only two inputs it
gives an exception as the array index out of bound exception. Now, again with only
single input it also gives an exception it is also an arithmetic exception. Now, no input it
also gives an error, it is also given the error that, ok. So, we can see, so this program is
vulnerable to three inputs, as we are three cases, as three test data as we have checked it,
but it works only for them. So, an exception is there.

Now, let us see our enmity how this can be robust, make a robust program using try-
catch, nested try-catch.

(Refer Slide Time: 20:13)

Now, here if we see the first blocks 42 by a is basically arithmetic exception and if a
equals to 1 it is an arithmetic exception. So, it is a very similar kind of exception. So, as
it is only one exception, so this can be tried with an only try block. So, this is the outer
try block.

Now, inside again this is another exception if a equal to 2 it is basically the exception is
called array out of bound exception. So, to take care of this exception we put another try-
catch, so inside this one. So, this is an example of a try-catch. As you see the in-out try-
catch caught, I mean try for the array index out of bound exception and catch
accordingly whereas, the outermost try-catch block caught the arithmetic exception here
and cause it. So, this is the idea about the instant try-catch block.

566
(Refer Slide Time: 21:07)

And now if we run this program and again try with all possible output for which it was
not working in the previous case let us see what will happen, 1 2 3 it is work. Now java 1
2, it is 1 2 it also works, right. It is showing the report; it basically catches the exception
that has been cached. Again 1 it is also seen divide by 0 it is basically the exception has
been caught, and then these also by 0 it is caught.

So, in this case, the program is robust in the sense that in the cause of exception the
program will completes its execution and finally without any abnormal termination or
any causes or loss of data whatever it is there. So, this is a concept of exception handling.
In fact, exception handling is a very important feature in java programming language
scenario, and more practice is required of course.

567
(Refer Slide Time: 21:54)

Again I advise you to practice all the example that we have used in this demonstration so
that you can practice your own. And then this basically hands-on practice is required to
understand all these things thoroughly, and in case of any doubt and confusion, you are
most welcome to, feel free to ask us. So, thank you for your attention.

Thank you very much and all the best for learning.

568
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 27
Multithreading – I

So, today we shall start about multithreaded programming very new concepts in
programming arena and this multithreaded programming concept is very important to
develop many different type of software. For example, java is best suitable for
developing application software’s such as library management system, word processing
system like this.

It is also equally best suitable for developing system software such as compiler operating
system. Now such system software development is possible using java because of this
features the multithreaded programming concept. Now before going to understand about
the different features so, for the multithreaded programming is concerned first we should
clear our idea about what exactly a multithreading is.

(Refer Slide Time: 01:13)

Now, as the name says the multithreading it is basically the short form of multiple thread
threading actually that is why multithreading. So, definitely so, it is in contrast to single
threading we can say. So, what exactly the concept of single threading is, that here we
can see this is a one example of a class which has one method. So, this is a method as we

569
see and in this method as the execution takes place from the very first statement to the
next statement, the next statement and so on.

So, this way the multithreaded this way a thread will occurs. So, this way the thread will
occurs starting from this to this direction. So, we can say in other way about that if we
start from with the first statement like so is a begin the next statement, the next
statement, next statement and so on and finally, it will go to the end of the statement.
And this way the threads or the execution that it takes place is called a single threaded
manner and then the execution is called the single threaded execution.

Now, in contrast to this single threaded execution there is a concept called multi thread
execution.

(Refer Slide Time: 02:51)

Here is an example that we can use this example to explain the concept of multiple
threading here. So, execution here will start from this point suppose and then if we can
bifurcate this execution into 3 or more here for example, bifurcation into this is a one
part, this another part and this another part then it is called that. So, the execution will
take place in a concurrent manner; that means, it will run this part, it will run this part
and it will run this part. So, all 3 executions can take place in a parallel manner or in a
concurrent manner then we can say this is a multi threaded execution.

570
So, this is a idea about the multithreading now here one important point that we should
note here is that whenever the threads are in execution all this threads can exchange the
data among themselves. Here for example, the result that is produced by these thread,
can be used by these thread or vice versa like this, also they can use a global data among
them also not global data means common data among them also anyway. So, these
thread whenever they execute, they execute in parallel and then the data exchange is
quite possible among them

Now, as an another example we can consider one more another example.

(Refer Slide Time: 04:21)

Let us consider this is a one part of the program and here as we see this program or you
can say the main method consist of different modules. So, this is a one module, this
another module, search module, clean module so, different modules are there. Now if
this program executes in a single threaded manner this means that this module will start
it is execution completes then only the next module start and so on. So, this way the
single threaded execution will takes place. So, pictorially the single threaded execution
will look like this pictorially the single threaded execution will look like this so, it is this
way.

Now on the other hand if the same thing which if we run in a multiple threaded then it
will look like this. So, if we run in a multiple threaded then as we see here. So, in a
multiple threaded as you see. So, after the reading operation is there it will bifurcate into

571
3 different what is called the parts, the sort, calculate and search. So, what you can say at
this stage there are 3 threads, sort thread, calculate ThreadAnd search thread. They can
execute in parallel and once all this threads are finished their execution it will come to
this ThreadAnd then print will execute. So, this way this parts can execute in a multiple
threaded manner, this is single threaded manner. So, this is a concept of multithreaded
execution or is a program.

(Refer Slide Time: 06:33)

So, now, we have learnt about the idea about the multithreading how it works is there,
there are many example that can be given why are the multithreaded execution is
obvious. So, whenever we are using our system computer there are many task which is
basically works in a continuous concurrent manner. For example, when you are reading
web page at the same time you can type into using word processor and at the same time
you can play your music. So, all the things are going in parallel. So, for everything for
playing a music there is a one thread for browsing the information from the internet one
thread whenever you are typing something using a word processor application is another
ThreadAnd all these things.

Now so there are many applications where the multithreaded way the executions are
there and to be carried out. So, that we can achieve maximum things from the system,
now how this multithreading actually can be achieved in our system, there are in fact, 2

572
ways the multitasking and multiprocessing. So, in our few next slide we should
understand about what is the multithreading and multitasking is.

(Refer Slide Time: 07:53)

So, here the multitasking is also alternatively called the time sharing; that means, if we
have to run the multiple programs together. So, is a part of one program can share the
CPU time or some other resource time and at the same time whenever the CPU is busy, it
can share some other resource and this one or actually the idea is that multiple programs
have their own time slots and each program can use their time slots so, that they can
execute this program. So, this is the way the multitasking things can be achieved and in a
time sharing manner.

573
(Refer Slide Time: 08:42)

Here is an example that we can use to explain how the multitasking it is possible and. So,
say is a basically single task if it is a single task as we see whenever the single task
requires the CPU time it is their and if it requires at the same time some other resources
say suppose input then the CPU is idle. On the other hand, once the input is reading is
complete then the CPU is engaged for some other task one this task is complete then it
may be some other task say some printing and one printing is over another task and so on
so on.

So, what we can see is that CPU is not busy for all the time whenever it is executing a
program if it is a single threaded because of some other resource requirements. So, this
way actually the a performance or efficiency or the throughput of the system is less as
we can see if we execute this way the code is executed only 57 percent where the system
remain idle for 43 percent. So, this is not an efficient way of solving this program.

On the other hand, if we run 2 programs concurrently say P1 and P2 for example,
whenever CPU is idle, at the same time if we can engage the CPU by other program then
whatever the ideal time can be vanished and then CPU can utilize 100 percent utilization.
So, this way the multitasking if it is possible here actually we can give the time sliced P 1
into this time then next this time and this time for the P 1 this time for P 2 and so on. So,
the time can be sliced among the processes. So, this way it is not only for the 2 processes
even multiple processes n number of processes can be time shared and time slice can be

574
given to each processes. So, that CPU will be busy and then the program all programs
will be executed in the fastest way.

Now, so, this is the idea about the multitasking is a one way of doing multiple threading
actually.

(Refer Slide Time: 10:56)

So, now other than this the multitasking there is one called the multiprocessing. So, it is
basically the idea is same it is also multithreading, but the idea is called multiple
processes can be engaged here. So, if there are say modules m1 to mn so, all these
modules can be assigned to different processors. So, that all the processors can run
concurrently in a parallel manner.

So, this way the program the entire program can be executed in a faster way and there
are many multiprocessing systems are available today, as we know for example, here
Pentium Xeon having the 32 processors you need Athlon X2 MD is a dual core processor
and then there are 4096 processor Cray X1 having so many processor now. So, these are
the high speed competing environment which basically allows to execute a program in a
multi threaded manner.

575
(Refer Slide Time: 12:05)

Now, so, here is basically the 2 concepts. So, for the multitasking is concerns so, process
and thread. So, basically the entire programs can have the different parts this basically
the process. So, process is basically is a program is an executable form which can be
loaded into the memory and then once the processors are loaded into the memory
operating system can take care the execution of each processes.

And on the other hand there is a concept of threads which basically the idea about that
how a process can execute in the system. So, it is basically it is a thread is basically a
sequential execution of a set of instructions one by one. So, there are multiple thread
means there is a multiple set of sequential execution of a system which can share the data
among them.

So, multiprocessors multiple processes this basically multiple threads we can say and
whenever one ThreadCome into the picture it is basically is a single process with a single
set of execution. So, multiple threads is basically a concurrent execution whereas, a
single thread execution is called the light weight process because it is a on
ThreadActually.

Now, so, we have learn about the multithreading and we can learn that a multithreading
means a concurrent execution. Now let us see how this multithreading is useful to solve
many problems as we are solving nowadays in our own computing system.

576
(Refer Slide Time: 13:52)

Now, you know whenever you are using the Gmail software or a Google browser. So,
Gmail software is basically loaded into some server is a Google server Gmail server and
you know at the same time the billion of peoples are using the same Gmail server. In
fact, then how this Gmail server processes all the Gmail users actually at the same time.
So, it is basically they the Google server which basically run the Gmail software’s in
their own system they processes all the users in a multiple threaded manner so, this is a
one example of the multiple threading.

As we see from here a user a user can place a request or can browse the Gmail from the
say Firefox, another Internet Explorer, another may be Opera so all the request goes to
the server at the same time so, billion of requests are there, then this server can process
them all the request individual in a multithreaded program. However, a user can think
that this server is dedicated to his service. So, all user can think that I am getting as if the
I am the only soul user in the system, actually the Google server serves multiple users at
the same time and this is possible because of that multithreading concept as it is followed
in execution.

577
(Refer Slide Time: 15:26)

Now, so, there is idea about this one and then basic purpose of this multi and this is
another example another example of multithreading using multiple processor. So, idea it
is that if so, many users one single server cannot handle then at the end the multiple
server can take care and then they can use it. So, here only 2 server as you see instead of
2 server a large number of servers can take care and then multithreading also can be done
in a multi processing manner also. So, basic idea about that it will not only process
multiple programs in execution, but it reduces overall time of executions for all
programs. So, this is a great advantage that one can achieve using multithreading
manner.

578
(Refer Slide Time: 16:18)

And this is another example as we see in the context of internet programming. So, the
idea is that if a many users are there in network access the network with different devices
like laptop, mobile phone, PDA, PC personal computer whatever it is there now all the
users those are there in the system they are connected to a server called the proxy server
and then.

So, these proxy server can know that which request to first 2 home in what way so, if so,
there is basically the different other servers those are distributed worldwide and then
from this internet server the request will go and then, they basically possess all the
requested and that again that are the end of the service.

So, another request also come from another network they also process and then they
produce the output and the output go to the again this proxy and then they can again
transmit to this way and this way the multiple execution takes place. So, for the internet
programs are concerns. So, this is a concept of internet programming and internet
programming is today possible because of the concept of multithreading as it is possible.

579
(Refer Slide Time: 17:47)

So, there are multiple servers that can execute in parallel as we see here for example,
these are internet server and there is basically service request that receives why a server
that needs for to process the different clients and then here as we see this server can run
many threads. So, they are called parallely. So, overall time that is required to get it
serviced will be reduced remarkably and that way we can improve the performance of
the system.

(Refer Slide Time: 18:27)

580
So, there are many example as we see where the multithreading is there now this is the in
the context of internet related it application now even in our single PC system also we
need the multiple threading. Here for example, the user whenever editing a document at
the same time he can fire a print come on to print one paper. So, to him both the things
editing as well as printing takes place together. So, this is also possible because here the
system can take care 2 threads one editing ThreadAnother is a printing thread. So, is a
pages will be printed one by one it will control the printer buffer and then get the
response and then do it. So, the system which is here can control both the applications
together.

So, this is one example even in the single user in moment also the multithreading is
required in our problem solving.

(Refer Slide Time: 19:26)

And here is another example also. So, for the operating system level is concerned we
also require the multithreading say suppose we are reading something from our hard disk
at the same time we are copying something from our pen drive or floppy disk to hard
disk. So, how this thing is possible again this is possible because of the multithreaded
program. So, they are actually 2 programs one is a writer and the reader, the reader will
read from the floppy hard disk and writer will write in to the hard disk and both things
will takes place together in a multiple threaded manner

581
So, this ThreadAnd this thread will execute in parallel and in a multithreaded manner
actually. So, there are several applications as we see where the multithreading is must ok.
So, we have learned about why multithreading now this is our turn to learn about how
this multithreading is possible in java. There are many features many concepts are now
available in this context and you will learn all this features one by one in the next few
slides.

(Refer Slide Time: 21:02)

So, here is basically the multithreading is done in the different level, first is the code
level, then medium grain the control level and then fine grain it is a data level and these
way very fine grain the data level it is there. So, here basically in the first code level
multithreading is possible because we have to first decompose the program into different
task where all task can be done independently.

So, at the task level or is a code level is called the code granularity or the task level the
multithreading will start first; that means, you have to when you write the program you
can tell that this is the piece of the code and this is other piece of the code the 2 task they
can do independently and then 2 threads can be planned for that.

One it is there then we can write the threads for each and then the all the threads can be
takes place and then at the execution level it basically creates the process for each thread
is basically the code that is executable for example, in case of your java execution the
byte codes for each threads actually it is there. So, it is a so, for each thread there is a

582
separate codes that can be placed there and finally, at the CPU level for each code can
takes place in a inter living or in a concurrent manner as it is basically, whether that is a
operating system can manage how this task, this task and this task can be carried out
parallely. So, they can use some process synchronization from time sharing or many
other methods that the operating system can follow for you to execute to more than one
thread together.

So, this is the idea about the parallelism is takes place in this right and java programming
is basically helps us to implement all this concept here, but at it is a very high level
concept. So, we do not have to bother. So, much details which is basically there only we
have to think about this code level and then, this is a that code level if we can plan it; that
means, program level we can say we if we can plan it, then we will be able to achieve the
multithreading. So, java exactly does for these things for us for the programmer.

(Refer Slide Time: 23:37)

Now, so here basically single thread verses multiple ThreadAs we say earlier that this is
the one single thread if it is there one execution, if the multiple thread mean multiple
executions and they can use the common memory common data together actually this is
the idea.

583
(Refer Slide Time: 23:59)

Now, a therefore, what we learnt is as a summary that, a thread is a piece of code that
runs in a parallel manner with other threads and each thread is a statically ordered
sequence of instruction; that means, each thread is basically one set of a sequential
instruction we can say and all threads are extensively used to express concurrency
whether in a single or multiprocessor machine whatever it is there that mean either in a
time sharing or in a multi processing whatever it is there.

Now, let us see the features which are there so, for the multithreading is concern.

(Refer Slide Time: 24:38)

584
Mainly 3 things that we have to learn about that, how to create a ThreadAnd how to
schedule the thread so, these are first thing and then second thing is that how the inter
ThreadCommunication can be takes place and finally, the synchronization of this
threads. So, in java there are many what is called the methods are available and there is
again package the package which basically responsible for running multiple threads are
there.

Now the different process that is related to I mean all this task like ThreadCreation,
thread scheduling, thread execution and then inter process ThreadCommunication
synchronization there are few methods which we have mentioned here these are the
methods is basically there.

Now these are the threads execution is done by is basically automatic one manager. So, it
is run time manager we can say the thread manager and this automatically run for you
now an example of a thread which usually occur in whenever you run a java program is
called the garbage collector there is also. So, this garbage collector is basically take the
memory and then how the memory can be efficiently used.

(Refer Slide Time: 26:00)

Now, so, there are many other concepts are there which basically to be considered
whenever we have to schedule the ThreadAnd then control inter process communication
among the different threads and then synchronizations.

585
Now, for all these activities there is a package which is there in the java jdk called the

java.lang and in the java.lang there is a class ThreadAnd one interface called Runnable.
So, these are the 2 main things that is there in the java and so, for the multithreading
learning is concerned we have to learn this class ThreadAnd interface runnable and using
this ThreadAnd interface runnable we have to learn about how the multithreading is
possible.

(Refer Slide Time: 26:46)

Now, the basic concept about so, for the creating a thread is concerned you write a
program for a thread that is basically the task and then once the thread is ready then you
have to first run the ThreadAnd then before running we have to start this. So, basically it
start and then this so, whenever a thread is build it is basically inactive ThreadAnd if you
can start it the ThreadBecome a alive and from the alive threads run until it terminates
when the thread is terminated the thread is called the dead.

So, doing I mean for controlling, all this start run and everything. So, there is a procedure
which is defined methods which are defines there in the class ThreadAnd in the runnable
interface. So, as you know it is an interface this means the methods are abstract and
public that mean we have to write our own code how to run the ThreadAnd obviously,
how to start it.

586
(Refer Slide Time: 27:44)

Now, basically the main idea about that if we use a ThreadAs a class which is there and
then your thread should inherit these ThreadClass to build the run method. So, it is
basically we have to override the run method if we use ThreadClass. On the other hand if
we use the runnable interface, then we have to implement the interface using your
ThreadClass and then they are also you have to implement the run method. So, this is the
basic concepts.

Now, we will discuss about using the both how the ThreadCan be created and then how
the ThreadCan be executed. So, let us first start the discussion about how we can create a
thread with the ThreadClass.

587
(Refer Slide Time: 28:25)

So, idea is very simple we have to extends the java dot lang package ThreadClass and a
ThreadClass can be created.

(Refer Slide Time: 28:39)

And if you use a interface then we have to implement the interface here now here is an
example that we can see how we can create a ThreadAnd what are the methods are there.
So, here basic idea about that this is the class thread extends objects implements runnable
whatever it is there. So, public thread these are the methods these are the constructor I
can say the thread has the constructor in a different form where name of the thread the

588
interface runnable object can be pass to them and then both name and threads and
everything and they are run into. So, these are the basic structure of the class thread
which is defined in the java dot lang package. So, it is simple not so, very complex
things are there, now we will slowly one learn one by one how all those things can be
handled in our program.

So, this is about the ThreadClass as we see there are constructors and there is a 2
methods run and start and all this 2 methods are as it is basically override because it is
abstract whenever it is there.

(Refer Slide Time: 29:42)

And so, for the different methods are concerned in the ThreadClass other than the this
start and run method also it includes few more methods which we have listed here join
get live, get name, is alive, setting priority, sleep, yield and so, on. So, these are the few
methods are very learning all this methods will basically completes our learning about
the thread execution.

589
(Refer Slide Time: 30:25)

Now let us first discuss about how we can create our own thread using class thread. So,
this is basically typical steps or procedure that you should follow in your program. So,
here you have to declare a class of your own that is basically your ThreadClass which
should extends the ThreadClass that is there in java dot lang package and then these are
run method we have to override this run method in your program and then once this
ThreadClass is created you can use this ThreadClass to create your own thread.

So, this is your own ThreadAnd this is basically creating a thread objects and then if we
call the start method for this thread object. So, the thread will start it is execution and
then the run will be invoked. So, the run method will be invoked so, that the alive Thread
can execute in the system.

590
(Refer Slide Time: 31:28)

Now, here is basically the idea about idea about creating the program this is a complete
program that we can see here and as we see this is the one ThreadClass as we have
declared. So, class ThreadA extends this so, ThreadA we create a thread of our own and
this thread, we in this thread we declare the run method of our own you can see the run
method is declared here it is basically there is a loop, loop will roll for i equals to 1 to i
less than equals to 5 (for (i=1;i<=5;i++)) and whenever loop will roll it will print this 1.
So, what we can say that these thread; ThreadA whenever it will run it will print then 5
negative numbers one by one.

On the other hand there is another thread we have created ThreadB, it is similar to this
thread, but here in this run method we define this kind of code it basically run the even
numbers. So, 2 threads as we see we have declared here and once the threads are
declared we can use it. So, these are the 2 threads in addition to these 2 threads there is
one more threads also.

591
(Refer Slide Time: 32:53)

So, ThreadA and ThreadB that we have discussed in addition to Thread And there is
another ThreadC these basically also the similar run method which we have discussed
here. So, what we can say that we have created 3 threads ThreadA, ThreadB, ThreadC,
creating 3 thread is basically the business about that how we can define the run method;
that means, the how the thread will execute.

I can tell one example suppose if you want to create 2 thread one for sorting program,
another for searching program. So, in the run method you have to implement the sorting
algorithm may be say quick sort and another run method which basically thread for
searching we can implement the binary search algorithm it is a example like this. So, in
the current example we have created 3 threads to print the 3 different types of number
one is negative number, even number and odd number. So, these are the threads creation.

Now, let us see how once the creates threads are created how can utilize in our program.
So, this is basically the main method as we see the main method it is there name under
this class these are main class. Now here we just look this things carefully what we can
do is we create one thread object a of the thread; ThreadA. Similarly B and C are the
thread objects for the 2 different ThreadB and ThreadC namely. So, here we can see 3
different threads objects are created.

Now, so, a dot start and b these are the basically once the thread object is created we can
start execution of this thread. So, here basically to do this thing we have to call the start

592
method for a b and c. Now at this point what happened is that this is the single thread
that is creating this and then immediately a dot start the on thread for a thread; ThreadA
for b ThreadB and c for ThreadC will be executed. This will print the negative number,
this will print the even number and this will print the odd numbers and then finally,
whenever it will come at the end of this one it will come to this System dot out dot
println and it will print that that multithreading is over. So, this way the thread will
execute in our program.

So, what we have learned is that there are 2 main methods, that is basically more crucial
whenever the thread is there the run by the run method you have to declare that what is
the task that to be accomplished by a Thread and then this start method. So, start method
is already defined here there in the java dot lang dot class. So, just we have to use it to
start the execution of the thread. So, this is the concept about the Thread creation and
then finally, execution of thread ok. So, we have learned about how the Thread can be
created using Thread class and in our next module we will discussed about other way of
running threads and managing the threads.

Thank you very much.

593
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 28
Multithreading – II

So, in the last module related to multithreaded Programming in Java, we have discussed
about the basic concept of Multithreading and then how the thread can be created in Java
program and then how the different threads can be executed in parallel. And in the last
discussion, we have used the class thread to create our thread. Now in this discussion, we
will discussed about how the Thread can be created using the Runnable interface the
procedure is very similar to the Thread class creation only a few minor difference is
there.

(Refer Slide Time: 00:53)

Now, let us first start with how we can create a thread using Runnable interface. As you
know if we want to create our Thread using class Thread so, we have to create a Thread
class which is basically extending the class thread. On the other hand the same
procedure, but here we have to create a Thread class that implements Runnable. Now
implements Runnable means in the Runnable interface the method run method is there
which is the public and abstract method these method needs to be created. So, it is

594
basically implementation of this run Thread is similar to the implementation of the run
method that is there in the Thread class here.

So, in that case, the Thread class run method they are in if you have to extend Thread
class is overriding, but here the run method is to be implemented. Once this class Thread
class is created by Runnable interface then we can create a Thread object for example,
here T is the Thread objects and when you create the Thread objects you see we use the
Thread class and pass these as a parameter. So, my Thread that you have created a new
my two all object is needed to be a pass. So, this is the only difference that you have to
these.

In other cases, if you use the Thread class so, Thread to new Thread no argument to be
passed. So, the only default constructor will take place, but here in this if you use a
Runnable or implement the Thread class using Runnable interface then that object needs
to be passed here, that is the only difference otherwise everything is same basically. So,
here T dot start is basically to start the execution of this thread. Now it is basically the
same again that this is the run method that we have to define as it is we have defined
there in the creating clays using extension of the Thread class and then T start.

So, both the things are, here again, now let us again repeat the semi same procedure that
we have discussed about in ok. In our last module exam example, we have considered
about 3 threads Thread a, Thread b, Thread c, which basically p negative number, even
number and odd number. The same concept here also we are we will just implement
each, but using Runnable interface so, that we can understand that how the two things are
work for us.

595
(Refer Slide Time: 03:22)

So, here exactly let see this is the Thread X I have given the name Thread X, in this case,
implements Runnable. So, this is the similar the run code that we have used earlier and
then Thread Y same as Thread b that we have discussed here, but it implements the
Runnable run method here.

(Refer Slide Time: 03:48)

So, ThreadX. ThreadY are declared and then it will implement the Thread Z. So, this is
the Thread Z. So, 3 Thread ThreadX ThreadY and ThreadZs are implemented. So,
created we can say 3 Thread class are created by implementing Runnable interface and

596
this is the main method as we see here these are the main class and here you can see we
create x y and x and y are the Thread object of this Thread x class. And then Thread is
basically created t 1 bypassing this x because, if we use a Runnable interface that object
needs to be passed as a constructor to call the I mean Thread class actually this is a
constructor that is defined in the Thread class.

So, these ways we can see t 1 t 2 and t 3 as you can see in this case again we can call in
one here actually two-step process but is a single-step process that means we can create
the Thread directly call this these passing these also it is equally applicable here. So,
what we can see here t 1 t 2 and t 3 3 Threads objects are created and one these 3 Thread
objects are created they are ready for execution and these are the basically to start the
Thread we use t 1 dot start t 2 dot start t 3 dot start and then Thread will be run in
parallel. So, this is the multithreading using Runnable interface as we have learned it
here.

So, we can see basically the same thing implements versus extends and then just how to
create the Thread object otherwise for the run and everything the same in both concepts.
So, the two ways of running a multithreading program using extends and Runnable
interface.

So, there is no I mean such a rule that these were these way the search basically the
difference syntax we can say the different procedure how the different Thread can
executes now. So, we have learned about how a Thread can be created although it is a
simple example that we have considered, this is the idea about and then it can be
extended to any type of complex there any number of threads can be executed any
number of threads can be then started to execute.

Now there are many more things are there particularly a Thread can be in a different
state. So, now, we will discuss about what are the different states that a Thread may have
and this is very important because whenever we have to control a very complex program
you should know the different states of a Thread that it may have and then how we can
communicate one Thread to another.

597
(Refer Slide Time: 06:33)

So, basically the interfaces inter-process communication. Now, so, far a Thread is
concerned it has different states like Thread can be in a new state. So, this mean the
Thread is just created and it is yet to start its execution. So, it is a new Runnable. So,
Thread is basically being execution that means it is about to run and run this is basically
active the Thread is in the execution and blocked somehow Thread need something or
Thread has been stopped or it is slipping so; that means, Thread is in a waiting state it is
called the blocked state and then finally, a Thread can be in a dead state; that means,
when it finished it execution.

So, these are the 5 different states that a Thread can be in this there and there are
different methods by which a Thread can change its state like a new, start, yield, sleep,
wait and notify and other some external events also their scheduler, I O and returning
from run and resume all these things are there.

598
(Refer Slide Time: 07:51)

Now, let us have a detailed discussion detail account of all these methods which
basically to control the states of a threads are there, now this is a state transition diagram
for a Thread that it may have as we have checked that a Thread can be in a new state. So,
whenever the created and then this Thread can be in a new state this means Thread is not
yet started its execution, but ready to start its execution. Now when the start method is
called then this Thread is basically Runnable but is a Runnable basically gives to the
scheduler it is basically the Java run time manager it basically all the Threads are now
started it but is about to execute or run it.

When the scheduler can call it is basically yield and then time slice is allowed to each
state may be in a time-sharing manner that it will share the different resources CPU all
these things so on. So, this is totally is a paradigm of Java run time manager which we
should not bother about anything, but it is basically working like this one. So, whenever
it is there so, it is running. So, there again once the Thread is running that Thread can be
stopped or can be resumed or it can be terminated or suspense so, it is basically
terminated.

So, once that terminated the Thread will go to the dead state otherwise if the Thread is
waiting for any resources in that it required may be Thread is waiting for some other disk
or memory that it is waiting. So, these are the running to it can go to the waiting state.
So, blocked in a running to waiting state the different methods it is there I O request

599
sleep, wait, join, suspend these are the methods which can change the state from running
to block state. From the block state it can again Runnable different methods, which are
responsible to move a state from blocked state to Runnable states are here.

So, these are the way that the Thread can change from new to dead state and the different
processes are there. So, this is basically state-run transition diagram says that how the
state of a Thread can change and what are the communicating methods are there to
control the execution of a threads and then Thread can be in a different state.

(Refer Slide Time: 10:02)

So, these are the different methods that we have learned about the start method we have
already used it and then suspend method. Suspend method is not exactly the stopping
stop method means the Thread will be dead but suspend means it will temporarily halt
the execution and then if a Thread is suspended by the calling suspend method it can be
again revoked using resume method.

Now, the resume method is basically when the Thread is in a waiting state or in a
blocked state it can be turned into Runnable state. So, the schedule scheduler can take all
the threads from the Runnable state to assign to the CPU for execution and then the sleep
method is basically by explicitly maintaining that Thread should stop it here wait for
some seconds may be n milliseconds like where the argument is n there. So, sleep means
the Thread will not do anything only the sleep for sometimes and yield method is
basically switching that takes from the context of a Thread from the current Thread to the

600
next available running Thread that is their Runnable thread. So, it is basically usually this
yield method used by the scheduler to invoke a Thread which is waiting ready for
execution that is there in the Runnable state.

(Refer Slide Time: 11:25)

Now, let us see how the thread's scheduling can be done.

(Refer Slide Time: 11:27)

And Thread scheduling can be done there are actually scheduler through scheduler is
basically responsible for scheduling a Threads; that means, scheduling a Thread means it

601
basically assign Threads to Java run time manager and is basically determines that which
Threads which are there in a Runnable state can be assigned to the system for execution.

Now, again in the Java system, we can assign the priority low, mean priority, high
priority, max priority like. So, according to the priority scheduler will call revoke a
method Thread from the Runnable state to this one and there are some threads we call
the demo thread. So, demo threads are basically running all the time in the system and
then the scheduler can interact with them so, that they can be executed and then they can
control their execution and they the Thread can be in any other states there.

So, the demo Daemon Thread is basically for the general service whenever suppose you
just insert one disk. So, automatically it detect that disk is there whenever some
interrupts are coming to the daemon Thread will take these are the few examples are
there. Now the program can be terminated whenever all threads are finished its execution
if there is some Thread is yet to be executed the program cannot be terminated and then
we have to do for the force termination by pressing the power button or like this one.

(Refer Slide Time: 12:58)

Anyway so, whenever the scheduling of a Thread is concerned again in the system there
are two type of scheduling called the pre-emptive scheduling and non pre-emptive, non
pre-emptive means one the Thread is in execution if it is a non pre-emptive scheduling it
is followed then this Thread cannot be interrupted until it finish it will start its execution.
So, no it cannot be interrupted whereas, the pre-emptive scheduling means, Thread is in

602
execution, it can be pre-empted may be either can change its state from running to
waiting for state or sleep or whatever it is there.

(Refer Slide Time: 13:38)

So, it is basically the policy of how you want to control the threads in your execution.
So, this is an idea about the pre-emptive scheduling that it basically. So, whenever the
Thread is in running condition, it will either terminates or it will go wait or ready wait or
ready until it finishes its execution. So, this is the idea about the pre non pre-emptive
scheduling; that means, it will no interaction interruption is allowed in case of non pre-
emptive scheduling is there on the other hand in case of pre-emptive scheduling as we
see.

603
(Refer Slide Time: 14:23)

As we see the pre-emptive scheduling is basically if there is an interruption occur. So, it


basically not wait it will from the run state to go to the ready state. So, this way pre-
emptive occurs anyway. So, this is the matter of policy that you can implement in your
system and this is the concept of an idea about managing the systems whenever you have
to implement it. So, pre-emptive non pre-emptive the core concept of how you want to
control your process in execution or we can say the Thread in execution.

(Refer Slide Time: 14:56)

604
Now, let us have an example of how the different methods are there which can be
implied to a Thread whenever it is in execution, this is again a simple method that we
can understand about it and it illustrates how the sleep method will work for you. So,
here is an example we can see we create a Thread class the name of the Thread class is
ThreadExample which basically created using Thread class. So, extends Thread now I
can tell you using implement Runnable also you can do it anyway.

So, here is the run method as you see how we can code the run method then this one it is
basically is a loop for loop and here you see sleep we use the sleep method for this that
mean whenever it executed this for i equal to 0 it will just call the sleep method and it
will sleep for 5000 millisecond. So, 5 seconds like and we put this code into this one
because here there may be an exception occurs that 3 Thread is no more there and then
we want to call this Thread using sleep method. So, this is why it is better to put under
try-catch. So, it is basically interrupted exception if it occurs then it can be caught it and
then handle from the premature termination of the program itself or the robust program
this is basically exception handling concept it is followed there.

Now, as we see. So, this is the run method this run method is just run the Thread and
here the idea is that Thread will for each loop whenever it runs. So, first 5seconds it will
sleep then again 5 second it will sleep and then another 5 seconds it will be sleeping like
this one. So, it is the idea about sleep there and if you print one system statement
system.out.print l n before here and after here that before sleeping first and then after
sleeping first then you can see that. So, the threads are executed in parallel wherever it is
sleeping intermittent way.

So, here is basically the idea about here we can see we have created two Thread
ThreadExample object and then start there so; that means, we run two threads parallelly
and if we run this threads parallelly with their print statement here in our demonstration
we will give a demo how this Thread can execute in a different order and everything. So,
this will give an idea about that the threads are running and invoking the sleep method;
that means, Thread is going to sleep there. So, basically, here the threat Thread that we
have created here we are sending a method to control or just change its state from may be
running to waiting for a state like this one or blocking state whatever it is.

605
So, this way the sleep method like this sleep method we can use many other methods as
we have discussed in previous slides namely, suspend all these things stop all this things
also we can call it here. So, appropriate code is to be planned for that to have it any way
we will discuss all these things in our demo. So, that how the different methods can be
called and then how their consequence is there.

(Refer Slide Time: 18:20)

Now, so, this is an example again we will discuss the portal execution of this statement
how this state can executed when the sleep condition I want to skip here. So, for the
theoretical it is more aspect. So, far that how it basically run, it in actual programming
environment ok. So, this is a Thread control we can say and these are basically the matter
the concept or the features.

606
(Refer Slide Time: 18:49)

So, for the inter-process Thread communication is concerns here and this is another
example of again inter-process communication of the Thread as we see and this is a very
interesting problem which usually occurs whenever multiple threads are in the execution
of the concept is called the DataRraces. So, here is basically we create one class called
the DataRrace which extends the Thread class here and here we declare one method run
which uses one static integer variable x there. Now, this method is basically used
interchanging for integer i equal to 0, i less than these are basically. So, many times this
will loop and for each iteration x equal to x plus 1 and x equal to x minus 1 as if this loop
is executed.

So, for every iteration x will be initially if x is 0. So, it is 1 then 0 1 and 0, but
interestingly if you run the Thread this DataRrace Thread and you see it it should in this
according to this one single Thread it will always keep the 0 as a value of x, but here the
thing is that because of this intermittent execution and then what is called data races are
there. So, if we run this Threads for this many loops and you will see it always not give 0
it sometimes keeps 1 sometimes gives 0, this is because of the different Thread whenever
it is execution and it is a static variable.

So, it prints the different situation whatever the values are there in this intermittent
execution. So, this is the idea about and then and it basically calls the data race example

607
in the Java programming concept. So, this basically says that how the different threads
are in execution that we can check it within this kind of illustration.

(Refer Slide Time: 20:47)

Now, so, these are the different way the Thread can be scheduled our Thread can be
communicated inter-process communication we can say and now next is that a Thread
can be synchronized also. So, the Thread synchronization and before this Thread
synchronization, there is also one concept is called the setting the priority our next
example is basically how the set priority of a thread can be established so, that the
scheduler can schedule the execution or the Thread according to their priority.

608
(Refer Slide Time: 21:23).

Now, so far the priority of a Thread is concerned there are three different priorities that
can be there in the Thread MIN PRIORITY, NORM PRIORITY and then MAX
PRIORITY. So, they have their global value called 1 5 and 10. So, we can set the priority
of a Thread by calling this method set priority which is defined therein class Thread. So,
if this is the Thread and then we can call this method setPriority and passing the num
number 1 5 or 10, then it will set the priority according to MIN PRIORITY NORM
PRIORITY or MAX PRIORITY, otherwise you can write this one min priority the
global variable declared in the Thread class itself. So, we can use it also.

So, a Thread can be assigned its priority and once it is assigned then the Thread can be
served using some CPU scheduling policy, for example, FCFS First Come First Served
policy look like this one. So, there is the way that the Thread can be there now let us
have an example.

609
(Refer Slide Time: 22:32)

So, that how this Thread can be priority can be assigned and accordingly the Thread
execution can be controlled. So, here is an example of this. So, here class A we create a
Thread and then run method we define here run method has a loop and this is a loop
control variable i equals to 1 to 4. So, loop will roll for times and each time the loop is
rolled it will print the value of i here; that means, loop variables. So, this is the Thread A
and similarly, this is the class A basically one Thread that we have created, now let us
have some more Thread because multiple Thread execution is more interesting.

(Refer Slide Time: 23:18)

610
So, here is another example and here is a class B another Thread that you have created
this also similar to the class A Thread, but it just printing the variable the loop variable of
its own. And so, this is the class B and similarly, we can define another class say class C
say another Thread.

(Refer Slide Time: 23:38)

And this is a class C Thread as we see class C Thread and then this also another a run
method it will print the k. Now we can see we have created just for playing only 3
threads by means of 3 classes class A class B and class C they are the from Thread class
the run method is created. Now once these threads are created now it is our turn that how
this main class can be composed. So, that all these three threads can be executed.

611
(Refer Slide Time: 24:12)

So, here is the main method as we see here this is the main methods and here we see we
have created 3 threads namely threadA threadB and threadC of the class A B and C that
we have discussed.

Now, once the Threads is created here we see we assign the Priority of the 3 threads like
threadC setPriority Thread MAX PRIORITY and then threadB setPriority threadA
getPriority+1, what is a Priority that the threadA Priority is there that by 1. So, this is the
Thread Priority sets and similarly threadB threadA Priority also Thread MIN
PRIORITY. So, these are the different ways the Priority can be set for some different
purposes we have setting this one. So, Thread Priority can be set this way, once the
Priority set we just simply start the execution of this thread and as you see this is
basically starting and start.

Now as you see whenever the threads are started it is not started in this way such this is
the first A will start B will start C will start is not that, if you see the print statement and
then in our demonstration we will see how this program gives the print output then we
will see that here out of these which has the first highest priority. For example, here
threadC has the highest Priority it will be executed first, then we see the threadB is the
next Priority because of threadA the lowest priority.

So, threadB will be executed and then ThreadA and then then the loop will be in an inter
min low a depending on the Priority the different execution will take place. So, this way

612
the ThreadPriority can be set and then it basically used by the scheduler to schedule the
Thread in its own way

(Refer Slide Time: 26:10)

Now, here is another example of the join method we have discussed, as I told you it is
also considered the con. So, if suppose one Thread cannot begin if the other Threads are
not finished its execution. So, in that case the other Threads switch should be waited for
to begin another Threads that can be controlled using join method here and this is a very
simple example as we see suppose t 1 and t 2 are the Threads are created, then we create
t 1 is a Thread and t 2 is another Thread by means of Thread class somehow created
there and we create by some methods are Runnable interface that means ok.

So, we have to run implement the two-run method by implementing the Runnable
interface that can be passed. So, the t 1 and t 2 the 2 Thread object can be created and
then they can be started its execution by calling t 1 start. So, what the thing is that this 2
Thread will start its execution because of these and then here try-catch there is a t 1 join t
2 join. So, there is a t 1 Thread t 2 Thread and then here t 1 join t 2 join so, it will wait
till all the Threads are finished.

So, then this one then only it will come to this one then it will execute the final
statement. So, join is basically the idea is that if there are many threads are there if we
join. So, all the. So, here the Thread point execution will wait until all threads are
finished its execution come here then the next task will take place there. So, this is the

613
concept of join is basically communicating or controlling the inter-process threads
actually.

Now, our last topic so, regarding this multithreading is basically synchronization of
threads, now the synchronization of threads in means that if two or more threads enter
into the same process then it may lead to lot of abnormality. So, what we can do is that,
if we use the synchronizations that automatically the Java run time manager will control
their executions say that no 2 Thread should not access the same data or same section
together that is called the critical section actually those are the students from computer
science they probably know that critical section is semaphore implementation.

(Refer Slide Time: 28:38)

So, it is basically synchronization, it is very simple the methods which we want to


synchronize just use the synchronize keyword before them and then synchronization
automatically takes care it is so, easy so, for the implementation is concerned.

614
(Refer Slide Time: 28:54).

Now, here let us have a very simple example that how the synchronization is there. Now
in banking transaction say suppose one Account where from the 2; one from the ATM
and one from the Bank terminal want to access the same account sometimes, in one
account one transaction one wants to use withdraw and another is to deposit.

Now, if they are not synchronized properly then, in fact, it can leads to a different result.
For example, say suppose in the account balance is 1000 and then once a deposit is 500
and withdraw is 300, if it is not successful then what is the out outcome will be that
either it is ok. So, it is basically the correct output should be 1200 because 500 deposits
and 300 withdraw, but if it is not successful then you may get that output as either 1500
or 700 because of the abnormality the situation is there. This means that both the
execution transaction deposit and withdraw should not take place simultaneously. Once
if it is not finished then others should not be executed like this one.

So, this is the one example that to this one here basically one class Account that is a
normal class which has some members and methods are there basically balance, account
number and displayBalance and whatever it is there is a very simple method are there.
And in this Account we define two methods deposit and withdraw and the deposit is
basically depositing the money. So, balance whatever it is their amount it will be
adjusted and withdraw means it will just this one.

615
Now, here we can see we use the keywords synchronized here one this means that if the
two methods are called for this class object account then they are basically already called
in a synchronized manner. So, it is right. So, this class is very simple to understand and
then only the thing that you should use the synchronize keyword here now.

So, this is the idea about and here is basically the class transaction we can say the
transaction is basically implementation using a threading example here we can see, we
implement transaction deposit there is two methods two transaction deposit class one is
related deposit and it basically implements Runnable. So, the run method as we declared
here this is basically the Constructor of this class and then run method is basically right
account X dot deposit basically these run method call this deposit method. So, this is the
TransactionDeposit.

(Refer Slide Time: 31:39)

And similarly, the transaction withdraw also another method as we have declared here
transaction withdraw it is a same the Runnable interface and this is a constructor for this
and here is the run method as you see is basically called the withdraw method of these
object account y.

Now, so, the two methods withdraw and deposit being synchronized they are basically
operated for the two operations, nowhere is the methods the main method as we see. So,
so main method this is the main method as we see the transaction is the name of the class
and the main method it is here its basically for the account class we create an object ABC

616
and then that balance is 1000 and then we call this Thread t 1 TransactionDeposit
TransactionWithdraw these are the two threads are executed in parallel t 1 and t 2 are the
two threads; that means, here we want to say imply that two executions are invoked at
the same time and then if there is no you can run this program with removing
synchronized what will happen.

And if you run this program with synchronizing what will happen you can see readily the
difference, but difference may not be always because the data race example that we have
discussed because of this things it may leads to abnormal results because if it is not there,
but if you synchronize, it always give the correct result all the time.

(Refer Slide Time: 33:08)

So, this is the idea about the synchronized and then again in the stack implementation the
same synchronize also we can used it anyway. So, that stack is basically the
implementation in a data structure that is there. So, I just want to avoid this discussion
here we will discuss this thing when we will discuss about the in our demonstration who
will have more examples and then more execution so, that we can run it.

617
(Refer Slide Time: 33:38)

And so, this is the synchronization that we can have it and using the synchronized word
that, we can control and then process the Thread execution there.

(Refer Slide Time: 33:42)

So, anyway so, this is about multithreading the concept is very vast and many more
things are to be discussed in detail anyway. So, although we have used the two modules
many more things should be discussed while we will have a quick I mean complete
demonstration on the different aspects of multithreading programming.

618
So, this is about the multithreading and after multithreading, the next thing is very
important about that how the input and output way program can be handled because Java
is for internet programming and then input and output from the many sources. So, how
Java can manage the different sources of inputs and then so, output also we will discuss
in our next discussion.

Thank you.

619
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 29
Demonstration – XI

So, today we have planned our demonstration based on the lessons that we have learned
in the last 2 modules on multithreading in Java. So, as you know we have discussed
about multithreading concepts and here basically we have discussed about how the
threads can be created and then the process communication among the different threads,
the states of different threads and finally the synchronization aspects.

(Refer Slide Time: 00:35)

So, in today’s demo we will learn everything from the practical point of view, we will
see exactly how ThreadCan be created and then those ThreadCan be executed.

And then we have already discussed that there are 2 ways of creating thread. So, using
ThreadClassAnd Runnable interface. So, we will learn about this the 2 things the 2 ways
of creating the threads and running them and there are different methods to control the
threads. So, there will be sufficient demonstrations on them. So, that we can learn about
what are different methods to control the threads and then for the inter process
communication again, there are few methods we will see exactly how this inter process

620
communicating methods can be invoked for the threads and then again the ThreadCan be
controlled.

Now finally, we will discussed about one real life example is very small example. So
banking transaction so how the transactions in a bank right for the operation of an
account holder can be managed and that is the using threads itself. So, this is basically by
the process of synchronization. So, we will discuss about this things.

So, let us have the demo on these aspects. So, first we have let us have the demo on how
we can create a thread using ThreadClass.

(Refer Slide Time: 02:15)

So, in this program as we see we see here this program if you see here we have created 3
threads namely here, we have created 3 threads as we see ThreadA and this is basically
extends Thread, this means this basically threads using the class Thread and so creating a
thread means, you have to override the run method and as we see we have overriding the
run method here and this run method is basically as we see from this code this run
method will run for 0 to 5 loops and in each loop it will print the negative number.

So, starting from minus 1, 2, 5 like and next thread. So, it is a ThreadB again it is extend
the Thread ClassAnd here also we override the run method these also loops for 0 to 5 6
times and in this loop as we see these method will print the 6, the first 6 even numbers
and similarly another thread, ThreadC it is also a extension of class Thread and then here

621
the run method which is basically a simple loop here and then loop will run from k
equals to 1 to k that mean 5 times and here it will print first 5 odd numbers.

Now so these are the 3 threads. So, our plan is to run these 3 threads simultaneously now
here is the main method and in this main method, we see how we can create the 3 3
thread objects A, B and C these are the 3 thread objects for the 3 classes like ThreadA,
ThreadB and ThreadC. Now this is the syntax as you see how we can create the 3 thread
object for the 3 Thread classes that we have defined here. Now in order to run the thread
so we have to call the method start for each thread object for example, a.start() this
means that ThreadA will run b.start() that this will run c.start() this will run.

So here, in this main method as we see so these are the 3 threads we will run, but in
addition to the main method itself is a thread. So, all together here actually 4 thread will
run. So, this is the ThreadA will run this means this thread will print the negative
numbers ThreadB when it will run it will print odd even numbers ThreadC will run when
it will print the odd numbers and here this main thread other than this executing or
invoking this threads, it will also print this statement and we are not sure the which
thread will be executed in which order because here, the scheduler will take all the
threads and depending on it is own because, here no priority has been assigned actually
all threads are in random pattern, it will be executed. Now so this is the program.

Now, we can have some idea about how this program, if it run then how it will give us
the output. So, name of the program and we have given here demonstration_111 ok. So,
this program is now compiled and then we are running this program and yeah as we see
these program, it gives the output here multithreading is over this is basically from the
main Thread and here you see ThreadC ThreadB A B B they are basically in random
order somehow ThreadC which was (Refer Time: 06:05) invoked in the main method
last, but it got executed first and then B A B in inter living manner and we see all thread
when they are executed they are printing their number in that order of course, in the way
the loop will executed.

So, this basically example gives that how the different threads will be executed and that
is the execution of the 3 threads. Now let us have another demo.

622
(Refer Slide Time: 06:35)

So, in this example we have created 3 threads using class Thread that is the extends
Thread now there is an another way of creating threads and running them using the
Runnable interface. So, this is the program which basically gives us an idea about how
the same problem, which we have implemented using Thread Class can be also
implemented using Runnable interface 112 ok.

(Refer Slide Time: 07:09)

Now so this is the example what we can see here how the Thread can be executed using
Runnable interface. Now let us see we define ThreadX the another thread which

623
implements Runnable interface. So, implements runnable; that means, we want to create
the thread using Runnable interface.

In Runnable interface there is an abstract method, which is basically run. So here,


basically implementing means we have to override the run method. So, this is the code
that basically implements the run method and this implementation is same as the
ThreadA extends Thread class, in the last example similarly ThreadY is the same version
of ThreadB and this is the implementation of run method for this ThreadX and similarly
this is the implementation of run method for ThreadZ, it basically implementing
Runnable interface.

So, as we see there are 3 threads we have created using Runnable interface. Now let us
see how we can create the. So, these are the basically class declaration for the 3 threads
and now this is a main method, this method is basically creates the 3 threads as we
defined ThreadX ThreadY and Thread Z. Now here, you see first we create a x, it is
basically the object of the class Thread X and then we create a thread of that objects. So,
this basically t1 is the thread object for the class Thread X.

So, to use it using Runnable interface method we have to have this syntax like thread t 1
that mean t1 is a Thread And we pass the Thread class that is the x object, which is
basically implementation Runnable interface actually and then so these basically, create
the thread t1 for the ThreadX likewise, these basically t2 is the thread 2 for the class
object y and thread ThreadY actually and this is the another way short cut method also
we can use.

So, t3 is the thread object new Thread and in this constructor. So, there are different
constructor as we see to create the thread, this is the one constructor where you have to
pass the object of the thread, but here we can pass the constructor directly. So, this is the
another way that the thread object can be the thread object can be created. So, these are
one way of creating (Refer Time: 09:51) actually anyway either these way or these way
you can do whatever it is there.

Now so we have created 3 thread t1, t2 and t3 and now we are in a position to run them.

624
(Refer Slide Time: 10:03)

So here again, we run t1.start(), t2.start(), t3.start() means 3 threads are now started
invoked for they are running and then this is basically the statement which is basically in
the main statement basically, the same program that we have done using Thread class,
but here only the difference is that we have done the same thing using Runnable interface
and definitely it is basically same program, but implementation is different definitely
they will give the same output. Now let us see the output of this program ok.

(Refer Slide Time: 10:39)

625
So, this ThreadA s you see X Z Y Z all this things run in an inter living manner, because
whenever the thread is executed they are basically executing parallely, but here in our
display we are our producing the output synchronizing. So, better can be that if we have
the three display unit for each display the different Thread can produce their output then
we can see that how the 3 threads are running independently rather, but here is basically
we are producing the output from the 3 threads on the same input same output screen.
So, that is why we are getting the output in the interleaved manner. So, this is the way of
creating threads, we have learn about we can create threads in 2 ways using the class
Thread and the Runnable interface.

(Refer Slide Time: 11:29)

Now, our next illustration is basically to every threads, whenever it is in execution from
the program point of view we can get have information about the threads by means of
their identity. So, the Id of a Thread can be accessed by a method called the getId, which
is defined in the class Thread in the Java.lang.methods class. Now here, let us see one
example as we see here now. So, these basically this is the name of the class that we are
going to declare is the ThreadId threadId is basically extend Thread always whenever
you have to create Thread class you have to have an extension or either Thread class or
implements Runnable interface that is the basic concept of course,.

Now here, the run method basically thread has it is own abstract run method, but
whenever you have to extend it we have to basically implement override this run method.

626
Now this run method is very simple here basically it include one print statement which
print the thread dot current thread the; that means, whichever the thread is in execution it
will basically for that Thread and then dot getId means for that thread the Id and it
basically it will give the things that which is a current thread is in execution and
corresponding to that thread, what is the Id will be displayed and print and so this is
basically, under try and catch exception to handle the exceptions if any things occurs
whenever this program is in execution.

Now here is the main method here, we can see in this main method there will be in fact, i
equals to 0 to 8; that means, 9 threads will be executed we are basically running for the
same class ThreadId, but 9 occasions. So, the 9 thread will be executed and here
although we are calling in this way, but whenever these threads are in execution they will
be executed simultaneously in parallel.

So, concurrently so these basically, it creates a thread in each loop and then that thread is
basically executes. So, this actually these way the nine loops will be created 9 threads
will be created and then each thread will be executed. So, this is the basically idea of the
program and in this program as we see the output this program will see you will display
the output whenever is thread is in execution and corresponding to their Id.

(Refer Slide Time: 14:07)

So, as we see here thread that is I1 is running thread I5 is running I4 is running now at
we can see 1 to 9. So, 9 threads are basically in execution. So, this way we can see the

627
threads are executing in parallel, but it is not sure if we run this program again not
necessarily in the same output will be let us run the same program again as we see
possibly it will give you the different ordering of the execution as we see here in this
case; obviously, in the but here in the last 3 we can see the different ordering. So,
ordering is in fact, provably stick or it is not predictable rather unpredictable ordering
actually anyway. So, this is the idea about as we see is a simple example where the, Id of
the Thread can be can be access whenever a thread is in execution.

Now, our next execution next program basically the same, but using Runnable interface.

(Refer Slide Time: 15:07)

As we have seen in the last program, we have created the Thread class, you have we
have extended the Thread ClassAgain the same program as we see here using the
Runnable interface same code, but only the implement this is a different and here again
as usual. So, this is also different because in order to execute or in order to create a
thread which has been implemented by Runnable interface. So, this is basically the
structure of syntax that we have to follow and then we have to just as in the Thread
class .we have to just invoke the start method for each thread to run it.

So, these will create one object each time the loop will roll and then it basically start
again the same output similar output as in the previous this illustration we will be able to
see it. So, here is basically we are running the program here threaded. So, we can see the
similar kind of output as we can see you can see the bigger screen so, that we can see it

628
clearly? Yes ok. So, this is the basically output as we see. So, here basically in the
different order as we see this is basically same program same logic, but that logic is
implemented using implement using Runnable interface ok. Now our next illustration to
express, the different states of a Thread and as we know the different control by which
the state of a Thread can be managed.

(Refer Slide Time: 16:51)

For example, there is yield method, stop method, suspend method, resume method, sleep
method, whatever it is there.

Now in this example, we will just see exactly how the sleep method will work for us and
then stop method also we will see yield stop and then sleep these are the 3 methods we
will see how this methods can be invoked for a for a current thread under execution.
Now here, is the code as we see we create ClassA extends Thread and here we again
override the run method it is the simple print statement that from which state these thread
in execution. So, it keeps that start from ThreadA and this is basically the loop here we
see for i equals to 1 i less than 5. So, 1 to 5 this loop will roll and if i equals to 1, the
yield method it will be there. So, then system dot out dot print from ThreadA i plus 1 it
basically, print the value of i.

So, yield method is basically tell that this thread is in execution. Now here again ClassB
extends Thread s you see the similar structure of the program code here in this run
method as well as, but here j equals to 1 to j less than 5, this run method also will loop

629
will roll for 5 times and here whenever j equals to 2 it basically stop; that means, these
thread will be after the running up to 1 1 and 2 from 2 for the third loop one was it will
basically stop and then stop for sometimes until it will stop means it is totally stop this
means, these thread will no more execute; that means, these loop will although for roll
for 5 times, but it will ultimately work for you only for j equals to 1 only.

Now, here again ClassC this is another thread we have created here similar run method k
equals to 1 to 5 and here we see when k equals to 3 we call the sleep and this sleep is 30
30 1000 millisecond 1000 millisecond means one second like. So, this sleep this thread
will sleep for 1 second; that means, it will roll k equals to 1 k equals to 2, whenever k
equals to 3 for sleep 1 second and then again it will roll for 4 and 5.

(Refer Slide Time: 19:29)

So, these are the 3 Thread classes we have created having their own mechanism and now
we in the main method, we can create the 3 objects of this 3 Thread classes t 1, t 2, t 3
and then we just start their execution here and then finally, one the thread is finished it
basically print that end of the thread execution, but as it is here in this main method
actually in parallel 4 threads will run concurrently. So, this is the idea about 3 threads
here and here is the again output we can see how this program run fine. So, these are
warning we can ignore.

So, as we see the output seen here, here, ok. So, end of execution somehow it is the last
statement, but it is the one main thread somehow it is executed first and then ThreadC,

630
ThreadB, ThreadB in a random fashion as we see the different threads executed and also
we can see the second thread, ThreadB actually as it is run it is basically stop for thread 1
right for the loop and for the 2 4 6, it is basically running. So, this is the way it is
basically it works for us

Now, let us go to the program here the program which we are discussing. So, what
essentially the multithreading basically it is there. So, as we see each thread has its own
code. Now again for example, say suppose we want to run 2 methods, one method will
be for sorting some array of elements and another method for searching some elements
in a array. So, what we can do is that, we can create a thread for the sorting method
implementation we can create another thread for implementation of searching method.
So, whatever the logic there is to sort some array or elements we can write the code
under the run similarly, whatever the code that is required to search an item in an array
we can put into the run method.

So, this is the way that we can run our own what is called the algorithm the method and
that those algorithm can be executed in parallel. So, parallel execution means that they
will share the system may be in a time sharing basis or in a multi programming basis that
is the part of the operating system. So, operating system; that means, here Java run time
manager will manage the execution of all the threads in parallel. So, this way actually if
we run says sorting and searching one by one. So, this may takes a 5 plus 5 10 seconds.

(Refer Slide Time: 22:07)

631
But, if you run in parallel it may take 5 seconds both the program will run, but it will the
maximally utilize the CPU resources other resources, those are required in your program
execution can be maximally utilized. So, this is the purpose of the thesis purpose of the
threads execution.

Now, let us have the another example as we have learned the method yield stop and then
sleep likewise there is some other method also like suspend and resume method. So, this
examples basically explain us how the suspend and resume method work for us. So,
suspend method means if you write if you can wait make a c thread wait by calling some
method right then suspend method is basically ok. Any one method is running and you
can call the suspend method that mean this thread will be not permanently stop, it will be
temporarily withheld and the same method can be again revoked if we call the resume
method.

So here is a program, which basically explain that we suspend one method Thread and
then the same Thread can be resumed from the other thread exactly. So, here is the code.
Now here, you can say Thread1, we create 1 Thread and this is a run method is basically
simple it is state that print a print statement that this thread starts running and then here
the sleep method we call here sleep for 10 seconds and then the system dot out print l n
the first thread finish running and then this is the Thread2 and here again the similar kind
of code here is basically thread we call a method suspend and then the 2 threads are here.
So, the threads this whenever the 2 threads are in execution, one thread will sleep for 10
milliseconds another thread will go for suspending.

Now here in the main method, as we see we run the 2 threads first and second namely
here and then start it and then execution. So now, let us have the code for that quickly,
yeah as we just output is little bit bigger so that we can see output (Refer Time: 24:25)
fine.

632
(Refer Slide Time: 24:27)

Now here again, we see the output as we see these are the thread was in executions. So,
sleep and that is why after ten second this sleep this Thread actually revoked and then it
produces the output like this one.

So, you can see that how the suspend and then the sleep the similarly resume method
also we can call the resume method in the main method after sometime the resume
method can be called so that it can resumed it now. So, this is the different method to
control the thread. So, is basically mechanism the way that different Thread can be
controlled. Now here, we have discussed about a priority can be assigned among the
threads.

633
(Refer Slide Time: 25:09)

Suppose, while in the execution we can set some priority to the threads as we have
discussed about there are 3 priority min priority, max priority and normal priority.

Now, the thread we can assign priority values to all these threads here now, this program
will explain how we can create 3 threads and among these 3 threads we can assign the
priority. So, ClassA is a 1 thread, this thread has a simple loop i equals to 1 to 5 and then
this is the simple loop execution it will print the 3 5 numbers actually 1 to 5.

Similarly ClassB also similar it will print same numbers 1 to 5 and class C also same. So,
both the threads are basically similar form of executions. Now here as we see in the main
method as we see in the main method, let us look at the main method we created 3
threads t1, t 2, t 2 we create 3 threads t1, t2 and t3 here for the class ThreadA ThreadB
and ThreadC and then here the method set priority which is defined in the class Thread
and then we plus argument as Thread.MAX_PRIORITY, this value is already defined in
the ThreadClass.

So here, basically this basically t 3 has been assigned the maximum priority and as we
see t1 has been assigned the lowest priority and here t 2 the set priority get priority,
whatever the priority of the Thread at present it is basically plus 1. So, it is a random
priority then 3 threads are executed invoked and then finally, the main thread it is there

634
Now, we will see. So, the order actually whatever it is there or you see the max priority
having the thread t3, it will be executed first. So, scheduler will know from this
information that which threads needs to be executed first. As we see here because, t3
because t3 the ThreadC namely having the highest priority and as we see here basically it
basically invoke first then B and then A and B they are basically random priority based
on and they have been executed. So this way, we can assign the priority to a thread so
that the execution of Thread can be further controlled.

(Refer Slide Time: 27:53)

Now so here is another problem, this is very interesting problem multithreading works
good usually first, but if you are not careful then you may not get the right result, now in
this regard there is a problem. So, for the concurrent program execution is concern it is
called the race problem, the data race problem. Now if you see the code here, now this
code is very simple as we see it declare one integer as a static x and the run method is
basically overriding the class method here and here we see x= x +1 , x =x-1.

Now after the end of the loop if we come here. So, what will be the desired output?
Output will be 0 if x is initialized as 0 is not it, but here we see whenever we run this
program it may not produce the result 0 always this is because, it is an intermittent way
this statement will be executed by the scheduler in a different way and that is why it is
not atomic. So, if rather non atomic the execution. So, whenever we run this main

635
method I mean run this loop for say here 1000 times and each time not necessarily 0
output will be produce, it can produce non 0 output as well as.

Now, let us see the execution of this program, but in the different instances if we run the
different program, it will produce the different result.

(Refer Slide Time: 29:37)

So, if basically 1000 output has been printed on the screen as we see all 0 0, but here
one is there and if we go little bit also top also as we going here may be that sometimes it
is there. So, these are the, this is not the right output actually we can say the erroneous
output and it may produce 0 time most of the time, but sometimes it can produce the
value 1 because of the data race.

636
(Refer Slide Time: 30:11)

Now, data race because this is the program those are the thread under execution, they are
not synchronization under synchronization means whenever one thread is in execution
then other threads should not be executed simultaneously having accessing the same
variable here, we have made the static variable basically the different thread takes the
same value on their own execution that is why the data race is coming. Now this is a one
example which can better explain in our real life situation the data race condition.

Now this program, we let us have the discussion on this program then I will explain it is
execution and then the in inherent what is called the point in it. As we see here we first
create a Account, this account has 3 fields balance and account number (accountNo)
with 2 fields are there and one method displayBalance. So, a very simple class
declaration as we declared here. In addition to this these method has one method is called
deposit. So, it basically deposit certain amount here into this account.

So; that means, whenever this method will call the balance whatever the current balance
will be increased by the value of amount. So, this is the code it is there and finally, it will
print the display balance which will declared here. Similarly there is another method that
we have declare here withdraw and it basically once amount will be requested for
withdraw will be deducted from the balance and after the withdraw is over it will
basically display the balance information.

637
So, these basically a simple one class method this is just regarding an account holder
information; that means, the account holder the name or name is not there account
number is here balance is there and the balance information balance status and if the
account holder wants to do a deposit. So, he will just call this method or he if we want to
withdraw something, you will call this method and this method will be executed there.

Now, here is a question point is that if suppose two customers having the same account
number joint account number may be they want to issue the two method deposit
withdraw or deposit again or withdraw or whatever it is there from the two different
terminals then they will be executed from the server point of view. So, it is basically
executed as a thread. Now again, just like a data race if it is not properly synchronized
then these may leads to the erroneous result say balance is 1000 deposit 500 and
withdraw is 300 the result may be sometimes 1300 or result may be sometime 700 so, is
not total correct.

Now here is basically the remedy, remedy is that if we want to make the two method
synchronized by force then we can create the synchronized keyword. So, once the
synchronized keyword is placed then this deposit and the withdraw will be control in a
synchronization that mean only one operation either deposit or withdraw will be
executed not the two operations can be executed in concurrent in parallely.

Now having these are the class information. Now here is basically two methods, we
declare as a transaction deposit basically in order to access the account having the
transaction here. So, integer amount this is the account that mean which account the user
wants to access and this is basically the code for this one and finally, these transaction
deposit will be executed in parallel. So thread so these basically creating a thread for
accessing this deposit method.

(Refer Slide Time: 34:05)

638
Now, similarly now, similarly there is a transaction withdraw in the same structure as we
see here it basically create a thread in this case and then this thread will be again can run
concurrently with the transaction deposit. So, these are the two threads in this program.
So now, after the two threads are there, this is the main thread this main thread is
basically execute the 2 threads that we have created here as we see we have created an
account information that mean an account is created this is the account say name of the
account B A B balance is 1000 account number is this one and here actually you see t 1
and t 2 the 2 threads are created.

In this case from the same program, but whenever the distributed (Refer Time: 34:50) is
there these 2 Thread can be executed from the different client and it can pass through the
server you can understand that this is basically the request to the server from the 2 client
that mean execution of 2 thread t 1 and t 2.

Now if these 2 threads are to be executed by the server in concurrent then definitely data
race may occur, but here these Thread are created or called for with depositing 500 and
withdrawing 9 900 and then what will happen it will give always the correct result. So, in
this case 1000 is the balance and after we depositing 500. So, total 1500 then after
withdrawing 900, it basically 600. So, this is the output as we see as we see here. So, 500
is deposited this one 900 withdrawn 600. So, this is the correct result.

Now, I can run the same program, but removing the synchronizations it will run again
just quickly we just, but in some situation may not always it can give erroneous result.

639
(Refer Slide Time: 35:55)

Now here, we can see yeah so, this is the right output as we see here just bigger. Now
see in the first execution the output was correct, but whereas, these execution the output
was not correct in that sense because, they are not executed in synchronization if the
amount is different you can get the another result also like this one anyway. So, these
basically shows that how the synchronization can help us to synchronize the program ok.

So, we have learned all this topics here and go to the yes fine, but the thing is that this is
just only tip of the iceberg, we said say there are many more things that you can consider
while you have to practice it more programs are there from the website link, which you
have mentioned very beginning, you can follow many more programs, you can access
from there and you can run those things there, if you have any doubt any query you are
feel free to ask us.

Thank you very much.

640
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 30
I – O Stream – I

We have learned about how the input-output is possible in Java program. So, the input-
output that we have learned so, far they are related to standard input and then standard
output. Standard input namely the keyboard and standard output is the display screen.

Now, Java provides many more other than this input-output related to only standard
input and output devices. So, today’s module in today’s module we will discuss about
what are the different input-output mechanism is possible in Java. So, this is particularly
called the input-output streams in Java. Now, again the new term that you are just
listening right now is called the stream.

(Refer Slide Time: 01:15)

So, the idea here is that Java treats any flow of data as a stream. Now, Java streams are
classified into two major categories. They are called the input stream and then output
stream. Now, in order to provide versatility in a programming environment, Java
developer provided say very good package deal with input-output stream. This package
is called java.io. So, java.io can handle many what is called the types of devices for the
source for input as well as many destination devices for the output.

641
For example, the keyboard, mouse, memory disk, network are the input from where data
can be collected. Similarly, data can be streamed into other devices like display unit,
printer, memory disk, network like this one. So, there are so many devices that are
possible by which the input-output stream can be controlled. As I told you Java provides
the java.io packages to dealing with this input-output mechanism.

(Refer Slide Time: 02:35)

Now, basically, the idea about the input stream and output stream is that, that your
program can have any data streaming from any other sources. So, it is called the input
stream mechanism. On the other hand from your program, you can pump data to some
other source, then this is called the output stream which we have discussed in the figure
in these slides. So, this is a basic concept of the input-output stream, that means from the
program the data will be pushed to some that are the output stream or the program will
read something from the input source.

642
(Refer Slide Time: 03:21)

Now, the java.io package is meant for this managing input-output stream and it is an
exhaustive package. So now, we will discuss about the basics of what is called the
structure in the java.io packages. Now, all the classes that are there in Java IO packages
java.io rather I should say java.io, all classes can be categorized into two bar categories.
They are called byte stream classes and then character stream classes. This category is
basically divided in case of byte stream classes the data input-output mechanism is
control in the form of a byte whereas, in the case of character stream classes data input-
output mechanism is controlled by means of a stream of characters.

(Refer Slide Time: 04:21)

643
Now, let us have a quick look at the total different hierarchy of the different packages
different classes which are there in this package. We can say that this is the Java stream
classes. Now, as I told you it can be divided into two broad categories: the byte stream
classes and then character stream classes. In the case of byte stream classes there again
two categories called the input stream classes and then output stream classes. And so, for
the character stream classes is concerned again there are two categories: reader class and
then writer class.

So, these are the so, many classes are there and essentially all these classes are to deal
with the different sources as an input as well as output like memory, file, pipe. Now, a
pipe is basically related to the network channel. Now, let us first discuss each one class
each class individually one by one. So, first let us have a discussion on Java input stream
classes that is there in java.io package. Now, as I told you input stream classes are
basically mean for in reading something from memory or from a file or from a pipe and
as it belongs the byte stream class means, it will read in the form of a byte.

(Refer Slide Time: 05:41)

So, here is basically the total classes those are there in input stream classes as we see a
large number of classes are there. And, all this classes can be mentioned like the
FileInputStream, then PipeInputStream, FilterInputStream, ByteArrayInputStream,
SequenceInputStream, then StringBufferInputStream and ObjectInputStream. Now, here
basically so, many classes belong to input stream class because they are basically to deal

644
the different input in a different manner. For example, byte array input stream class is
basically how to read data from an array which is stored in memory, it is just an example.

There are so, many classes like and then example again filter input stream class if we
consider there are again many different classes belong to this class hierarchy it is. For
example, DataInputStream, data output, data input stream, BufferedInputStream,
PushbackInputStream etcetera. So, we see that there is a lot of classes and I have just
mentioned only one type it is called the filter input stream. Like likewise byte input
stream there again are the subclasses are there. So, our objective here will be to learn it is
not possible to learn all classes one by one, but at least some classes we can learn which
are most frequently used.

(Refer Slide Time: 07:11)

Now so, input stream classes as I already mentioned that it belongs to the byte stream
classes. This means it is used to read 8-bit bytes and supports a number of input related
methods. And, few methods which I have mentioned here which are very common in any
programming; like say how we can read a byte from an input source, how we can close
an input source, how we can make a position of streaming in an input source. And, it is
skipping ahead into some if we want to read the input one source, not in a sequential
manner rather in a random manner. And, then we can also find a total number of bytes in
stream etcetera. There are many such methods that includes in the input stream classes to
process it.

645
(Refer Slide Time: 08:03)

And, the methods basically belongs to all classes are overridden method. For example,
the read method that can be used for any say for byte array input stream, we can use the
read array method for that. It is basically the overridden method that, those are there in
each class. So, in general, a read method as we see that read a byte from the input stream.
Now, this is an overridden method read byte b; that means, read an array of bytes into b.
So, it will read and store into a temporary location that is there in the program. And, read
also has another overridden method like byte b int n int m.

So, it is basically reading m bytes starting from n and put into the array say b. Available
is another method it says that whether the input stream currently available or not, skip is
basically for random accessing. So, it is skipping n means, it will skip from the current
location to n bytes ahead and then reset also, reset the reading of location of in the input
stream. Reset means it will start from the beginning and then close basically every
stream has to be as it is open; so, as needs to be closed also. So, these are some standard
methods we will learn all these methods when we will have some more detail
explanations regarding a particular stream class.

Now, here again another example data inputs term is a very popular one stream class and
as we see they are also many methods that can be used. So, basically, the data input
stream belongs to this byte; byte stream classes and it basically has many what is called

646
the utility. So, it can read as a sort integer, it can read as a floating-point number, it can
read as a read normal integer, it can read at a line ok.

It can read long integer, it can read a character, it can read a Boolean, it can read a read
some data in a UTF format; there are many other formats are there. So, so basically it
basically tells that a data input stream, if we have an in, have an input then, we can read
the data from that input source in a variety of ways. That is why the different methods
have been planned and according to your requirement you can fix that which method you
should invoke in order to read a data.

(Refer Slide Time: 10:35)

And, this is the syntax for example, whenever you declare a read is basically read an
integer return an integer value and like this. So, read byte b we have already discussed
about; so, it read as a byte and store into then temporary array b and like this one. And
so, these are the few methods which will learn while we will have a more detail
discussion on it. And so, the method is for example long skip void long skip are a
parameter is a long integer. And, then it will skip to some location depending on a
parameter values first, mark int is basically, it will mark a particular position in a stream.

And, then reset as I told you it is basically reset the file position, I mean stream position
and Boolean markSupported whether any location stream can be supported or not, it will
return true or false like. So, these are the many methods that are required to control our
input mechanism, those are already defined in the in-stream input stream class. Likewise,

647
there is a class called the Java output stream classes. If the input stream is to read
something from the input source the output stream is just opposite. It will push the data
into some output destination.

Now, likewise the input stream classes it also belongs to the byte stream classes. These
means that it will write something in the form of a byte and this class has again can
output data into memory. It can output data into a file; it can output data into a network
channel. So, it is same as the input stream, but only the thing is that input is taking and
output is pushing.

(Refer Slide Time: 12:25)

So, output stream classes are therefore, used to write 8-bit bytes and like input stream
classes, it also supports a number of methods. For example, writing a byte into an output
source, output destination, closing the stream, flushing stream and etcetera.

648
(Refer Slide Time: 12:47)

Now, like the input stream also it has many methods in it. Now, one particular class
belong to this Java OutputStream is called file and then the FilePipeOutputStream,
BufferOutputStream, FilterOutputStream. FilterOutputStream, if we consider there again
varieties DataOutputStream, PushbackOutputStream and like this one. So, it is like this
from different sources mean into a different source, how we can put data into that; so,
that is why it is there. For example, if we consider saying the byte array output stream is
basically telling that how we can put some data into an array in memory. It is an example
like this one.

(Refer Slide Time: 13:33)

649
So, it is again there are many methods like write method; it basically gives an idea about
how we can write a bite into a stream output stream write byte b. It basically say that an
array of bytes how it can write into an output source, write byte b int n and int m. So, it
basically says that how m bytes from the array b starting from n bytes can be pushed into
an output destination and then close and flush is basically closing an output stream. And,
flush is basically output stream is basically clearing cleaning, it is basically called output
stream usually temporarily buffer. And, then whenever you read whenever you push
something before placing it to an output we need to clean it.

If you do not clean it the previous stream that can be used it can be stored in the their
buffer, that is why it is flushed. And, like the data input stream, there is one class called
the data output stream. It is like the data input stream as it was it can write data into
many forms starting beginning with the bytes actually. So, is writeShort means write a
sorted integer, write Double it basically writes a floating-point number, writeInt,
writeLine.

It is basically written a stream consisting of numbers or characters say together, it is


called the writeLine. Then writeLong is basically writing a long integer, write character
writing a character into the output stream, writeFloat and then WriteBoolean and
writeUTF. So, writing data into UTF format. So, these are the different methods those
are there in the data output stream.

(Refer Slide Time: 15:33)

650
Now, here is basically syntax that writes is basically return does not anything, this
method it takes a byte b or just simply the byte that needs to be written into the output
stream. It is an overridden method, there are three different overridden method as we see
we which we have mentioned here three overridden method here. And, this is a close
method and this is the syntax of the method void close, void flush that means they do not
return anything just do the work for the output stream.

Now so, these are the byte stream classes we said they are reading as a byte form. Now,
another way of input-output streaming it is called characters stream classes. Now,
likewise there are many different methods that are there and broadly all the character
stream classes can be divided into reader class and writer class. So, the reader class just
like an input stream classes will read some data in the form of a character; from either
memory location, from a file or from a network channel. And, write class is basically the
same as the data output streaming, it basically writes some data into memory or in a file
or it can pass the data into a network channel.

(Refer Slide Time: 16:59)

Now, so these are the two classes and they are mostly in the same manner as this one.
The difference is that the byte classes is basically deal the data in the form of bytes
whereas, the character stream classes deal the data in the form of characters. Now so,
reader stream class as I mentioned that it basically this class is to read characters from
some input sources. And, it is in many ways very similar to InputStream classes. On the

651
other hand write stream classes writer stream classes basically, write characters into the
output destination targets. It is also in many ways very similar to the OutputStream
classes.

(Refer Slide Time: 17:41)

Now, here is the reader stream classes. So, reading input from some input source in the
form of a character. And, as we see in this figure it can read like a BufferReader, it can
read like a character array reader, it can read like a File Reader. I am reading from a file,
it can read just a StringReader read as a string of characters; it can read as a PipeReader,
FilterReader, PushbackReader. So, there are different o a the reading is possible using
the reader stream classes it is mentioned here.

652
(Refer Slide Time: 18:23)

Now, here is the one quick summary of the different methods we have mentioned here
and it is just for a piece of information. And, the details and everything is really very
difficult to discuss. As you see here that we have mentioned that, if we want to
accomplish a particular task then which classes that we can consider.

Whether it is basically character stream classes or byte stream classes, as we see say
suppose we can perform an input operation. If we want to do so, it can be done using
both character stream class as well as the byte stream class. As an example as we see
here performing input operation can be done using character read class Reader classes
which are there in character stream classes or InputStream classes that are there in byte
stream classes.

Similarly, if we want to perform a task say buffering input, buffering an input means
storing some data into an into a buffer every what is called the input source, in general,
has their own buffer. For example, a keyboard has its own buffer. So, whenever you are
typing from our keyboard it is initially going to the keyboard buffer and from that
keyboard buffer any program can read, either read as a character or it can read as a bytes.
So, if we want to read as a character, then the class that you should consider
BufferedReader and if we want to read as a byte; so, BufferedInputStream.

This means that if we want to read a buffer then and by means of say BufferedReader
then we have to create an object of the class BufferedReader and then that object has its

653
method. For example, read method or the different methods as we have mentioned and
you can invoke the method for that object to complete the particular task. So, it is like
this as a particular example, if we want to write writing to a file. So, there is an again
both character stream classes as well as write byte stream classes the method is there.

As we see writing to a file has the FileWriter, if we want to use the character stream
classes and then FileOutputStream if we want to use the byte stream classes like this one.
So, these basically give an idea about if we want to perform, not all I have mentioned
only a few tasks that are very important. These are the different task if we want to
perform then if we want to use a character stream class, then we have to use this one.
And, if we want to use a byte stream class then we have to use this one. So, these are the
just for the information that what are the different methods are there.

But, all these things are not possible to learn in just one module. So, we will follow step
by step methods using each class and then each task rather than, how it can be done. So,
this is the better way so, that we can learn about the input-output stream classes into the
program ok. So, this is basically the topics for today. And, in the our next module we
will discuss about how step by step method to handle the different way of input-output
mechanism using in I O stream concept in Java programming.

Thank you very much.

654
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 31
I – O Stream – II

We have learned about that I-O stream classes and java.io package. Now let us see how
the different classes in these packages can be utilize to meant to process the input output
mechanism in java program. So, basically this module includes the concept of the
application of I-O stream classes into the program.

(Refer Slide Time: 00:45)

Now, let us first start with a very simple one which you have already familiar to. So,
suppose the calculator program to calculate something, which will read some value from
the input say may be standard input. So, the program we have already familiar to this
kind of program it is there as we see. We have given the name of the classes input
InterestCalculator as we see here this is the name of the class and this is the method and
in this method as this actually purpose of this program is to read something from a
keyboard. Now keyboard it is identified by a System dot in. So, here is basically you see
System.in so it is a System dot in.

655
Now first you see what how we can connect a connect a link from your program to this
standard input namely the keyboard in this case. Now to do this things, we have to create
an object of the class DataInputStream. So, we create the object and in let in with the
name of the object and this is the syntax for creating an object of the class
DataInputStream as you see DataInputStream = new DataInputStream (System.in).

So, this basically create a connection from your program to the keyboard. Keyboard here
being a input stream source. Now once you create this objects, then we can read the data
from this. Now to read it here we see, I use in dot readLine. So, in.readLine the readLine
is a method which is define their in java.io package for the DataInputStream classes.
This basically read whatever the number of entity.

For example, if we type say 2, 4, 5. So, read line is basically read 3, 4, 5 as a whole
together if I write say 2, 4, 2 4 5.6 7. So, it will read as a whole thing. If we enter some
string, it will read whole the string as a whole together so; that means, the idea about the
readLine. Now for the object in, we call the method readLine which basically read the
entire thing that is presently available in the buffer and read it. And then so here basically
we see we can read here for example, this one basically reading the principal amount in
order to calculate the interest here for which we need the input from the keyboard and
this will be stored in a principal amount, rate of interest, number of years.

So, three readings are here involved and in the first reading as we see, we can read for
the principal amount and then in the second reading, we can read for the rate of interest
and we can read here for the number of years. Now after reading, we can see we read all
this things in the form of a byte. So, this byte is store here in the form of a this buffer
tempString and it is basically this byte is store as a I mean considered as a string actually
and then this method you see this is interest important to note that this method basically
convert the string because you rate as a string and this string needs to be converted into
the desire number. So, it is basically float.

So, this method is basically read a string from the by data DataInputStream and convert
into a float value. So, this is a value of method which is define in java dot lang package
for the class float will convert the stream into the double or float value. Likewise this is
also as we see, it change from the stream and reading and change into the float value.

656
Similarly, here this basically reading the number of years as an integer and we see we
call this method which is define in java dot lang package to convert into the integer. So,
Integer dot parseInt (tempString) like. We are already familiar to in several our discuss
problem program we have use this kind of concept here anyway. So, this basically shows
an idea about how the DataInputStream class is basically used particularly here in this
particular example to reach something from the keyboard.

(Refer Slide Time: 05:51)

Now so, this is just an example and one more important example that is dealing with
files. So, how we can read some data from the file? How we can write into file? What are
the different way the file can be read. For example, using byte stream classes or how a
file can be handle using characteristic classes etcetera. So, our next few slide includes
this kind of definition and mechanism rather discussion. So, this file handling right.

So, as I already mention that a java provides the package call the java.io package which
includes number of class declaration and the methods in its class and one important
methods one important class out of the so many classes is called the File class. So, it is
basically called File IO stream more precisely. So, there are 4 major impact classes
belongs to file IO stream is are there.

For example, the class File so, it is a general file and then class FileInputStream, this is
regarding how we can read from a file and then FileOutputStream - how we can write

657
something into a file and then another is that RandomAccessFile. So, all the File,
FileInputStream, FileOutputStream their sequential that mean reading a one by one
where as RandomAccessFile allows one to read and from any random position. So, these
are the four different classes rather we can say four different mechanisms to deal with the
input output stream related to the file.

(Refer Slide Time: 07:31)

Now, let us see what we can do. Now so, for the file is concerned first task is that how
we can open a file object; that means, file is basically in a object oriented concept
everything is an object. So, file is an object. how we can create a file object? Now this is
basically as I told you there is a class called File. So, this basically this declaration; if
you declare, then myFile is an object of the file and then it so my file can be open using
this statement new File fileName. Here basically every file that is there in your memory
or in your system, they are basically have a unique name. So, you have to pass the
fileName.

So, if you this is basically constructor. So, if we passed a fileName and then we can
create a file object. So, creating this file object means that from your program, you
connect one connection to that fileName file. So, this is a one way and these the first
constructor that you can use it. There is another constructor file that also you can
mention the pathName and then fileName.

658
Now, the difference between this constructor and this constructor is that, it assume that
your file is belongs to the same directory from where your working that is from your
working directory and the file is store in the same working directory whereas, if we want
to do access a file which is not currently in your working directory that you can specify
pathName and filename.

So, these the second constructor and this is also similar; third way very similar to this
one here basically in the same working directory, but in the different directory. So, you
can specify which is the directory under your working directory and what is the file
name. So, these are the three constructor by which we can create a file object. In any way
there are actually the one main thing that is there file names should be mentioned
uniquely, if do not mention the right fileName, but you try to open it then it will written
an error.

So, error is basically handle that way. So, this is the try catch block can be there. So, it
can to check the exception if it is occur and then it is. So, sometimes that file is existing,
but the file is damaged or that file is existing, but you do not have any permission to read
or write. So, in that case also it will throw an exception and then exception can be handle
accordingly to make the program robust.

(Refer Slide Time: 10:21)

659
So, this is the different way the file objects can be created and once the file object is
created, then we will be able to have the different information through this file object.
For example, there are many methods which are related to this file class say getName- it
basically written the full name of the file that you have currently connected to, the
getPath - it will say the what is the path, gateAbsolutePath- it is basically from any
directory it will find and then path will be there, getParent-what is the directory above
this the file where it is present and then whether renameTo- if want to rewrite the file
into a some other name also it is possible using this file object. So, they are the those are
the many utility methods we can say available related to the file.

(Refer Slide Time: 11:07)

And there are many other things also you can test a file that ok. There is some methods
like whether with the file exists or not, you can just do this using the exists method
canWrite; that means, whether the file is writable, canRead whether it permission is there
whether it is a file or it is something then say other form, is a directory or is a absolute;
that means, it is a standard file or not. So, those are the things that you can do using this
file object.

660
(Refer Slide Time: 11:43)

Now so, regarding this file information few more things also we can have just
lastModified; that means, it will tell tell you the date and time when the file has been
correct I mean use last time and it will also has the method length. So, that it will written
the length of the file. If you want to delete a file that also you can do using delete method
and there are some directory till it is; that means, using a file we can create a directory
and then in the directory the file can be replace there and make directories more than one
directory also can be created and list of files that is store in a particular directory also can
be accessed using method list method it is there.

So, there are many utilities methods related to file which basically helps the program are
to handle the files in a in their own ways in the different ways that they want.

661
(Refer Slide Time: 12:41)

Now, let us have a simple example about we have learned about the different method
those are there in file and some methods related to the checking status of a file; whether
file exists, file available, what is the name of the file, what is the path and everything like
like. So, this example will help you to understand the idea about status of the file.

Now, let us have a quick look about this program as we see this is the class that we have
been given and we import these the java.io.File because we want to have the methods
those are there. Now as you see here so this is the main method and; obviously, throw
and try catch blocks should be included here in order to make the program exception;
handle the exception more reliable rather. So, here we see first what we do we create an
object call fileToCheck. This is the name of the object of type of class File.

So, this is the object that we want to do. Now in this program we assume that user will
send the name of zero or more files for which you wants to have the information about
those files. Now here if user does not give any file name whenever he runs program, then
is basically args length equal to 0. In that case it will say that java FileTest, this is the
name of the program and file name you should give at least one or more file names there.

Now, suppose if you if user gives at least one or more one or more file name, then it will
basically enter into this loop. Then for each file each input into the common line i = 0; i<
args dot length, it basically create the method say the file to check newFile (args dot

662
length); that means, it crate an connection from the program to the file which is basically
in the input. Now so, for this file will just find this method getPaths and getInfo these are
the two methods which is basically under this method we define this two method here.

Now so, let us see what is the getPaths method and getInfo user define method. Now
here is the idea about here is the getPath method.

(Refer Slide Time: 15:13)

As we see so, getPath method which is define under this class. These the FileTest class
we can say under this method, this is the getPath. Now if you see getPath method f dot
getName. So, this is basically will pass this function here basing a fileToCheck like and
then f.getName, getName is a built in method which is defining in the class file.

Similarly, getPath the method will written about the file object, the path and getParent
written the parent of the file directories of this one and then it will written it. So, it will
print after getting about the file object path name and everything it will written, it will
displayed on the input screen and similarly the getInfo is also user defined one method
and it basically has that f dot canRead; that means, readable or writable read write
permission it is there or what are the date or time that it has been modified, what is the
length of the file like this one. So, these are the different way the status of a file can be
learned using the file object and the different methods belongs to this class File.

663
(Refer Slide Time: 16:37)

Now so, we learn about how to open a file object. Now let us have an idea about how
some contents which is already there in a file can be read from this file to the program.
So, it is basically reading a file. Now we have small program to illustrate this concepts.
Now let us check this program here. We define one class, this basically to check that
how we can read a file. The name of the program here is file input InputStreamTest.

Now, in this program as you see the, this is the declaration of main method and here
again you see we create FileInputSteam. So, FileInputSteam fin as you know this
FileInputSteam is basically belongs to the byte Stream classes. So, it will read as a byte
form like. Now here the method that is already define in the files input stream classes
call the available. So, it basically if we call this method available for this object
FileInputSteam object, then it will written what is the total bytes that is there in the file.
So, it basically written the number of bytes and it will print the total bytes is this one.

Now, here is the suppose how we can read first one fourth portion of the file. So, it is
basically using this for loop for (i = 0; i<size/4; it will read fin. fin read basically the
read method that is there in the FileInputSteam class and then it read the byte and then it
basically convert this byte into characters. So, is basically read the byte may the ASCII
value and then convert in the character that character will be display on the screen.

664
So, whatever the contain of the file, it will be there and then first one-fourth position of
the byte will be read and it will display on the screen. The same program can be
extended to read part by part reading. Here is the next part of the program with basically
tell you how the other portion of the file can be read.

(Refer Slide Time: 18:53)

Now, continuing this discussion you see this basically remaining bytes; that means, it
basically; so after reading one fourth byte it will tell that, how many bytes yet to read it.
So, it basically give the print statement this is the file that is still remaining and then for
the remaining byte again we can write here the different way just explaining that new
byte size 4.

So, this basically my plan is to read the next one-fourth part of the byte from the current
location and those byte will be store into this array temporary buffer we can say. So, we
declare a byte array of byte array namely the b here of size by 4. So, it will be declare so,
that will we can store it. Now here read b the another way the method can be called. It
basically read the buffer I mean byte input stream file here and store the result into the b
array and if (fin dot read not equal b dot length); that means, it is not the capsized, then
defiantly it is an file error and if it is not there. So, if there total of bytes is successful
read actually then it will basically call this part here.

665
So, we just string (b, 0, 0 ,b dot length) is basically converting the string and then we
store into the byte that we have written and store into the temp this string. So, is basically
the idea about how we can convert a bytes into a string that is basically more convenient.
So, that if the byte stream is covert into string and then we can process the string.

Now, here we can see once the whole byte array is converted the String in the last
example, we are storing that one particular byte can be converted the character, but here
the entire bytes stream can be converted in to the string and then this string can be
printed on the screen. So, this is the statement and likewise we can again still available
this one is basically after reading first one-fourth part of the file, then next-one fourth of
the part of the file then the remaining file.

Now it basically says that this file is available and here you can see there is again the
methods skip is basically skip the byte number of bytes that is there. So, is basically keep
size by 4. So, this way up to this we can cover the three-fourth part of the file into the
input stream and then file remaining for read is basically a fin available. So, it is this one.
So, this basically shows that, how sequentially we can process we can cover we can
traverse an input file.

(Refer Slide Time: 21:53)

Now so, this is about how we can read. Here we have use the byte input stream classes
one mechanism reading in the form of a byte. Now will discuss about the just opposite

666
one process call writing into a file; how a byte can be write into a file or a character or a
string can be write into a file. Now here is a small program again to illustrate the concept
of writing bytes into file. Now here is a method class that we have discussed here
namely, the write bytes. Basically writing bytes into file and this program you see this is
basically the character string which basically show that this is the args values of D args
value of E basically bytes.

So, it is basically stream of bytes we first store into an array call the cities. So, it
basically store all the information in the form of a byte it is there and then we want to
write it into a file, for this things here we see we create an object call out file of type
FileOutputStream. So, if you want to read some file, then we use FileInputStream. On
the other hand, if we want to write something into a file, we should create an object of
class FileOutputStream and this output file is basically the object that we connect your
program to a file where you want to write something. Now so, it is basically we put this
code under try catch block to make the program robust. If there in exception occurs so,
that it can be caught here and here you see we first created we just declare an object of
out file of type FileOutputStream.

Now, create an object, in order to do this things we first pass a file name where you want
to store it so, city dot txt. If it is already exists, then fine I will come to this discussion
later on. So, if the city dot txt is the file name by where the it will make an it will
establish a connection from your program to that file and this is the connection basically
objects is basically established here.

Now, here out file write is the method. If we pass this array so, this is the array of bytes
actually if pass there the entire array of bytes will rise into this files city.txt. Now here
again one important thing is that, if already there exists a file names city.txt and if we
write it, then the previous content will be over written; that means, it will erased only
then new content that you want to do write it will be stored there.

Now so, this example explain you how a large shrunk of data can be stored into a file and
then finally, the out file dot close; that means, you have to close the file it is always
customize that once you open a file you should close a file. So, here is the basically
opening a file and here is the closing file after your operation is there. So, this program
explain nicely that how we can write something into a file.

667
(Refer Slide Time: 25:13)

Now so, so we have learn about reading; reading from a file and writing into a file using
the different method data input stream and data output stream classes. So, there are many
other things way also a file can be read. Now I am to discuss the other mechanism how
the file can be read.

Now so, in the last example we have been discussed about a FileInputStream and
FileOutputStream. So, that we can read form a file or we can write it from a file here. So,
here again another example which explain how the reading in the form of a bytes from a
file is possible. So, again same thing the FileInputStream, this is the class for which an
object in file to be created and then again we just make a connection and then read
method is basically read. Now here this read method read one byte at a time.

So, this is the read method and here is basically this basically is a end of file; that means,
it will continue read until the end of file occurs. Now you read one byte store this in a
temporary b here and then this b can be converted into character and then the same can
be printed that mean it will read a file and then content will be despite on the standard
input device there is a System.out.print. And finally, once the entire file is read one byte
by one another, then it will close this is very simple way, it is most similar the file output
stream classes that we have consider there or like. So, it is the idea actually the
sequentially one byte at a time and then the inter file can be diverse or can be read.

668
(Refer Slide Time: 27:11)

Now, let us ok. So, we have been discuss so far using the byte stream classes. Now it is
necessary to discuss about again doing the same thing, but using CharacterStream class.
So, here is the one simple program which includes how a file can be read and or it can be
write in the form of a characters is very similar to previous one only the method that
whether byte or character that is all.

Now here you can see this is the method class we have declared and in method here we
can see what we have done inFile new File, this is the name of the input file from where
you want to read and these are the name of the output file where you want to write into.
So, these are two object inFile and outFiles for the input file and then the output file is
created and then here we use FileReader is basically to create I mean to read a file and
FileWriter to read write a file.

So, the two other objects are created. Those are will be responsible for reading a file and
outputFile and this basically once the connection is established. Now here this ins
basically is now object is declared here and now object is created; that means, ins is now
connect to this using this FileReader constructor giving the input file; that means, this
objects. So, the inFile input data is a input file objects output data is output file objects
and for this using ins method and outs method we make a connection between the two
objects input data output data from the program and now this is the integer character is a

669
temporary variable and here we can see ins read; that means, from the input object the
read method will read one character at a time and it is basically read until the end of file.

So, this basically end of file and then it read a character from a file and outs write that
mean we write the same character into the output file named here output dot dat. So, it
basically read one character from a input file call input.dat and then write a same
character input and output file call output dot dat. Again then once the whole the entire
file is read and write it is over, then it basically close the two objects here using the close
method for the two objects.

So, this way you can see how reading and writing is there and here we can see all those
exception handling mechanism is there. In case suppose we are not able to open the file
or not able to write the file or file is corrupted or whatever the file permission is not there
so many reasons and then and then output dot file as it there as it is a override so always
in override. So, if the contain that is not an appending; that means, what are the contents
are there it will go on adding is not like that, but it can be done also if the different way.

Now, here basically we see that if the file already exists, then it will start writing from
the very beginning. So, the previous content will be erased. So, this is the way that using
character stream class how the copying of a file is possible.

(Refer Slide Time: 30:25)

670
Again again using the same, but using byte stream classes also how the copying can be
possible. I will just tell you the mechanism for this. Here again so we can create two
stream FileInputStream and FileOutputStream the two object in file and out file for the
input streaming and for the output streaming. And here as we want to use the byte stream
class say so instead of character, we just declare a temporary variable call the byteRead.
So, where byteRead that means, where the buffer byte will be temporary read and store
there.

(Refer Slide Time: 31:09)

Now, the next is that we have to connect the file. So, here for this connect we create an
object in file new using this input file name and similarly output file name in discuss in
data and then output dot dat. Now so, this way we can connect create an connection from
the program to the input source and then output store source and then it will basically
start reading until the in file is completes.

So, it is basically byte read byte in file read out file write byteRead. So, the same will
read and write and it is basically while the end of file is there. The concept more or less
same in each cases only the mode the way we can read actually and then copy into there.
Here in this example as we see in the form of a byte and then finally, the method will be
here ok.

671
(Refer Slide Time: 32:05)

We have to have some closing mechanism that this basically closing.

(Refer Slide Time: 32:11)

Now so, we learn about reading, writing copying and then storing data into a file. Now
here again see from the program how the data can be store interactive manner rather in
one by one like. So, this example is basically explain you how the data can be post into
some file. So, here basically read write primitive it will read from file and write it
another file, but storing some data from the program generated like example.

672
So, first we create a File type object that is the name of the file where you want to store
it, this basically the name of the file and then we create a File object primitive. So, this is
the File object once the file object is created, then it basically FileOutputStream is there;
that means, connection. So, FileOutputStream class connection to this primitive means
this file. So, fos and DataOutputStream is basically another stream for the data out prim,
then this is the objectives is created; that means, here if you see this is the file and fos for
FileOutputStream and dos for the DataOutputStream.

So, through the data output, we have to connect to the file output and then it basically
connect to the file for storing some data into here. Now here again you see for the
DataOutputStream WriteInt the method is there write int; that means, it knows how to
write an integer in to this data input DataOutputStream. Similarly there is WriteDouble
method there in the DataOutputStream classes which basically it helps how to write a
floating point number in to the object and Boolean also how and then characters.

So, here we can see the four different type of data which can be store into a
DataOutputStream and then this basically store it. Once the DataOutputStream is ready,
then the same data can be post in to this FileOutputStream. Now this is the method and
the rest of the part here as we see ok.

So, we just write we just write in all this things is basically create the of these are the
value to the, this file output stream and finally, we have to close it. Now again the object
that we have created now that can be read also the opposite mechanism here; here we can
see FileInputStream and DataInputStream the same can be read from the other version
also. So, here basically we write it here and here will read the same content using
DataInputStream and FileInputStream mechanism. So, both way the things it is there.

So, this example will tell you how we can store the data from program. These are the
data from the program into some File object and then same data which is their how we
can read it here, but while you are reading you have to mention that which type of data
you want to read it. If you know that this structure if you read it, then it will what find; if
you do not read in that order. So, first it is ReadDouble and this one then some error you
encounter. So, we have to be careful about that in the way the data is stored the same
way it can be. So, this way any object having their values can be store into the array.

673
(Refer Slide Time: 35:33)

Now so, storing and reading into the same file. Here we can see we have store ones and
then read another, but at the same time both things can be done. So, this is an example to
explain it here and here the read write integers and here we can see this is the create
objects of DataInputStream dis and this is also output stream objects. So, two objects are
created of type input stream and output stream. A file is write declared here the, this is
the random data file here and here you can see how we have developed the program. So,
it basically generate a random number and store into the program here.

(Refer Slide Time: 36:13)

674
Now, here is basically for i equals to 0 total 20 random number will be created and then
they will be generated using random function which is there in java dot line and then
write into that stream. So, this way it basically write into the file. Once the file writing is
over we can write into the something into file into the file here.

(Refer Slide Time: 36:41)

As here is a file input stream the intFile again these are the values that is there and
readInt all the; that means, whatever the file that we have, written they are we can read
we can read in this form and then finally, it is close.

So, this basically the idea that tell you how a random data which is generated in your
program can be propagate can be post to the file in a memory ok.

675
(Refer Slide Time: 37:09)

Now, next is merging two files. It is basically the file buffer input stream mechanism and
this program is very simple here you can see we first create two FileInputStream file one
and file two and there is a sequence stream SequenceInputStream file buffer. This
basically take the two files and then convert into one file like. So, here is idea about file
1 the first object, file 2 is the second object that we have created. These are the name of
the file suppose and then file 3 is basically the concatenation or merging of the two file.

So, we can create an object SequenceInputStream file 1 file 2. So, this basically
concatenate the two files text 1 data, text 2 data into one file and the file can be store
there. Now for storing, here is the idea about the BufferedInputDtream in buffer and this
is the file 3 and then we can create it and then the same thing can be stored and then here
is basically the content which is there can be read and then display it.

So, this way, this is the this is an example of SequenceInputStream class which basically
concatenate two files into one and then same file can be displayed or can be managed or
can be processed ok. So, these are the different way the file can be handle as we have
discussed here and in our next module, we will discussed about the random access
mechanism to handle the file.

So thank you; thank you for your attention.

676
Programming in Java
Prof. Debasis Samantha
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 32
I-O Stream – III

So, we are discussing about input-output stream concept to handle the different ways of
inputs and outputs to and fro from java programs. So, far we discussed mainly the two
categories; one is called the bi stream class concept to handle the input-output and then
character stream classes for handling the same. Apart from these two things, there is one
more concept; it is called the Random Access File mechanism. So, by the name Random
Access, we can understand that, in case of the other stream that we have learned so far,
they are sequential in nature.

Sequential in nature means that you can read one item and then only the next contiguous
item can be. It is not possible to change the file location or we can say more precisely, a
pointer of the file from one point to another point randomly. So, this way, these are the
two things are different. So, in many situations, the sequential stream access is what for
us, but there are some situations where we need to access the file in a random way. So,
our today's topic includes the Random Access File mechanism in a program.

(Refer Slide Time: 01:57).

677
Now, as the name implies, so the random access implies that we can move the file
pointer according to our own requirement. So, this is the main difference between the
stream classes; like InputStream and OutputStream, that we have already learned then
the Random Access mechanism. And another important difference between the
sequential stream versus this random access is that, in case of all the classes that we have
learned so far the sequential stream is concerned, they are basically, can be opened in
only one mode; either the read mode or write mode.

So, in case of reading mode, it basically used as an input and in case of write mode it is
used only for the output, but random access can provide us to do the things together, read
and write simultaneously. So, we will see exactly how this random access file
mechanism works for us in the java program.

(Refer Slide Time: 03:06).

Now, so far the RandomAccessFile is concerned, the file system is very, the class
mechanism is very simple. Here we see, this is the class called the RandomAccessFile, it
has only two types DataInput and DataOutput. So, if we create an object of the types say
RandomAccessFile, then these object can take the input and output. So, this is the
concept there, so it is very simple. Now, we will see by means of an illustration only,
how this file, this class works. Actually, the methods those are there so far reading and
writing are concerned, is basically the same here, in this case also.

678
So, I do not want to repeat all the method. For example, read, readInt, readDouble, write,
writeDouble, like this, all those methods are there and again I want to mention is that
using this Random Access file, we can write or we can read in any form, whether it is a
byte form or character form. So, basically we can say a Random Access File, concept is a
general, overall file concept, it can be used either read or write mode. It can be used to
access the items in a byte stream form or a character stream form like this and it is also
simultaneous both input and output it is there. So, it is basically a more generalized form
is there.

So, some people can work only if the Random Access File to do it, but so far other, I
mean speed and all these things are concerned or another input mechanism is concerned,
it is basically another input stream is better than Random Access File. It is usually good
or easy to learn to programmimg, but so for the application point of view, other stream
classes are more preferable than this one.

(Refer Slide Time: 05:09).

Anyways, so let us see, let us have an example and we have to watch this example a little
bit carefully, because I did not mention about what are the methods are there. With this
illustration only I want to point out what are the different methods are there. Now, this is
the one program that I have planned for you to explain how the RandomAccessFile
works or how you can use a Random Access File in your program.

679
So, here I first create one object of the type RandomAccessFile. So, here is basically if
you see, this is the class and this is the object that I have created this is the object of the
type RandomAccessFile. So, I have just declared an object, the name of the object is, in
this case, is file and this file, this object is of type RandomAccessFile. I think this is clear
ok.

Now, let us see I just establish a connection from this object file to one file, which is
stored, there in the memory. Now, here you see our next statement is for this one. So,
this statement file equals new RandomAccessFile, we pass this one. Now, this is the
name of the file, which we want to use as a RandomAccessFile and here you can see, it
has the two-parameter. So, for this constructor is concerned and this is called read-write.
This means that we can use, access this as a read or write.

Now, instead of r w, if we write only r, then this file will be opened as a read mode or
also we can access this file as a w mode, only then in that case this file will be opened as
a write mode. So, in this case we opened the file as a read-write mode. Now, another one
important thing is that this is the file we are assuming that already is available, if the file
does not exist then; obviously, using these things a file will be created automatically for
you. Again if a file already exists; this file can be created using any either data in, output
stream or read buffer, write buffer concept character stream classes.

So, whatever the way, this file is there absolutely, this is not an issue. It is not that this
file should be created using the Random Access File concept, whatever the mechanism if
the file is created. Even this file also, can be created using your editor like; notepad++ or
any other things also, even this file can be an image file, this file can be a video file also,
absolutely this is not the issue there. Anyway, we assume that a file already exists and let
us, let us give the name of the file as rand.dat ok.

So, with this statement we can create a connection, the connection to the actual file
physically which is the file and name of this object, which basically connects from our
program to this one are called file. Now, here we can see a few statements what we can
do is that writeChar; this is the one method and then the argument is X, this basically the
ASCII value of the character X. So, what is the idea it is that, this method writeChar will
write this X into the file object.

680
Now, where it will write? It will write there, where the file position is currently located.
In the beginning, whenever we create this file, it is that default, the file location is at the
very beginning; that means, at the 0’th position what we can say. So, this means that this
character X will be stored in the 0’th location of the file.

Now next, now we write another item called the writeInt. So, the writeInt basically, write
these value as an integer and write into the file. So, where it will be written; after the X,
exactly. So, if it is 0, then the position of this value will be in the oneth location. Next,
we see, we again write into the same file objects and is a double. So, this is a double and
it will write there. So, after this writing 3 elements into the file, this goes to the 0
element, this go to 1 and this go to 2. Now let us see, there is another method called the
seek method. So, what the seek method is basically, this a very useful and very is
important one method. This method basically allow a programmer to move the file
pointer at any location where the programmer wants to do that. Now, so seek method is
basically is seek or positioning the pointer in a location. Now, this parameter is very
important. So, a parameter is basically, stated where we want to place the file pointer
location right.

Now, here file seeks 0, this means that we want locate the file position at the 0’th one.
So, in this case, 0 1 2; that means, file pointer will locate at this position, where the X is
written there in the file, this file is rand.dat. So, it is basically, in other words, file so seek
0 we can say that file pointer will locate into the very beginning of the file. So, this way
we can move the file pointer, we will see about positioning the file pointer more. Now,
here again, see, so this is the 0th 1 2 and here System.out.println file readChar.

So, which character it will read because we have already positioned our file pointer at
0’th location and at the point file.read character, this actually this. So, file.read character
means it will read the character at the 0’th location Now, so it will read basically X and
here again once it is read automatically, file pointer then will move to the next location.

So, here again, if we issue the next, statement like file read.Int then it will basically read
this one again, after reading this integer it will go to the next location; that means, it is
where this value is stored, so it will go here again. So, this one will read to the next one.
So, this will read the element which is the 0’th position of the file this will read the
element, which is first position, then second position and so on. Now, so this way we

681
will be able to move the file pointer automatically. Now, again here if you want to move
the file pointer explicitly then we can again issue the seek command. So, here seek 2, this
means that file pointer will move 0 and 1. So, this location goes to the second item.

So this basically indicates that the file pointer will go to the first-second item; that
means, these are the second item ok. So, this way we can move it and then if we readInt
it will read the integer value there. Now, here again we can move our file pointer
randomly and as we move it and from that pointer, we can read any value there. Now,
whatever reading is concerned there are little bit formalities that you have to mention.
Suppose, at a particular location we have stored an integer and you want to read as this is
a double, then actually it will result in an error. So, this would not be correct actually. So,
if it is an integer pointing it, so you should read that value as a read proper read method.

So, no other method is allowed if you do it then this will leads to an error that is;
obviously, should be handle the way with exhibition handling mechanism Now, so we
have learned about how to write something into a Random Access File, also we have
learned about how to read something from the file and also we have learned about how
the file pointer can be moved across the file. Now, here again, there is a many more so
far the seek is concerned here if you say file seek file.length. So, this basically, whatever
the size of the file at the movement, file.length will return this one and then it seek
means; it basically says that the file position, file pointer will be positioned at the very
end. So, this basically seek this one, it basically places the file located at the very end of
the file.

And once this is again writeBoolean, so again we are writing something in the form of
bBolean and this is the value that we want to write, so false. So, it will basically write at
the very end of the file and file seek 4 is basically position into the fourth item in the file.
So, it is the file seek four and this is a usual method is that a close; that means, once
every operations are over then you should close this file and then all things would be put
as we have mentioned here, under the try-catch block to catch any exception, if any
occurs while you are either opening the file or closing the file or you are reading or
writing into the file or from the file. So, that is why the try-catch block is a must, if we
do not put the try-catch block so the compiler will report an error, you will not be able to
run the program actually. So, this is the mandatory thing that you should do.

682
So, this is the idea about the random access file. I hope you have learned that how the
random access file to be managed and what are the methods are there very simple and
whatever the way that the file can be opened and it can be closed is very simple. It is, as
usual, the either, the earlier method and we have already understood about this one.
Now, likewise also we have considered here reading integer format or double format or
character format, write way also you can read or write into the other format like byte
format uta format and many other formats absolutely it is more flexible. It will allow you
to do whatever the way you want to do.

(Refer Slide Time: 15:34).

And here is another example that you can see, it is basically just example that ok, it can
also be used as a byte stream mechanism like byte stream way and let us see the program
here and this is the again, I am just creating one object rFile of the type
RandomAccessFile in this program. And so, rFile is the object that is to be operated
using the Random Access File concept.

Now, I am just creating this file object, first establish a connection, let the city.text is the
file to be operated using random access file. We create this object using read-write
method. So, you declare rFile and once the object is instantiated. So, this is the
completion of the object rFile, in the mode of RandomAccessFile.

Now, here we can see rFile seek rFilelength, you understand that what it does mean; it
means that whatever the location, it will go to the beginning give, go to the end of the

683
file. Now, in this case at the opening, so if there is no content, so it will be at the
beginning is the same at the opening. Now, here if suppose city.text already has certain
data. So, by means of this seek method rFile.length, it basically goes to the file pointer at
the end of the file. So, that is why we have here, assuming that this file already has
certain data and then writeByte as you know it is just like earlier; writeInt, write Double,
writeChar like this one, it is basically writeByte. So, this is the value that it will write.
So, it is in the byte form.

So, automatically java pro system, java run time manager will convert this string into the
byte form and then that value will be appended at the end of the rFile and finally, we
close the rFile and as I told you everything the operation whatever it is there should be
put under try-catch. So, I just put under try-catch. So, in that case, the general exception
that may occur is basically, input-output exception. So, it is called the ioe.

So, this the way that random access file can be used, actually it is very much similar to
whatever the method other classes that we have already discussed for byte stream as well
as for character stream classes. So, that is why I do not want to discuss much more about
this one, more about this random access file will be able to learn when we will discuss
about the demonstration giving some more programs in this regard. So, this is about the
random access file concept.

Now, whatever the input-output stream we have learned so far, mainly byte stream
character stream and then random access, whatever it is there you can use them and you
also use them in an interactive input-output command; that means, you can do one thing,
you can ask the common. The right way, the general program is that what is your input,
you can give a prompt to the user, user will understand about what is the input to be, for
example, enter your name. So, the user can understand that ok, in this case I should enter
the name, you can then enter your name within 20 character. So, the user understands
that the user has to enter a stream of the length of less than 20 characters like this one.
So, this is basically called the prompt should be given, according to the prompt user will
enter something and then accordingly the data will be collected, whether these data can
be collected from the standard keyboard or can be from the file or can be from other
network channels, whatever it is there, it is called the file.

684
So, this the idea about the interactive one, I am just going to give a very simple one
illustration about interactive input-output using the concept of data output stream class.
So, here the idea is that it will give a prompt, what to do; the user will accordingly work
on that, given action reply to the action and then accordingly the program will write it.
So, let us have a quick demo about this program here.

(Refer Slide Time: 19:44).

Now, here is the program as we see in this program, so we have created one class called
Inventory and next statement you can understand, what we have done is
DataInputStream class.

I have created one DataInputStream class here. So, this the DataInputStream class. For
this class we have created object din; that means, this is the name of the objects and
DataInputStream System.in, this means what? This means that we have created an
object of the class data input stream and this object is now ready to read something from
the System.in, here the System.in means that we want to read from the standard input.
So, standard input means a keyboard. Now, here we want to read a particular item from
the keyboard that will read it as a stream.

So, for these things in the java.util package, there is a class called stream tokenizer, it
will basically read a stream as a token. So, that is why it is called the stream tokenizer,
whatever the input, you write it is a general form of giving input or treating input, not
that integer, not that character not that double not that other thing. So, whatever you give

685
it, it can be considered as a stream and then stream tokenizer and then return it and then,
later on, we can change into the format, whatever the way we want. Now, here see how
we can do all these things here.

So, we first create an object called StringTokenizer and this is the name of the st. So,
basically the temporary buffer, in the earlier example we use a singular kind of buffer to
store a string value. So, similar same stream-like. So, it is like that. Now, this is the main
method. Now, in this main method, we create another stream called DataOutputStream;
that means, whatever the things will read from the standard keyboard, it will write into
this file, so invent data. So, this is the file where we want to write something; that means,
upon reading something from the standard input, we want to write into a file. It is not
that we are writing into standard output or display.

So, in that case so, so, this the two objects; one DataInputStream objects and
DataOutputStream objects. The two objects are created for input stream and output
stream; that means, reading form and then writing into. Now, the next few statements is
basically given a prompt here enter a code number. So, then once the code number is
there then these a readLine; that means, whatever the data it is entered from the
keyboard, the entered data will be read from the that source and so, this is the din is
basically, the input object it is there; that means, it will read from the standard input and
read a line and then StringTokenizer will take this value and then change into the string
form and store into st.

So, basically it reads whatever you enter the code number, is basically may be digits and
whatever it is there, but it will store at a string. Now, in the next statement as we see
st.nextToken. So, it is basically read the next items, whatever it is there and then
integer.parseInt; that means, it will change whatever the string that you have written into
an integer and will store in code. So, basically code is now whatever the user enters, it
stores as an integer into this form. Now, again enter a number of items. So, again another
input the user will provide from the keyboard, it will read from the keyboard and store
into st and again st nextToken.

686
It will basically read this token, convert into integer and then store it into items. So, here
we can see that code and items are read from the keyboard then again another input enter
cost. So, again StringTokenizer din read, it will read and here we have to convert in the
float. So cost, so in this, so far we have read three items; code as an integer, items as an
integer and cost as a double. So, once these are the three values that are collected from
the keyboard, our next is that how we can push it into the output object namely the dos;
that means, how we can write these values into a file. So, here is the method of how we
can do it.

(Refer Slide Time: 24:21).

So, you can see this is the next part of the program as you see in this program dos is
basically, the objects for output stream and we just write all the values that we have
written according to their format. For example, the first item, the code read as a writeInt,
the second item also writeInt, the third item also writeDouble. Once all values are
written, we close the output stream. Now, so, this is basically the way how the output-
input, I mean taking using prompt from the keyboard collecting this one and then finally,
writing into to there.

So, this kind of usually application is many more frequent and common, whenever you
have to develop any application line. Now, again here what we are doing you see, see
invent.data is already created by storing these on the file, we again create it; that means,
we want to see we want to read it again, whether this. Now, this is again creating another

687
dis invent.dat. Now, here also there is another way that we can do it. So, code number we
are reading as a readInt directly from this.

So, readInt and the readDouble and then we also calculate total cost and close this one
and once read is complete we again complete it. So, this is basically another way. So,
earlier is basically use the StringTokenizer, here we are showing the different ways how
we can read directly from this one, no stream form, it is basically if we read, if we know
the format directly, we can use it like this one. So, these are the common method that is
there in this class DataInputStream.

So, these are the second method or alternative approach to reading the values
interactively and then once the reader is there we just disclose means closing the stream
and then again the same thing, we are doing here writing it. So, is basically whatever the
things that we read it into the DataInputStream same is basically displaying into the
standard output. Here, the standard output means the display. So, it basically displays all
the value that we have read it there.

So, we have done about the interactive way of input and output that is possible in java
program and now we are going to discuss one more interesting application of this is
(Refer Time: 26:54) called graphical input and output concept. Now, what is the idea
about that ok? This idea is very simple and regarding these things actually our next part
of the lectures next few modules, actually we have planned to do it, but will give just a
simple introduction to this concept. It is very simple to understand at this movement
although, many more things we have to learn while we will progress further.

688
(Refer Slide Time: 27:17).

So, the idea about this graphical input-output is can be better explained with this example
here. So, this is one a window and we can say it is basically the window for text entry
things or we can say it is a frame or form. It is just like an applet actually, we have some
idea about the applet only. Anyway, so this is also we can consider an applet here. Now,
if we see this is an applet, it has many items in it. So, items mean all the applet items that
we can classify into their; here this is the one item, we call it is a button and this is
another button.

So, these applet has two buttons at the bottom, the buttons are label as entering and done.
So, two buttons other then two buttons it has also another three elements; here this is the
element, which is called the text entry field and this text entry field means it is the area,
where the user can type something and this is basically a label for this text entry field.
So, similarly their second text entry field and the label is this one and these are third text
entry field, these are label ones. So, in this basically applet, there are actually, if we
consider it as a grid so, there are 4 rows are there and 2 columns are there.

So, it is basically 4 cross 2 grid actually, we can see. Now, so the out of this 4 cross 2
grids right, there are 3 text entry fields and two buttons, this is very simple one idea
about it there. Now, so this once these windows are displayed to the user, then the user
can type the, his roll number can name and then marks one, all the values are entered

689
then if the user can click done. So, this means whatever the input that you have entered it
will be collected and then once it is collected, it should be stored somewhere.

So, that can be stored in any output stream classes or in a random access file or in a
character stream file whatever it is there. So, this our mechanism that I am going to
explain to you that how graphically the user can enter some input and then some, the
same input can be collected and finally, the input can be stored into the program. And
this program can be repeated whatever the entries user wants to do and once the user
wants to finish it so, this will select the done button. So, enter button means enter the
record sorry and then done button means when the user wants to exit from the entry
system. So, this is the concept, it is here.

Now, let us have some a program regarding these things how this program; this program
also many things we should assume it and whenever we will follow applet and then
many other concepts, then all those things will be clear clearly understandable. Anyway
so, just for the sake of interesting point only, I just want to have included this discussion.

(Refer Slide Time: 30:25).

So, this is the one program, I will briefly tell about what exactly the program is doing for
us. So, in this program here we can see first, we declare one class called StudentFile
Frame and is extend frame, this frame is basically is an AWT package which is not yet
discussed, we will discuss of course. So, this basically one class, which basically allows

690
you to create a frame actually. So, the last window that I told you, it is basically is an
example of a frame with 4 cross 2 grids.

Now, so we create two things; first TextField, there are 3 TextField number, name and
marks. They are basically student roll number, name and then marks are needed to be
stored here and these are two buttons as I mean to enter and two-button that we have
already told you and these are the label. So, numLabel is basically for the number and
nameLabel is for the name and marks for the marksLabel. So, these are the different
variable that is required in this frame and finally, data output stream dos is basically we
declare the stream objects, which is basically for storing the data permanently in a file.

Now, here this one constructor as we have declared here, StudentFile is a constructor,
this constructor and then these this basically create StudentFile. So, basically it just, it
will basically give the idea about that this the create StudentFile is the menu there and
then the setup is another method that we are going to discuss shortly. This is basically the
setup method, we will create whatever the frame, it is there allow user to enter the values
and then collect it and store it. Now, resize is basically sizing of the applet, how big you
want to have it, setLayout as you see it is called the grid.

So, there is actually a mechanism using GridLayout 4 cross 2 grid; that means, a total of
8 total 8 elements can be placed in the applet this is the idea about. So this is the total
way of creating the way applets in our program and once the applet is ready, then we
have to place the different items here. So, these are the few steps as we see, this basically
for the number TextField size is 25 and these are label is roll number. So, this basically
the first TextField for displaying on in the applet and this is for the second TextField and
this is for the third TextField. So, this is the idea about the three TextField and finally,
there are two buttons having labels enter and done is to be placed there. One all these
items are created this is called the different components in this applet created we have to
add the component into the applet.

So, these are the common for adding all the components everything into that. So, they
will automatically fix in the apple applets and finally, the applet will look the way as you
have already shown it to you. So, this way and then finally, the show method is basically
all once, all items are been placed into the applet it will basically display as an user. So,
this is basically as a part of the unit method those are there in applet actually.

691
(Refer Slide Time: 33:50).

Now, once this applet is ready, therefore, once this applet is ready, what we have to do is
that we have to add the records one by one. So, for these things what we have? So,
DataOutputStreams already you have created and then dos are the object for that and let
us see student.data is the file, where you want to store the data and then here is basically
how we can, add the record into the file. So, add record basically, these are the
temporary value numDouble d. So, num is basically collecting value from the TextField
area as an integer value.

So, this is just users syntax is that int value, it will read from the getText and then a
number. It basically converts in integer and finally, stored as an integer and then it
basically dos writeInt. So, num will be read and then dos writeUTF name. So, it will read
from the TextField area, name and is a writeUTF and then store it and then finally, it will
read the double, the marks and read at the value and write this value into the objective
dos and here is basically once a particular record is entered. So, this will basically
cleanup. So, this is the method that cleanup will do that. So, add record, once the record
is added so it will clean up and then finally, flush and then close.

692
(Refer Slide Time: 35:16).

So, the output system will be closed. So, this is basically the skeleton of the program and
finally, once it is done we have to call the method as a final method, but they're actually
two events is required one action event object o, it is basically to deal with entering,
whether it click DONE or click exit it will do there. So, it is basically two events for
entering and another event for done the (Refer Time: 35:33) button event. So, regarding
the button event we will discuss more in details whenever we will discuss about handling
applets. So, this will be done and finally, it will come to the main method.

So, the main method will just simply create this object StudentFile and it call the setup
method, which we have already discussed there; that means, this will display the total
applet and then ready for your work a user will enter as long he wants, till he finish
button, click the button DONE and then go on entering and for each entry, there will be
entered click, it will go to the next cleaning their TextField area and so on. So, this is a
very simple program which is simple, but yet effective to develop any, what is your text
entry system or a data entry system in any application.

693
(Refer Slide Time: 36:24).

So, this is about the graphical input-output concept I just do not want, do not want to
discuss this one.

(Refer Slide Time: 36:31).

So, we have planned about the graphical user interface concept. There are many more
sophisticated programming in this area of a graphical user interface, which we will
discuss in our next module.

Thank you.

694
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 33
Demonstration – XII

So, this demo is based on the topics that you have covered in the last three modules. In
the last three modules we have cover on the topic Input-Output streams in java. And as
you know the input and output is the very important activity in any program
development. And in order to make this diversified input-output process that means input
from the different sources, output to different sources, there are many mechanism rather
many ways has been devised in java system.

(Refer Slide Time: 00:53)

Now, today we will discussed about how the different in way of input-output is possible.
There are some trivial input output mechanism, those are related to the standard input,
and then standard output namely keyboard, and then display unit we have already
covered, we usually used it in our previous programs. But, here we will discussed about
other than the standard input and output, how we can store some data into memory or we
can receive something which is stored in hard disk like.

So, our demonstration includes how to create, how to open, and close a file, how we can
create our own file. And there are again two different classes rather we can say the ways

695
the byte stream classes, and then character stream classes to read and write into file from
file by means of DataInputStream and the data output stream. So, we will discussed
about the usage of these two classes to create files to access the data, all these things.

And then we will discussed again file handling in java. So, file is basically secondary
storage right, we can store some data in a permanent non-volatile way into the secondary
storage space. So, how we can create a file such a secondary storage, and also how we
can open, how we can copy, how we can merge, so many other things are there. And few
advanced methods, they are called BufferedInputStream, and SequenceInput Stream to
make our programming easy we will discuss in this demo.

(Refer Slide Time: 02:51)

So, let us have the demo for first thing, and this demo we can start about from very
simple idea about using the DataInputStream class. We have already familiar to this class
in our last in our earlier discussion we have used it. So, DataInputStream class as in the
name in implies that it will basically for the input purpose, then we using this class, we
can read something from some sources.

Now, here we will see exactly DataInputStream class can read from memory, can be
from network channel, it can read from standard input device. This example illustrate
how the DataInputStream class can be configured, so that we can read some data from
the standard input namely the keyboard. As we see the program here, so this is the main
method as we see here. In this main method, we create two way fields namely the

696
principal amount, and the rate of interest for which we want to read the value from the
keyboard, and the number of years also. So, the three input needs to be collected from
the user through keyboard.

Now, here basically we create an object called in, and this is object that object is created.
And then this object wants that it is created by means of a constructor, where the input is
basically System dot in. Now, System dot in implies that it is a standard input the System
dot in this is already defined in the java dot lang, so from there it will get the definitions.
So, it will basically is a standard input.

Now, so basically what we do we here that we create and DataInputStream object, which
basically connect your program to the keyboard. Now, let us see we given from to the
user that entire principal amount, here basically we have discussed about that for seeing
that means, keyboard has its own buffer. So, we have to clean the buffer, each time we
are going to read from it.

So, System dot out dot flush is basically clean it is now here then ok, so it will read from
the object in here that means which connect the keyboard. And the in that read line for
this method read line means, it will read the entire content that is there is a buffer. So, the
entire whatever the value we will enter, it is read it here, but as you know the value that
will be there is a buffer java program read it as a stream. So, we temporarily store this in
the stream format here, so it will basically read as a stream. Although these are may have
entered some value say 5, 6, 5.25, so it is basically plotting point or double value.

Now, here we convert this string value into our double value or float value. So, using the
float method for this in the class float, which is defined in the java.net (Refer Time:
06:02) package, and for this class there is a method called value of this is a static class
actually. So, we just convert this string into the float value.

Now, again we read the another form enter interest again we flush it, and then readLine,
again read the buffer, and then again convert this string into the float value which stored
in the rateofInterest. Say again then we need the integer number from the read, we
convert it into integer format as initially it is a string, and then store the value is a
number of years here. So, this is the way we can read the three inputs from the standard
in standard input that is the keyboard here.

697
And then finally, we calculate these are trivial process. Now, main thing here we can see
you can tell here is that how using this DataInputStream class, we can create a stream
object which connect your program to your keyboard. So, the stream can be propagated
from the input source to the program. Anyway, so this is the simple program we are
already familiar to, and we have discussed it many times earlier. And other than this
class also there are many way the input can be found the standard device like common
line input, and then the using the Scanner class which is defined in java.util package, we
can run all this things.

(Refer Slide Time: 07:43)

Now, our next example that we are going to discuss about is basically as we have
discussed about all the DataInputStream class is basically the two fold using the byte
stream, and then character stream. Our next example this examples to illustrate how we
can output to a file which is stored in a secondary storage, and we can propagate the
output from the program to the file in the byte form. As you know byte is the smallest
unit a chunk that the java program can handle it.

Now, here is a program as you see here ok. First you have to import java.io.FileOutput
Stream, this is because we want to propagate the output to a file. And this a FileOutput
Stream class in defined in the java.io package, so the import is must. Now, here is the
main method as we see we create an object name of the object is a fout is basically of
type FileOutputStream. And here you see the constructor the FileOutputStream has its

698
own constructor, where an argument is required is basically the target. So, here actually
the target we have mentioned explicitly, where we want to store this content.

So, as you see it is in the D drive under these D drive there is a directive demonstration,
under this demonstration XII, and then this is basically the target file and test dot txt. So,
you should explicitly mention path of the file, where you want to store your data. So, this
is a way that we can do it. Now, here you see for this object fout, fout therefore object is
basically the connection from your program to this file test dot txt.

Now, from the programme we can write 65. Now, 65 is basically here in integer form,
but it will be converted to and byte form as you know the 65 byte in the byte form, it is
basically capital A character. So, ultimately although we give the 65 your program the
system will convert into it a byte that means, 65 in the byte is basically the ASCII code is
a. So, a will be store actually in the file. And then finally, once the file is open, we have
to close the file it is always, you should close your file always wants your task is over,
and then finally it print the writing is over.

Now, this program as you see this program will write 65 in the byte code form into a file
test.txt. So, after the successful execution of this program, we will see the output file here
test.txt that 65 is told there or not. So, this program is run successfully, and then output
file is here. The test dot txt is now displayed as we see it basically store A.

(Refer Slide Time: 10:41)

699
Now, in the same program if we again write 90 fout write 90 type it no another write, 65
is the here write yes in addition write.

(Refer Slide Time: 10:59)

Now, we are writing another 90, as you see it will happened after the first 65 that mean
A, and corresponding the 90 byte code, it will be stored there in the same file again.
Now, here the same file can be AZ. So, Z is basically the ASCII code for the 90 ok. So,
we are learned about how in the byte form, we learn more about in the byte. So, the next
example, suppose you want to store an array of elements into a file. Here we can give an
idea about how using the bytes code system, and array of elements can be stored into an
into a file.

Now, this program as we see the main program we first created array of bytes, so here D,
E all these are basically the ASCII value within the single code whatever we mention, it
is basically the ASCII value of that character. So, capital D, E, L, H, I, so ultimately like
the previous program as we see this is the byte so A it will store, but it will store now in
the array. And this array is basically byte array, because it is declared as a byte type
array. We can declare float, integer also that way it will store the integer from that way.

Anyway, so this basically now we create one output objects, so output file is a type of
FileOutput Stream very similar to the previous one. And then we decide it is a create the
object, and finally we make a connection that where this value will store. So, for this
object output file, we establish a connection to this is the location. So, the location is as

700
we see location is city dot txt that means, this is the output destination target, where the
output the entire things whichever here will be there.

And then finally, you write the entire array here, so passing the array name here and
finally close, these are the same as earlier now ok. So, this way the entire array elements
will be stored into the file. Now, let us run the program, and final you will be able to see
the file in this case city dot txt, which store all the values that is there in the byte array
ok. So, file has been written successfully.

(Refer Slide Time: 13:43)

And then we will be able to run the we are display city dot txt as we see here Delhi,
Mumbai, London. These are the basically ASCII character as it is there in the byte array.
So, it is basically print a store successfully. So, this program says how a an array, and the
similar way this program can be an extended to store any array actually, whatever the
you can use a byte array rather you can use the characteristic classes also whatever it is
there.

701
(Refer Slide Time: 14:07)

So, an array of elements can be stored, a single element can be stored, and like this, here
we are storing all these things in our memory. Now, our next example again using
FileOutputStream classes that we have discussed that we have to pay to copy some text
using again byte array steam into the same file.

Now, here is a program as we see, it is the same FileOutputStream class. Here


FileOutputStream, create the object, and we just connect it to one target testout.txt. And
here we create a stream here welcome to NPTEL. Here is a small string we have
considered, many other large string also we can include say, other things also you can
input here.

For example, type here welcome to NPTEL, hope you are enjoying java programming
hope you are enjoying java programming ok. So, this is the text whatever the text may be
here only few characters, very big I mean very large file also can be consider. I will
discuss about how a file can be entire file can be copied here, anyway our objecting is
that these stray string, which is basically here in the program, I want to store into a file
the name of the file is testout dot txt.

Now, we first store this string into the form of a bytes. So, here is a mechanism for a
string object, how we can convert into the bytes. So, basically string this is the string and
we converting into the entire string content is the byte. So, get bytes is a method for the
string class, which is there in java dot (Refer Time: 15:57) package. So, we temporary

702
stored into an array byte array, it is the similar to the city array we have as discuss there.
Then write function write method for this a fout FileOutputStream, which basically write
the entire array, it is also same as the earlier one and close. And finally, file writing is
over (Refer Time: 16:16), and then it will there.

Now, we see after the successful running of this program. We will see one file testout dot
txt has been created, where we could store the stream which has mentioned there fine.
Now we are displaying the file content as we see this is the content has been pushed to
the file, which we have displaced there. Now, so this is the way that now so far what we
have done is that we can create something we can store something from our program to
file.

(Refer Slide Time: 16:57)

Now, we learn about how to read a content from a file. Now, this very simple program
for this purpose for reading some content from the file, we have to have that create object
for the file input stream class. So, file input stream class, because we have to go for input
process. And then fin is the name of the object of this class we have created, and this is a
usual process of creating the object, and giving the explicit mentioning where actually
from which file we want to read.

So, in this example we want to read something from testout.txt, which file we have
already created like welcome to NPTEL like. And here int i equals fin dot read(), you

703
little bit carefully observe for the fin object. A f in object means that is a connection from
this program to this file, we inform the method read.

Now, read method always read one character at a time, so this means that the whenever
we create the object file object here, it basically point to the first character in that file,
and it will basically read that character. And this character actually written by this read
method as an ASCII value of the character that means, it will read there. And finally, we
can print this character by casting it that means, i its ASCII value will be converting the
character corresponding to this, and it will be stored there.

So, you can note that in the previous example testout dot txt, we have store the welcome
to the NPTEL. So, W has been store there, and W being the ASCII value, and then it is it
will be access it, and then it will display from your program. Now, here you can see here
you can see here, you can see W is being printed. Now, if little bit change this program
without casting it, you can see here without casting it, we can run the same program
again, but only the its integer value rather it is basically not ASCII code, it is the ASCII
value.

Now, here we see we print here in case 87 and 87 is basically the ASCII value for the
ASCII character W. So, this is basically the way here exactly we save this programme
earlier in the byte code form, here we read in that ASCII form byte form, and then
printing into its character. So, conversion is it possible. So, this means actually I want
emphasize is that whatever the way in the byte or character, you can do it and you can
read it also no issue it is there.

704
(Refer Slide Time: 19:55)

Now, we learn about more about regarding the charactering the stream classes. As we
have seen in the last example, we could read only one character from the file. If you want
to read the entire character set stream text from a file, what is the program should look
like? In this case, again we have to create an object for the FileInputStream, because we
want to read a file. And here is the object the same way, we created the object a fin. And
this is the for example, testout.txt is the target file from, where you want to read the
entire text. As you know in this text, we have written welcome to NPTEL hope you are
enjoying java programming like.

Now, here this basically is the loop instead of only single character, we want to read it all
the characters which are stored there in this testout dot file. Now, a fin.read, it is
basically to be looped until here is the condition. This is very important not equals to -1,
so not equals to minus 1 java (!=-1) implies that it is the end of file. At every end of file
whenever you put file close; the java put a -1 there indicating that this is the end of the
file, so -1 is a termination condition for a file object.

Now, it will basically read the file content. And here the content which will be read from
their FileInputStream in the byte form, we convert the character and those things will be
converted printed on the screen. And finally, wants the entire file is scanned, it will
basically closed. And here you can see it will read the file sequentially the first, then
second, and third and so on so on, until it will reach to the end of file.

705
So, these program again as you can understand anticipate. If we run, it is basically
extract all the content, which is there in test out dot txt, and display on your terminal. So,
I am running this program, and then will see after running. So, this program has we see
here, it basically show the output entire which has been accessed from the text out dot.
This is the basically content, which we have stored in the taste out file and this exercise
and displayed it.

(Refer Slide Time: 22:03)

Now, so we are learned about how we can open a file. And then from that file we can
read the content in the form of a byte. And our next example is basically regarding the
file status checking. So, it is a 12.6 programme, we are going to see about it. Now, here
you know so for the status of the file is concerned. Whenever we store a file or operating
system maintain all about its file that mean in which directory what is the name of the
file, what is the extension, whether the file is in which mode readable or writable,
whether file is available or not available, whether file is corrupt, whatever the
information it is there. So, it is basically the program, which all these information can be
accessed from the program site itself.

Now, here we can see this is the program, and it basically two methods we have
discussed here in this class, this is basically our main class. The method is getPaths, and
another method is getInfo. Now, so for the getPath method is concerned for a object file
object. So, file is basically one class, which is define in java.io package, so .* include

706
that file package the file class need to be accessed. So, file for this we will pass this file
object, whenever you call this getPaths.

And now here you see this getPaths method input simple three statement namely, it will
basically give the name of the file f dot getName(), the name of the file f dot getPath(),
which path actually it is stored. And f dot getParent() what is the parent, if it is there.
And then so far the getInfo method is concerned, if the file exist that means, if file is not
null, file exist means you can pass information which is no more exist. So, in that case if
it is exist, it will just exception.

If it is exist it is true, then it will go for this printing f dot canRead, f dot canWrite that
means, it basically whether this file is readable or write writeable, read mode or write
mode, read permission, write permission. And then it also say the last modified
whenever you created file, system always store at the last modification of the date of this
one so this one. And f dot length is basically how many bytes, basically how many byte
basically are stored there in this file. So, they are the information.

Now, let us come to the main method here. So, this is the main method this is the main
method. Here basically we create one file object name of the object is file to check. And
then if args.length, basically we can we can pass the command line input, so that we can
run this method program for as many file you want to check for it. So, it is basically args
dot length. And for each file argument we have passed it, it will basically call the
getPaths and getInfo method that means, it will retrieve all the information regarding the
file name path and status of it, and finally it will come to the end of this program.

707
(Refer Slide Time: 25:27)

Now, will run this program passing three input as a command line, and say the input is
input is say city.txt, we know we have created one file test dot txt, testout dot txt. These
are three files are already we have created. Now, so we can see ok, we are running this
program using passing three input city.txt, test.txt, and textout.txt fine.

Now, here you can see the output as we see path test dot txt parent there is no parent
actually indicating null, and then and is writable. Last modified this is basically the
system time it is in a some (Refer Time: 26:13) form, and then file size is two bytes.
Now, name city text, path is city.txt, parent there is no parent for the, this file. Readable
file it is also it is a writable, last modified this one 20 bytes, this also like this. And here
you see textout.txt this basically file does not exist, because this file actually it is not
there whatever it is here.

708
(Refer Slide Time: 26:47)

So, whatever file you have passed to the program, this program from side it can check
the status, and can show you. Now, we have discussed about so far the byte stream
classes for reading as well as writing. Now, it is our time to learn about other classes, so
for the file handling is concerned. They are called FileReader and FileWriter class.

Now, we are going to have a demo. Here in this demo, we will see how we can copy the
content of one file into another, so basically making a duplicate, and using FileReader
and FileWriter class. So, this program again we make the program for illustration as
simple as possible, we can see we fast create one object inFile for the file. This basically
creates a connection from this program to this target date input data. Assuming that
input.dat file is already there in the system. If it is not there, then it is throw an exception,
because file opening will not be possible anyway.

So, this is also another out file, and this basically where the content will store. So, here
we have created two file, inFile and outFile for the two purpose; purpose is that reader
and writer. So, I just create an object ins, so that in file can be used for the input purpose
that means, from in file I will be able to read something. So, inside out are the two
objects of type FileReader and FileWriter for the input and output mechanism.

Now, here for ins we create the file reader object for the inFile. So, in this case inFile
means, it is basically input data. So, in other words ins means, basically a connection
from your program to inFile, inFile means input.dat. Similarly, outs is the connection

709
from your program to outFile that is the output.dat file. Now, here basically we have to
read each and every character those are there input.dat that means, inFile. And then write
into the out display on the it is basically read the entire file, and then outs write means it
will store into the output file.

Here we see the statement that we have ins read means read one character from the file at
a time store as ch the temporary store. And then same ch, it write into the output file
outs. So, reading one character from the ins, writing the same character into the outs that
mean input date and output date. So, this program and also we have filled up with try and
catch you have to always use try and catch block.

(Refer Slide Time: 29:27)

As there may be some situation unwanted situation, whenever a file is not accessible the
file read permission is not there, write permission is there or file is no more memory
space is available to avoid so many situations, we have to handle the exception. So, those
things can be done by try catch mechanism.

So, you have to handle for every occurrences either creating file or reading or writing,
whatever right so they should be put into the try catch flow there. Now, here is basically
as we see the output welcome to NPTEL is the input.file. And we copy this the same
content, and also create the output file welcome to NPTEL. So, we created the duplicate
of one file input dat the name of the duplicated file is output dat.

710
(Refer Slide Time: 30:29)

So, we have learned about how a file copy is possible. Now, here another example in the
last example, we have discuss that copying the file using characters, so it will basically
character stream classes. We want to do the same thing again, but using byte stream
classes. The difference is that in the last example, they will read as a character, but here
they will read as a byte that is all.

Now, the mechanism is almost same, but there is again reason that when we have to read
character, when we have read byte. Whenever heterogeneous stream is concerned, then
you should use the byte stream classes. And homogeneity means in the same system
whatever it is there, you have created the file in macro ways, and want to read from the
windows, then obviously byte stream is the best procedure. But, if it is the same system
(Refer Time: 31:09), then you can use whatever method you can. So, byte stream is
always preferable.

Now, here is a program as we see the same as a inFile, and outFile are the two FileInput
Stream and FileOutputStream object. We create the connection inFile, passing this is a
target is the input source is the target that means, where the file will be stored there, now
here is only mechanism it is difference then the previous one.

So, here byte read temporary store here as a byte in file read, it will read from the in file,
store if the byte form, and it is the byte ok. And then by read is again while this is not
equal to -1 mean, you have to copy scan the entire file. So, we have to go for loop. And it

711
read one byte at a time, and the same byte is write into the output file, and again go for
reading the next, and then loop continue and until this one is there.

Now, input.dat as you see welcome to NPTEL restored there. And here out.dat file will
be created now, if it is successfully copied from that file. So, mechanism is little it
different, but the target objective is same object is that we are copying from file to
another file yeah, file has been created out.dat file we are going to display the out.dat file
yeah, this is the out.dat dat file, you see this is the continue file that we have obtained it
after successful compling competition.

(Refer Slide Time: 32:37)

Now, so this is the idea about, now before concluding our demonstration we want to
have two more chance in programming illustration. This is the utility of BufferedOutput
Stream class like also BufferedOutputStream, BufferedInputStream. In our next two
examples, we will demonstrate how the BufferedOutputStream and BufferedInputStream
is possible, it is basically same thing the same idea about byte stream actually, but you
use another class that is there already java jdk call the BufferedOutputStream class.

Now, let us have a quick look of this program here, we just create file output stream of
this, because you want to read something to write into somewhere for the file output
stream, we want to write something into testout1 dot txt. This is our target file, where
you want to store it from our programme, we want to put somewhere into this target.

712
Now, let us see what is the program that you have to put string s welcome to NPTEL,
this means that you want to write stray string, string into this one, but here we want to
store it using this is the object the BufferedOutputStream object call the bout. So, is
basically bout is a BufferedOutputStream is basically is a connection from the fout. So,
the fout to this one that means, it will channelize the content. And then is stored in a
BufferedOutputStream form and that in this one.

So, here at this stream s will be from our program, and we convert in the string and here
write b byte, and then we will store into the bout form. Now, this idea about that byte
buffer output stream classes is there, and this kind of program although we are storing
our programme. But, instead of this program if it is a network source at the moment, we
do not have any network experience. So, we will not be able to do it with a networking
example, but here this s can be forms a network channel.

Now, you will receive the BufferedOutputStream from the network whatever the stream
will come, we will buffer it first in our local buffer, and from that buffer we will push
into the file target file. So, basically suppose you are downloading an image from the
website, and then this image can to be a very large one, so we will buffer into. So, in that
case we should use buffered output stream object, so that we can store and image as a
buffer form instead of the entire image can be push there, because entire means too large
maybe few MB, and you cannot put it there, so it is a buffer form. So, for this purpose,
we will do it yes.

Likewise, buffered input basically if we read very large image from the channel network,
and writing into a channel network like ok now, let us see here, how we can write this
things into this one. And ok, so here the file is successfully content, here we can see
directed our output to a file. But, here instead of directing this file, we can direct it into
some network port, so that through network this can be transmitted. We will see about
the network, whenever you will cover the networking in this module in this course.

713
(Refer Slide Time: 36:19)

Now, the next example just opposite to this byte output steam buffer, here the byte
BufferedInputStream class. Same problem here, basically here we just create the buffer
input stream that means, we will read something. Here we will read again from this
object out dot dat is already stored there.

So, instead of out.dat here, we can in this source we can maintain the network port
number socket all these things. Here we will just read the output at in source of the input.
And then it basically read the entire content, and then read in the form of a byte, and then
print on the screen. So, it is basically the idea about BufferedInputStream, and then
BufferedOutputStream concept yeah this program as you see using the
BufferedInputStream, we can access the file.

714
(Refer Slide Time: 37:19)

Now, if I ask you the same thing instead of buffer input stream using simple
DataInputStream and output stream, you can do the same thing, you can do it actually
you have done it already. Now, our next example to illustrate the usage of Sequence
InputStream class. Now, so the SequenceInputStream class is basically can handle two
more files together. And it will automatically manage it without any intervention within
them.

Now, here is the program you see, first we create one input stream FileInputStream
namely input1 and another input stream-2. So, here input1, and input2 are the two input
target source I can say. And these are two source namely input.txt, input2.txt assuming
that there already present in the directory. Now, here you see we create an object call
inst, which is of type sequence input stream, this class is again define in java.io package.

So, we can create an object inst, now why we are creating objective you will see, how we
can create object passing two input as a overloading constructor of this class input1,
input2. Here also we can create input1, input2, input3 also, it will take the overloading
constructor will take it. Now, what it will do is basically input1 and input2 the two
sources will be scanned one by one, and then the resultant total scanning output will be
stored into the inst. And then that inst can be accessed I can read it, and then finally this
inst can be display on the screen.

715
Now, here is basically inst, which is basically the result of sequence input stream, and
then will be displayed on the screen. So, it will see the input 1. txt, and input 2.txt, the
two content will be displayed on the screen. And finally, we close all the string in input1,
and input2 from our system quick.

(Refer Slide Time: 39:31)

As you see here the output as it is shown here, this is a input this is a input two one. So,
actually this is the content in the input1.txt and this is a contain input2.txt. So, two files
are sequential accessed one after another, and it is basically displayed on this one.

(Refer Slide Time: 39:49)

716
So, this is the one usage of the sequence input stream class. Another one application of
the sequence input stream class very same concreted margin. Here actually we (Refer
Time: 39:58) not stored into the third file. When this program will basically tell you, how
the merging result can be stored in the third file is the same as this one. And file1 and
file2 just like input file1 input file2, and file 3 is basically the target third file is basically,
we will store the concatenation of the two file.

We use the sequence input stream again file 1 and file 2 that means, file 3 will store the
merging of the two content. Now, using the buffer input stream, I can read it and then
display it. So, here basically in buffer, in out buffer is basically file3 and output is output
buffer is basically displaying on the our standard output device.

So, it basically using the by buffer output in form and this program if it is data there, so
the concatenation of the two file result will be displayed from the third file on the screen.
So, this is a program that we have discuss about using the sequence input stream class
example and here is the. So, this is the again program as you see this is an input this is
the same thing that is concatenation of the two input file.

(Refer Slide Time: 41:17)

Now, we will discuss about random access, this is the last content to have the
demonstration. Random access is just different mechanism the totally different, then the
concept that you have learn so far. In some situation, we have to access the file in a
random manner, whatever the things we have discuss that we discuss the file in a

717
sequence manner that means, one character the next character one by the next byte until
the end of file likely, but here we can read at random.

So, this program can have a quick demo about it. And you can use the file class for this,
so here we just Random access file rather. There is a class RandomAccessFile, which is
defining java.io file, we have to create an object for this. So, we create the file is that I
RandomAccessFile. And this file whenever we created, it can be open in any read write.
So, other unlike sequence access, it can be read either read or write, but it can be open
both mode.

Now, here we create the file object and this is connected to the file. So, you want to
randomly access rand data reading, writing on the same file at the same time like. So,
here you see we first write something writeChar, writeInt, and writeDouble, and these
are the input that we have to write into this that means, if the file is blank or if the file is
there if we write it from very beginning, it is basically overwriting. Then entire content
will be deleted, and it will store this one.

And here is the file seek is basically positioning the file pointer, so it basically zero
indicates that, it will position file pointer at the very beginning that means, where the x is
now written there. Now, here system.out.println (file.readchar()) that means, presently
seek 0 that means start here. This statement will read x, and then again after reading x
automatically file pointer move to the next one that means, read come here and readInt, it
will read this one. Go to the next one, readDouble, and it will read this one.

So, this is basically reading and writing from the same file as you can see there. Now,
here again seek two as you see that file position will be move to the second location. So,
1, 2, then it will go there. And then again we readInt that means, you can read the 555
here. And then file dot seek (file dot length), so file.length as you know, it will give you
the size of the file.

So, if the seek is go there means, it will move the file pointer to the end of the file. And
at the end of the file.writeBoolean false that means, we write a Boolean value and the
false. And files dot seek (4), again we go to the forth position 1, 2, 3, 4 means, it will
come here. Then we can file read Boolean, so read Boolean means it will false and then
finally file close. So, this is basically shows a very quickly shows that how the random
access mechanism can be applied to a file object.

718
(Refer Slide Time: 44:13)

Now, here is a quick execution of the program, so that we can learn about it. And then
you can see the difference state that it will show here as you see here, this is the first read
integer write, read character, write integer, and then write double, and then again read,
and then again finally go to the file position at the end, where the true is store and we
read attribute and then get it. So, this way we will be able to access the file in a random
way. This is a very small example, we have discussed about it.

Now, I hope you have understood the concept of file input output mechanism in java.
Input output mechanism, it just started here. The more input output mechanism will be
discussed, whenever we will discussed. The graphical user interface concept there is a lot
of input output in a different fashion, the different style we have to follow. But, all those
lesson that we have learned, we will be utilize there. In addition to this also few more in
those context, we discussed ok, we should wait for the next topic that we are going to
cover, it is basically graphical user interface programming our next topics to be covered.

Thank you very much, thanks for your attention.

719
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 34
Applet Programming – I

Now, we will learn the second part of this course. It is basically Applet Programming.
Regarding this applet programming, at the very beginning of this course we have
discussed about what exactly an applet it, we will basically recapture because is a long
term back we have discussed it. We will recapitulate all that consider we have once
learned and then finally, we have planned a series of modules other modules to cover the
concept of applet programming in detail.

It is in fact, a very huge and then many mechanisms, many concepts, many ideas, and
many tricks are to be learned actually. So, all those things we have learned one by one.
So, again first let us have the applet programming.

(Refer Slide Time: 01:03)

Now, definitely so for the applet programming is concerned you know applet is
something different than whatever the programming that we have learned so for using
the convention mechanism. So, they are called applications. Now a Java applet is
basically is a small program, which is usually embedded in a web document; web page.

720
And this way whenever you browse a web page, a particular applet will be viewed or
applet will be displaying its results and then applet will allow you to do a lot of
interaction from the user using this applet; a user can play music, user can play video,
user can enter the data, user can login to the system, user can receive data from the
database; what is not.

So, an applet is more versatile. And you know if we add applet in an application, it really
adds beauty to the application and whatever the (Refer Time: 02:00) program we see
nowadays, there basically embedded. That means an applet is embedded into the java
program, then it becomes more fascinating, more user-friendly and more useful to many
people who do not know much about the programming actually.

So, really it adds beauty to the programming. Now many programming languages as you
know C, C++ , Pascal they usually do not have this applet facility. The java is an
exception in this regard. So, Java provides applet and managing this applet in a variety of
ways, in a very professional way actually. There are many mechanisms are for this
purpose only on which we are going to learn actually.

(Refer Slide Time: 02:45)

Now, in very simple words if we see what exactly applet is. An applet is nothing, but a
window we can say. So, that is why the operating system which based on this concept is
name as the windows operating system; what is the most popular operating system from
the Microsoft corporation ink.

721
So, an applet is nothing but a window and as we see, this window has few things are
there. There is basically the title of the window or we can say applet I should not say
window here. Window which is a special term coined by the Microsoft, but applet is the
basic things which basically used to develop any windows of your own.

And then here is basically the status of the applets. So, the two things are basically the
title and the status at the top and bottom and then, this is basically the view area of the
applet. Here it contains it includes many things. In one example where we have
discussed about the graphical user interface concept, these basically text entry areas, it
can include displaying the image or a video or it can include multimedia contact image,
video and then text and everything. So, these basically the area which basically used to
display many elements in it. It can also display the menus, sub-items of the menus and
everything.

So, this basically typically and an applet is. So, applet programming is basically an idea
about how we can develop this kind of user interface. More precisely, it is called the
Graphical User Interface and more popularly it is called the GUI; so GUI, so that is the
applet actually.

(Refer Slide Time: 04:35)

And usually, how we can write an applet? It is very simple as we see here, this is the
simple most code that basically an applet can be. Whatever the applet we have shown
just now, is basically a product from this program. So, this program already we have

722
appeared. So, to write an applet as we know we have to import java.applet.star, because
this basically applet programming follows many classes, many methods, many
constructors from this applet class.

So, there is a class called capital APPLET, applet class which is there in the package
java.awt, java.applet. In addition, this is also one AWT package is there abstract window
toolkit, which basically used for managing the different working or activities in an
applet. So, this is the two important packages already built in the JDK and we have to
import it and use it in our program.

And here is the simple most code, which we already familiar to earlier and this is the
name of the java class that we have declared and this class should be extended and applet
class so, that is the user syntax whenever you have to write an applet class or a program
for applet. And this is the one method we use here to paint and this is the Graphics g this
is also one class that is there in the Graphics class which is in the java.lang package is
there, and then for this we just drawString “Hello World”.

So, this is basically an idea is that in this location of the applet window 150, 150; it will
print this thing. So, this is a very simple one applet program which will basically display
only one element namely a stream, which is as “Hello World” on the view areas actually.
So, this is the way that applet can be written and as you know once the applet is written;
we have to we can run it, we can compile it. Obviously, this file can be compiled
HelloWorld.java. If this is the name of the program, then after compilation
HelloWorld.class will be created.

(Refer Slide Time: 06:49)

723
One this created, this class file can be viewed using any browser. For example, an applet
viewer is one browser that can be used. So, basically we have to edit, save and compile.
So, as we told you this is the name of the file that java and then once the compile javac is
the compiler which will produce the HelloWorld.class.

(Refer Slide Time: 06:57)

(Refer Slide Time: 06:59)

724
(Refer Slide Time: 07:05)

Now, this class file needs to be embedded and to do it we should follow one HTML file.
So, this basically looks of an HTML file will look like this and there is basically this is
the typical structure of the HTML file. And their applet code that is the code which
basically used to embedded the file HelloWorld.class. So, this is the name of the class
file that we have created and we have included here and this width 30 and height 30 is
indicates that what will be the size of the applet in your case, in this case actually. So,
300 cross 300 so, 300 pixels this one and then 300 pixels this one. So, this way the applet
is configured and ready for browsing.

(Refer Slide Time: 07:57)

725
Now once this an HTML file is created, our next time next task is to open this browser
and this browser can be open using any browser as I told you. And obviously, this file
should be stored on HTML file as we see here HelloJava.html, but not necessary
HelloJava, it can give any name of the program. It is not decided to give the same name
as a .classfile or .javafile; any file name can be given here.

(Refer Slide Time: 08:21)

Now so, this file can be browsed using any browser and there is one popular browser in
this reaction is called the appletviewer. So, it is basically appletviewer and appletviewer
and then following the appletviewer.htmlfile that can be used here. Now earlier versions
of the Internet Explorer, Netscape Navigator; they allowed it, but now because of the

726
security reasons and many more aspects the modern browsers like Mozilla, Safari they
basically do not allow to browse any applet code.

So, that is why we cannot use this one which was earlier possible but nowadays it is not
possible. Anyway, so appletviewer is the best way to browse an HTML file to sue it see
it.

(Refer Slide Time: 09:07)

So, here is the way that how you can see it basically, so appletviewer and the name of the
HTML file. So, you can see it here .htmlfile can be this page, then it will display. And
then typically the output for the program that we have discussed, it is basically the
typical output it will look like. So, this is the output that you can see on your screen.

727
(Refer Slide Time: 09:21)

So, this way we can see, how a code. Very simple applet code can be written, can be
processed and finally can be viewed. And this is enough for the beginners so, that you
can understand about, how it will work.

(Refer Slide Time: 09:55)

Now, we will quickly see about the general features that are there in an applet. So,
basically, we will discuss about the structure of an applet. And as we see in this program
it has 3 different parts as we see here. The first part is basically, this part is called the
package part and this is basically the main body of the applet.

728
Now, the main body, in this case, is very simple, but actually there is many more things
that need that can be incorporated here and ok. This is the 1, it is called the .java
component and this is basically called the .html component which basically embedded
the applet, after the successful compilation. If the composition is failing at this stage and
if you do it, this view will open it; but it will not display anything. So, it will be totally a
blank.

And if you do not give this code and then applet viewer you can use it, the applet viewer
will do it; but it will give only a blank applet. Now, so this is the 3 things are there is
a .java file versus the .class file and then this is basically the HTML file and finally the
browse; browsing of the output.

(Refer Slide Time: 11:07)

Now so, now I will just discuss about the structure of the applet code that maybe there
that means java .java component it is there. As we have already discussed about there is
basically one section or the first part of the body is input. Here many things can be
imported as in the last example as we see import applet.star, import java.awt.star like
((Refer Time: 11:34). So, there are many import section that mean those are the class or
library that you want to include in your java code that you can use it here.

So, this is a first part and second part as we see, this should be an applet should be a
public, because an applet needs to browse. So it should be public, you cannot provide
any other modifier like default or private or protected. Only the public is allowed, then

729
class and then by default actually it will take public. So, if you do not give anything is
public it will take and then class name and that this is a name of the java class name that
you want to do as we say it extends Applet. So, this basically part 2.

Now, part 2 includes many more things, it will allow declaring any variable that is
required in your applet. So, it is a variable declaration part and then an applet allowed to
invoke many methods. You can write your own method or you can write some method
which is there in this package, libraries. So all these method sections will be there.

So, altogether there are 4 parts, import part, this basically the class declaration, the
variable declaration and this is the method declaration. And obviously, it is the
mandatory parts so, but seems to have an applet you do not you may not have any
variable declaration, you can ignore it. So, it is not necessarily that all parts are
mandatory which is some parts are optional required if it is there otherwise not there
even we can write an applet without method part also. This means that it will just do not
display anything, do not do anything. So, it is a blank applet will be displayed like this
one. Anyway so, this is the general structure that an applet program should have.

Now, so here is an example check one by one. So, this basically import section as we see
here and this is basically public class declaration, there is no variable part in this case and
this is the method part that we see. This is a method part. So, these are the 3 parts are
related to the small applet that we have discussed just now.

(Refer Slide Time: 13:41)

730
Now, so far the applet methods are concerned, I will just give a few hints about it what
are the refund method is possible. You cannot include any method of your own rather
you should include some method which is basically the method declared in the applet
class and in basically you have to overwrite that method.

Now, the method which can be overwritten in an applet is misted here. The init method,
is the init method, the start method and stop method. So, the init method is basically used
to initialize an applet before giving it and start method actually, it will follow the init
method once the initialization is over, then the start method will start execution of the
applet and stop is basically while an applet is running. So, if you want to stop it, then you
can use it.

So, these are the three methods that we can use it. Actually, these are the method as I
told you is basically to overwrite the method means we have to write the code for this
method in our own applet program.

(Refer Slide Time: 14:47)

So, this is the way that different method can be created, there is two more methods also.
They are basically already we are familiar to one method the paint method we have; this
basically for painting. Now, whenever you have to display something, it is basically via
paint. If we have to paint the image there also via paint and you see how we can displays
thing that is also void paint. That means, using the paint method anything you can draw
on the applet.

731
And the destroy method is basically it is the method which is basically to remove and
applet compactly from the memory. So, it is basically closing the applet forever ok. So,
this is the idea about the different methods very simple only 5 method; init, start, stop
and then paint and destroy. There are a few more methods also. Those are basically
standard methods there, I will discuss one by one.

Now, let us first discuss about very quickly about the different methods and how we can
write a code for all these methods in our own applet. Now, so this is simply that using
the paint method as we already used it there, but I will see exactly; we will I will discuss
about the other method like init, stop how they can be incorporated in your applet code.

(Refer Slide Time: 16:07)

Now, here let us have the quick look at this program here. This is a basic idea about how
we can declare an init method in an applet. Now, what is the purpose of the init method?
As I told you the init method is for initializing and applet. Now, what do you mean by
the initialization of an applet? Suppose, whenever you use the HTML code, there you
have to fix that what should be the size of the applet, say 300 cross 300, but the
regarding the program and whatever it is there in one what is called the graphical
display, I want to show many applets here and there.

So, definitely I can reconfigure the size of the applet. So, here is basically from the
program only, we can reconfigure the size of the applet and to do these things we can
take the confidence of the init method. So, here I can declare about, init method public

732
void init. All this method should be public because those methods are public only. So, in
applet everything should be public there is no concept of private, protected or default
concept is there because an applet is publicly useful. So, that is it should be public;
everything is public, a class is public, all methods are public like, the main method is
public. Now, so init method we are declaring and here is the resize method. This resize is
the one built-in method there in .applet package.

So, you can just use it without creating this is basically static methods. So, no object
needs to be created, we can call this method to resize. And resize, it has a 2 parameter
200 cross 200, it indicates that it will be basically allowed to create an applet which has
the 200 size and 200 widths. So, this is the init method that means so whenever applet
will be viewed, so it will be initialized as 200 cross 200.

And then finally, this applet will include the paint method, that is basically again paint
method is that is there in the applet class, we are overwriting this paint method. In this,
this is our own added code we are using this one. That means it will print “Hello World”
at the location 150 150 of this applet.

(Refer Slide Time: 18:27)

So, this is way about init method is there. Now there is a basic you can see the output of
how it will look like this. So, this is the applet code, .java file, compile .class file,
embedded into the HTML file, and finally, if you run this, then it will show this one. As

733
you see, we cannot display the whole thing this is because the applet size that you have
init it is a 200 200.

So, in this case actually it cannot fit the whole thing. If you do it a little bit bigger maybe
the whole the stream can we better so, applet size can be this one. So, this is an example
here we can see, how this to init method can resize your applet view, viewing the
program or when it is running.

(Refer Slide Time: 19:03)

Now, there is also may another application of init method, by which we can provide an
input to an applet. Now, here we can see, how the input can be provided to an applet, for
the second we have to rewrite our own init method here. So, here is an attempt to rewrite
the init method as we see here, this is the init method we are discussing, and these are the
few codes that basically we have mention here so, that it can read the value x value, y
value, w value, h value from where; from the HTML file.

The value because an applet cannot be useful to read, using the standard input-output
mechanism actually, does not allow ok. Applets cannot be directly from the keyboard or
it cannot directly something from the output, stream or whatever it is there.

So, whatever the value that applet can be it will read through HTML file only. That
means these are the value will be supplied, using some applet code, in the applet itself
and then from that applet get parameter will get the value and this value will be

734
converted into integer, and they will store in an integer variable x, y, w and h like. And
then finally, here the drawRect so, it is basically one method that is there in graphics
package, it basically can draw a rectangle having x, y coordinate is basically if this is the
rectangle, this is the xy coordinate and this is the w and this is the h, so these are the 4
parameters needs to be placed.

So, in order to draw and rectangle, so this is basically drawing a rectangle via a paint
method. Now here you can see, here we use the init method to read the value for drawing
a rectangle from the user, rather I can say from an HTML file. Now obviously, the
HTML file should be accordingly, now let's see what is the look of an HTML file in this
case.

(Refer Slide Time: 21:01)

So, this is basically a simple look of the HTML file as we see. So, these are applet code
is, as usual, RectangularTest this is a name of the java .class file and this is the size of the
applet and here these are the code, that is the HTML code I should say that HTML code,
param name, x value, y value, w value these are the parameter name actually and the
value is basically 20, 40, 100 these are the specified value.

This means that x value is 20, y value is 40, w value is 100 and h value is 50. So, these
are the first value through an HTML file to an applet. So, this is the idea about, that how
we can pass an input and then if we run this applet; this HTML file it will basically draw

735
a rectangle on the applet area. So, the typical applet will look like this. So, this is
basically the output is actually that can be there.

If we change the value of this input through this applet, definitely this rectangular size
can be changed and many more other things can be done. Those things are the advanced
features that many more. Suppose, this rectangle can be colored with some color that that
line can be thickened and whatever the things are there, those things are from the paint
method only.

Anyways so, we have learned about how to resize the size of an applet, using the init
method that is there. So, again the same program if we run with the different values as
the output looks like this. So, it basically shows the different value if we pass through
HTML code the different applet will be viewed on the screen.

(Refer Slide Time: 22:49)

Now, so we have learned about the applets and then basic things about the applet that we
have learn about, many more about the applets are on the way of our learning procedure.
Now, we have plan applets we have also learned a lot about the application development
using java, then definitely you can understand what are the difference between
application and applet.

Now, application is a basic standalone program which can be written using any editor
can be stored as .java can be compiled on the success able compilation, it will

736
produce .class file and that the same can be run using Java command. Whereas applet as
we see if you can we can write a program .java, it can be compiled .class, but it cannot be
executed by Java program it should be embedded in an HTML file; and then that HTML
file needs to be browsed by any browser, for example, appletviewer.

So, these are the basic things that we have there. And then an application can include
many things which basically an applet cannot, because the applet has its shown purpose,
has its shown objective, has its shown uses whereas application is totally different. So,
there are two different ways of programming actually. So, usually an application is for
developing some programs which can help us to solve many applications; application
software error, but applet is basically is to provide a graphical user interface. That means
applet can be considered, as an interface and at the backend the application can be
control to run.

So, this is the basic idea about here. But in general, there is a difference between the
application and applet so far, the program structure is concerned. And as you know this
is the structure of an applet is very simple, it has only a few methods like init then it is
basically an init method, stop-start method, stop method, then destroy method, paint
method these are the few methods are there. And then the input section is also very
simple, either java.applet.star or this is java.awt.star or javax.swing, those are swing
package is basically related to this graphical user interface development or applet will
creation.

So, the import section is basically limited to this kind of packages; other than the user's
own package also can be included there. Now, whereas if we see, so for the application is
concerned it has a document section, is a package section where we can define whether
input in a package or creating a package whatever it is there.

Then interface also, then class definition this is main and then finally the main class is
there. And there are a lot of mechanisms as we have already learn encapsulation,
inheritance, runtime polymorphism, binding and then static declaration what is not. So,
many more things that can be included there and whatever the idea that we have learn
including multithreading and everything those things as can be; can be put into this part.
So, this is basically an application.

737
Application is very versatile there, but you know an applet is also less, we will see
exactly how applet can be developed. Anyway, so these are the; so for the basic
structures of the 2 concepts application and applets are concerned. So, there is a
difference.

(Refer Slide Time: 26:33)

And now, there are again a few differences are there. So, for there running is concerned
as we see, an application can include a method called the main method but as we see in
case of an applet there is no main method. So, it can start; from where it can start in fact,
applet class to start it basically starts with the main method which is there. So, it is an init
method if it is there it will start from the init, then start then what are the methods are
there in the paint or whatever it will start in the sequence.

So, there is no main method in applet whereas the main method is must in an application.
And as we see an application can be run independently whereas an applet should be
browsed via and HTML pages through a browser may be applet viewer. Now, again we
can know we have noted that an applet cannot read or write neither from any file from
standard input device or to any file or to any computer display like. So, there are no read-
write facilities that are possible for the applet directly however, we can give input bia in
HTML file.

So, that is also not good to run a return we have to change HTML this one, but there is
again a reason for that, how we can manage it? Now, obviously, there is another way

738
using the event handling that will discuss about whenever we discuss that there is an
interactive way of giving input to the applet also.

Now, again applet for example, application java application can run any program from
its, any program means any class whatever it is there, but applet cannot run any program
from the local computer or from the distance computer remote computer.

Now, as we see applet also cannot allow accessing many libraries that are there in other
packages. It is basically only those are the AWT or applet or swings those are the
packages can be used in the applet. So, there are many restrictions so for the applet is
concerned. Now it is a little bit surprising that, why the applet is having so many
restrictions? Obviously, the reason is there that their objective, their purpose is different.

(Refer Slide Time: 28:45)

Now, it is our turn to run about how the more sophisticated applets can be designed and
can be used and can be developed in many programs. And then, there is all lot of
technology development around ok throughout the year and then there is a very
sophisticated methodology is available for developing applet. So, all these things will be
discussed in our subsequent discussion. So, till time thank you I think you are enjoying
and more on the way we shall learn it.

Thank you very much; thank you.

739
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 35
Applet Programming – II

We are discussing about Applet. We have some basic idea about, how to write an applet
using Java syntax. So, there are many more things also to be learned so for that applet is
concerned. So, today will discuss few more concepts and in the next module also we will
discussed more advance concepts.

So, the applet is very important one what is call the concept in Java programming and it
has many applications rather and so, we will exactly how the more organized way the
applet can be designed.

(Refer Slide Time: 00:47)

Now, before doing that we should have some basic idea about applet. So, basic idea
means, what exactly an applet it is and what its usefulness. Actually, when Java
introduced into the concept programming arena that time, it was a highly requirement
that, how a programming language can supports internet programming. Now, so far the
internet programming is concerned the basic requirement is that how a browser can
browse web page. So, usually the web page written in HTML page, HTML what called
the HyperText Markup Language.

740
Now, HTML can include many things. Here for an example this is the one figure that we
have shown here this is basically web page, right. And then in this web if we see it
contains many elements. For example, this is an image and this is also an image and
there are some text box and there are may be some link like as you see here. So, this is
the link those are the many links, this is basically menu we can say like this one.

So, there are many elements are there. Now, out of these many elements one elements
may be an applet. So, applet maybe we can consider say suppose, this is also an applet
look like ok. So, this applet has its own contents and it basically serves some purpose, it
can if we click this applet or rather you use this applet to interact to the internet this kind
of concept are there.

So, basically the main purpose of the applet is for internet programming and for this
internet programming, we have to create an HTML page; and to create the HTML page
we may use some code to be executed; some programs to be executed and that code that
program is called the applet program actually. So, essentially applet is for this purpose
only.

(Refer Slide Time: 03:13)

Now, so this is the idea about this applet. Now, for this applet programming let us see
how Java favors us, what are the supports from the Java that we can have. Now, in Java
API, there is one package with the package is defined in applet package. So, this

741
java dot applet package we rather say and there is one class called Applet class.

So, in java dot applet package there is a class called the Applet class. So, we can use this
applet class to create our applet program actually. Actually, basic idea about applet class
is what? Exactly, applet class is an abstract class and it has certain predefined method,
those methods are also the abstract methods.

So, if we have to create an applet essentially this will be basically inherited from this
applet class. Inheritance in the sense here is that all the methods which are there in
applet, that means abstract methods are to be overwritten here. Anyway, so this is the
basic idea about writing and applet program. So, we have to import this package first,
this package needs to be import whenever we have to write this applet and then once this
package is imported, then we have to overwrite this method. And here another one thing
is that, applets and the general program has different context in many sense.

The different in the sense that in case of applet as we see we need some separate
program. For example, for the Java application, we need the Java command whereas, for
applet we need the separate program called appletviewer. So, the Java runtime interpreter
called the Java command is not actually applicable to the applet. And again another
important thing is that, Java needs to be opened or the applet program needs to be
executed with a help of browser, like say Hot Java, Netscape Navigator, Internet
Explorer etcetera.

So, we need in order to run the applet, a browser or an appletviewer. So, this is the basic
idea about, the applets and then obviously, the difference between the applets and
application.

742
(Refer Slide Time: 05:37)

Now, how the applet is executed as we say there, in case of applet program there is no
main method or rather there is no main class as it is there in Java application.

And again, the outputting form an applet is also totally different. So, for example, in case
of Java application in order to produce an output on the screen or in some file we use say
System dot out dot print( ), println like. But in case of applet, we need drawstring( )
method, which basically draw something. Essentially applet is a graphical windows or
GUI based window themes, where we can draw many things. So, that is why is call the
painting an applet.

(Refer Slide Time: 06:25)

743
Anyway, regarding this painting and applet we will discuss many things later time. And
one important thing is that apart from this applet being a window based program one
important thing is that applet always an event driven program. So, event driven means,
applet is ready to view something and it can interact with the user. So, it is basically the
user interact with the internet, user can interact with a computer, but this is interaction
through applets. So, this interaction is possible in applet using one another concept
AWT, it is called Abstract Window Toolkits.

So, basically applet and AWT works together. So, we cannot impact for the actual applet
programs AWT and then applet cannot be things in a separate way, both the things can
be consider jointly. So, that is why we have to import the java dot applet dot star, that
means, all the applet class facilities as well as, we have to import java dot awt dot star.
That mean whatever the classes those are defined in AWT has to be there. Regarding
AWT we will discuss in details once the applet is covered.

(Refer Slide Time: 07:39)

744
Anyways so, this is the idea about that applet is basically an event driven one program.
Now, what is the event driven program that can be better understood using an example,
let us have the quick look to this image here, and we see this is basically is an applet.
And actually, if you see care carefully this kind of applets you see in your mobile or
whatever it is there. And this basically is a calculator program, that means, if we can
click 7 and then 8 then plus then 1 2. So, this means that the result will be there.

So, here you see if the click, I said the click. So, mouse click 7 and 8. So, if we click 7,
then basically what will happen, the 7 will be selected or it basically appear here.
Similarly, 8 after the 7, so 7 will be appear here, plus and then 1 and then 2 if we select,
then also those will be there. And then say suppose, the plus this means that, it is an
event. That means we want to add whatever the previous selected, plus the next that will
be going to select. So, these basically call the event driven.

So, here the idea is that, here the different components. These are the basically the
different elements in these applets can be triggered and then once the applets that
elements are triggered and event will be generated. This is the concept of event based
programming. So, applet is basically an event base programming concept.

745
(Refer Slide Time: 09:17)

Now, so we have learned about that applet it is basically the window program
graphically user based windows program and event driven con program actually. So
now, we have to learn about, how this graphical user interface face windows can be
created and then how the event can be generated. So, these are the basic concepts, if we
can learned it and then our concept of learning applet will be completed.

Now, before going to this things let us see, what is the structure an applet usually it can
be. Now so, applet has the some essential components. Now, as I already told you that,
these are the 2 packages to be included, whenever you have to do applet programming.
And then the next thing is that, we have to create your own class, that is your program
and it should be inherited from the applet class. So, our next syntax is basically this one
public class this is your name I mean, user define name and then extents applet. So, that
can be an extent that mean inherited program.

Now, next part the different methods. Now, again there are many methods are there. So,
as we see there is an init method and then the start method and the stop method then
paint method destroy method. So, these are the 5 standard methods that that usually
occurs whenever a program are wants to design their own applet. Now, all these method
again as I told you, these are the abstract method, which are defined in class applet,
which is an abstract class. This means that we have to overwrite this method if we want
to do our own applet program.

746
So, this basically if you want to write applet program this means that you have to
implement the init methods, start methods, stop method, paint method and destroy
method. Not necessarily that all methods are mandatory, all this methods are basically
optional you can use it if you need it.

(Refer Slide Time: 11:31)

Now, so for, so these are methods optional for an example as we see here, in this
example this is the one AppletSkeleton class that we have declare here. And here you see
init, start, stop and destroy are these are the methods basically we have just overwritten,
but the there is no code, is a null code actually so, but method as over written even if we
do not write all these method also, that is also not a problem.

Anyway, so this methods as we see, if we run this applet as you know how to run this
applet using an html applet code this is the applet code to run this applet and these
basically, so an output here. So, this output if you see this output if you see here, this
basically is a applet area and here there is no content and applet is just like a (Refer
Time: 12:21) applet actually, it is not doing anything for us, but it is just viewed only.

So, appletviewer, browse it and then display it on your screen and showing that nothing
is there, no event, no other content, no other elements etcetera. So, this way want I want
to emphasis here is that the methods which we have used, they are mandatory; they are
not mandatory they are optional, but preferably if you want to have them then you should
implement them properly according to your own requirement.

747
(Refer Slide Time: 12:55)

Now, next thing is that, whether all these methods should be written here and there in the
applet program. Actually answer is yes, we can write it is not necessary to write init first
then start then paint whatever it is, but we can write in any order. However the execution
of all these methods follows a specific order. Here for example, as we have seen here, the
applet will be executed if you define all these methods there then init first, once the init
is executed then, start will be invoked and then paint in method will be invoked.

These are the 3 methods if it is defined in your applet program they should be executed
in that order. And finally, the stop and then destroy if they are declared in your program
they should be executed in these orders. So, order is very important as we learn here and
then we will give an example so that we can understand that how the order is important
here.

748
(Refer Slide Time: 13:53)

Now ok, now let us see: what is the purpose of this method; init method it basically used
to initialize the applet. Initialization means, if we want change the background color of
the applet, style of the applet or if you want to do something prior to start the applet. So,
it is basically initialization. Anyway, we will have the detail demonstration, detailed
illustration of this method how they are used; init has very important many important
applications in many applet design actually.

So, we will discuss in details whenever we will consider some case studies. And then
finally the stop start method. So, after the init; that mean, init method is for initialization
it will not do only the initialize the applet and then start is basically starting and; starting
and execution of an applet. So, it is basically usually called after init if it is defined here
and, in fact it is basically call to restart an applet whenever it has been stop. For example,
you are browsing a web page where than applet is there, you just leave these web page
and then come back. Whenever you leave this so, applet basically stop, and when you
come back again the same applet started to execution.

So, it is basically the idea about this method. So, start method.

749
(Refer Slide Time: 15:19)

And then finally, the paint now you know whatever the things you want to include if you
want. So, applet also help allow a user to draw something on the screen using the paint or
cursor whatever it is. So, using this paint; paint is in that sense very versatile one method
with which user can interact with the screen interface and then draw it, even paint can
also displays on screen from the user, the also it can be include many other graphical
component into your applet. So, paint is also very important, init is very important, paint
is also very important in that sense.

(Refer Slide Time: 16:03)

750
And here is an example; this example basically illustrates the execution of order, order of
execution of init, start and paint method. Now, let us look at this program first as we see
here we declare one class, that is the Sample the name of our applet, it basically extents
applet. And here, msg is basically the message that we want to use it, may be a string,
and here you see init method. This is very important here as we see what we have done
here, setBackground and these the color dot cyan. That means, the back ground of this
applet is set as a cyan color and then foreground, the text if you want to display within
this applet.

It basically selected as a red color. And the message is initialized as in that is the with the
screen. So, message is initialize at this thing in side init. So, this is basically the init
method. Now, here the start method, whenever the method starts is execution. It basically
doing nothing only just message is basically updating that Inside start. So, that mean,
message is augmented with these plus this one. And then paint method is if we see; the
paint method doing exactly again message Inside paint and then g dot drawstring(), this
the message that already been write obtained in the store in this message fill, and these
basically print the message.

Now, what is the message right now? So, whenever it is initialized. So, message is
initially in Inside init and then whenever start is executed, the same method will
appended with these method. And finally, whenever the paint is called, the method will
be again appended and the message become Inside init, then Inside start and then Inside
paint and finally it draw there.

Now, having this is the basically, i mean type of the methods that we have dis discussed
here. If we run this, so init, start and then paint and automatically this way you can see
the output. So, that means, it shows that all other execution is first init then, start and
then the paint method. So, this way the execution will takes place in case of applet,
whenever it starts its execution.

751
(Refer Slide Time: 18:29)

Now, further termination there are 2 methods are used, stop and destroy method. So, as i
told you, stop method means if you want to leave this browser and then actually the
applet will stop its execution. So, this is the basically the idea of the stop. Now, stop is
basically correctly stop its view, but not the key completely. So, to do it basically the
destroy method is there. Once the destroy method is used in your applet program, and
whenever this method is invoked.

This means, that it will completely remove from the memory and whenever you open the
browse again we have to reload it, but in case if you do not use the destroy. Stop means it
will be in the memory, but not completely remove from the memory or destroyed it. So,
destroy is basically completely kill the execution of an applet.

752
(Refer Slide Time: 19:19)

Now, here is an example which basically explains, how the stop method works here, but
lot of things basically at this movement will assume. Now, here we discussed one
program or class basically, this class we have discussed here although, we do not have
any idea about, how this frame and everything. This frame is defined in a AWT, let us
assume that we declared one class called the SampleFrame, which extends a Frame.

Basically frame is basically one separate window, that can be included in the applet or a
in a separately it can be viewed. So, frame is basically like this, it is just we can say one
set up applet window like; it is an window we can say. And these frame we will basically
there is an event concept it will takes place ok.

So, without knowing much about these things we assume that, there is a frame will be
created and this frame will just wait for something’s to happen. So, this basically code
will do this. And this is the paint method, as we see in this class, this paint method
whenever it is called, this paint method will draw a string, this is in the window in the
title of the frame actually.

Now, so this is the first part of this program, and then the next part as we see, we have to
define the method that we have declare Mywindow. So, this basically the method that is
declare. Again this method is basically will not doing this thing only whenever an applet
is started its execution, it will basically display the window on the screen.

753
And then finally, this is basically the applet class program and this is the main program
we can say, here we declare the init method. Init method create a frame, this is the f is
the frame. And then this frame is initialized a frame window and then its set size; what is
the size? For example, this; if this is the frame and this is the applet, this is the size of the
frame. And A frame window it will basically show here like this, and here in this is the
string basically paint within the applet, this is the; this is in the applet window.

Now, here in this program if we start, so whenever this applet is run by means of applet
viewer. Then it basically display this one and as we display this one also display frame.
So, both the things will be displayed on your screen. And then so, start means it will do
this things, then it stop (Refer Time: 21:52) for you.

Now, if we click this one then what will happened, it basically invoke the stop method.
So, stop method means it will kill it. So, it will stop, that means this frame will go out
and, but this applet will remain it there. On the other hand, if we stop this applet, then
what will happen? So, this is basically the entire things will go there. So, stopping a
frame means only frame will go out, but stopping an applet means the entire things will
go out.

Now, again so this is basically the idea about that stop means it will be basically close
the view of this one. So, this idea says that, this is the use of the stop method that is there
in the applet. And the destroy method is basically, completely removing this one.

(Refer Slide Time: 22:35)

754
Now, here is an example again if we see; so, this is the definition of an applet class and
this is that complete applet class include. Now, in this applet class if we see; we the init
method, the start method, stop method and destroy method. For the illustration we make
all this method very simple. It basically, use one string and the string will be initialize by
this one and then add item one method is basically called this all this methods basically.

Now, addItem method is defined here, is basically take an argument of the string and it
basically print the string on the console, that means, use as the java console window and
then it basically whatever the strings are there will append it and then basically the just
similar the message concept, that is shown in the last example. And repaint means it
basically, clean it and then paint it actually.

So, this is the repaint; repaint method is basically clear showing the output all the time.
Now, so addItem here for the start staring the applet it will, whenever this method is
called or the applet is executed start will be invoke automatically. And then starting the
applet will be showing, and then so; so then the stop and then destroy will come into the
applet.

Now, here in the paint method, so for the applet is concern; so it will basically draw
rectangle and within this rectangle it will basically draw a string. Now, let us see, the
output of this program, how it look like then you can understand.

(Refer Slide Time: 24:15)

755
So, is basically whenever we start this it basic initialize the applet and starting the applet,
because of this addItem concept it is there go to the console. And also applet will be
there, which is not show here. Anyway, so applet will come there and applet will display
the string on the applet area. And then whenever you stop it, then it will basically stop
the applet and then unloading the applet means, completely clearing from the memory.

So, this way the destroy method will clear it. Now, these are the methods has many
application, whenever we have to have a very complex the web base browsing
application these are there.

(Refer Slide Time: 24:55)

Now, other than this update destroy and stop there is another two very important
methods are there. There called the update and then paint method. So, update method is
basically, just opposite it is on set of init method is basically re-initialization we can say
updating the applet class. So, we can change it as an example as we see, if we define an
update method and then we can change the background color, foreground color we can
do something like this.

So, if we have initialization with some settings by means of updating we can resetting
sort of things are there. And then these update method if we have do it, it cannot be
invoked automatically. In the paint method you have to call it in order to update this one.
So, it is basically update in the paint methods, so it will update it and then after the

756
updation, whatever you can do in the paint method you will do it. So, update is basically
setting changing the settings in your applet

(Refer Slide Time: 25:57)

Now, repaint method is another example here, you want to update it. Now, for an
example say suppose, this is your the entire applet view, these are entire applet. Now, a
particular portion I want to change it, say suppose this portion I want to change it, but
other portion will remain index. So, whenever you drawing some graphics or something
using like paintbrush and like this one, I can select it; and the selected portion I can
repaint it and then there something we can use it.

So, the repaint method is basically, a not the may be entire applets view or a particular
portion of the applet view can be redrawn or repaint it. So, this is the idea about the
repaint method. Now, I can have an example, so that we can understand, how this update
and repaint method works it, there is very interesting program. This program is called
Banner example.

757
(Refer Slide Time: 26:49)

Now, again before going to this repaint has the 3 different constructors. This is the one
constructor without any arguments, so these are another constructor, it shows that which
is the portion. So, it is basically left, top, width and height. So left, top is the one portion
and then weight and then height. That means, this amount of area that we want to do the
repaint.

(Refer Slide Time: 27:21)

And then another constructor, it is basically with some delay, that means repaint and
update should be used together. So, once the repaint is there, then the following by the

758
update is there. So, a time delay we can specify, repaint long maxDelay it indicates that,
what is the maximum number of time in milliseconds, that is should be that applet should
wait before the update is called. So, it is basically, now if you do immediately the effect
cannot be seen. So, that is why some delay should be then repaint. So, that some view,
some impression can be obtained here.

(Refer Slide Time: 27:55)

Now, this can be better understand with an example, it is call the banner example the
idea it is there. So, suppose this is the applet, it can be viewed here but this is fine. We
can run it; once you run it, then you will see this basically the banner will scroll it from
right to left. So, it will change there. So, simple moving banner it will go there and then
it will come here and then. So, base; basically this text will move. So, that is the banner
text we can say.

Now, so do this things here you see we cannot simply use the paint and then redraw
string. So, it is the static paint, but here actually painting will be always update, repaint
and then display; update, repaint and display; update, repaint and display is a basically in
an iterative method. So, that it will appear that this text is moving.

So, that can be understood by means a simple program here let us have a quick look of
the program. First we declare one applet, this is the SimpleBanner extends Applet and it
require set to be executed. So, we implement Runnable. So, it is a (Refer Time: 29:00)
program also. So, applet combined you threading, both the things together here. Now

759
here, so a thread class is created t is the thread class and this is the state int. Now, so this
is one boolean variables stopFlag.

Now, here the init method that we have declare; init methods is doing nothing is
basically changing the background and foreground. So, as the background foreground we
change like this one. And then here is basically the start method that we have declare
here. In the start method we create the thread of this own applet.

So, this thread means, it will run independently until you stop it like. So, this basically,
defining the state thread is basically created, which is the thread means these are thread
of this applet, so applet is thread. And then stopFlag is false, means it is run. So, if we
click some like, so this one stopFlag will be true line.

(Refer Slide Time: 30:05)

So, this is the first part of the applet and then; then the next stage basically, the next
portion is basically run as you know this is the thread program. So, thread should be
accompanied with say run method. This is the run() method here and t.start you know;
you see this start is basically starting the thread not that the applet start method. So, that
is the totally different as you have implements runnable. So, start will automatically; that
mean, we start the execution of thread. So, in the start method of the applet, we start the
thread.

760
Then run method if you see, this is the more intelligent one code actually here. This run
method what it will do is basically, here initially it will repaint, whatever repaint means
initialize repaint is there, then thread will sleep for 250, because some weight to be there.
So, that user cannot, otherwise if you constantly change you cannot find that change
right.

So, delay it is there. So, this is the sleep means, the thread will just wait without doing
anything and then the character will be corrected from the message; that means, fast
corrector from the strings of the characters and then message it will basically next is the
message will be obtained by competing the substring of the next corrector of 1 to the
maximum 1.

So, basically each time, say suppose welcome; so first character is wel then the next
substring basically, after preponing w e l c o m e like this. So, this will basically the run
method as the thread will execute. So, it will go on, one by one, one by one. So, it will
take 1 character at a time from the front 1, and then get the substring, and then substring
will be displayed the next and then again it basically update it and repaint it.

So, this way update and repaint will be go on go on and the idea it is there it first is A
and then A will move here, then simple moving will come here, then this will come here
and then other portion will be there and this way that that applet will start moving. So, if
we run it and then we can see this actually applet gives a life to this and then is a
beautiful one program that you can check it. Anyway, whenever we will give the
demonstration, we will show its execution. Then stop here, so whenever stop means say,
suppose user select this one. So, the stop will be invoke and then stopFlag is true then
thread will stop and then the applet that the banner will stop its execution.

Anyway, so basic idea that different methods, which are there in an applet like init, start,
stop then paint, update, repaint all this methods we have try to give an idea about, how
these methods are there. And whenever you run different application, different program
you can innovate also, different way of viewing the different applet you can see. And
more over, all those things also will come into great effect whenever we develop a
calculator. So, will see exactly in our demonstration, how all those advance applet can be
designed and then those methods will be used to do that.

761
(Refer Slide Time: 33:11)

So, these are the methods we have discussed there and so fine. So, these are the methods
last standard methods. Apart from these standard methods, there are many more method
also can be any method also user can implement and add into the applet. And all those
things, we will discuss whenever we will discuss more advance features about applet
programming.

Thank you.

762
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 36
Applet Programming – III

So, we are discussing about Applet. And in the last module, we have discussed the
standard methods which can be included in an applet. Now, we will discussed about the
HTML concept, as you know an applet cannot be executed independently. So, in order to
view an applet, we have to host this applet code into an HTML page. And then this
HTML page will be browsed by means of a web browser like say Internet Explorer or
Netscape navigator or the hot Java browser. And in Java JDK, there is a built-in viewer
also called the applet viewer.

Now, whatever it is there, first the idea is that applet should be hosted by an HTML page
embedded into an HTML page. So, in this module, we will see how this hosting is
possible using HTML contact. Actually, one specific tag that is there in HTML; HTML
stands HyperText Markup Language is called the applet tag. So, we have to discuss
about applet tag here.

(Refer Slide Time: 01:30)

Now, so applet tag is basically let us first see exactly how a typically an HTML page
looks like. Now, here you see HTML is a basic tag-based as we said, now this is

763
basically HTML, and this is the end. So, these are the tag, it is called the HTML tag that
means, this indicates that this is the HTML page 1.

So, if this is the tag and then browser use it no issue, the browser will see the blank page
here, because it in this tag nothing is there. Now, the next that we can do is that head. So,
head is basically we can write, what is the title that will be there. So, head is basically
with one HTML browser will show it, here the browser view is not there. So, a simple
HTML file if you use it, the browser will show that.

And then within this body, we have a text is a header 1, header 1 is a very big font large
font. So, this will display here in the header font. Now, you see there the different tag we
are using, so this is another tag B. So, B tag indicates that, it will display some font in a
bold as well as I tag to indicate that italics. So, this basic text will be displayed both in
bold and italics form.

The next tag is H 2, H 2 is the text is basically small tag. And here not H 1 is the very
bigger font, H 2 is a little bit smaller medium size font, so this will display here. And you
see there is another a ref is basically link, so this is another tag a, and then closing tag.
So, every tag is here starting and then closing syntax. And then these basically see the
link that means, from there this is the hyperlink if we do it, so this and in this basically
hyperlink. Hyperlink means if we click it, it will go to this link actually that means, it
moves to browser moves the focus from this link this page to some other distant page.

Then there are many other images also can be included in the text. And in order to
include an image, so image img is the tag for that. So, these basically display this kind of
image on your screen. And the comment if you want to include in HTML, it basically
comment will be included within this angular, then exclamation then dot, and then it is
closing is this one.

So, these are the few tags that I have shown here, so that how the HTML page can be
designed using the tag only. And the browser is basically run and HTML page. So,
browser running an HTML page, this is basically in an interpretative manner. So, it will
basically the first tag, then second tag, next tag and so on. As it is interpretative not
compilation nothing is there. So, if there is any mistake in these tags, say suppose H 1 is
there, no closing this one, so this means that this will completely ignore. So, the browser
will not do anything ignore, it does not mean that the next portion will not be executed.

764
So, the next portion will be interpreted and executed. So, it is an interpreter, and it will
see every tag, and interpret every tag, and then display or paint on the screen. So,
basically, the browser will paint on a window actually. So, this is basically the HTML
page concept, and one more important thing that HTML tags whatever you can it is a
case insensitive whether capital letter, small letter, it does not matter for the browser, the
browser will do it correctly. So, is a case so is whether lower case on an upper case that
is not the issue there; so, this way the HTML page can be executed there.

(Refer Slide Time: 05:09)

Now, we have discussed about the different tags. There is one special tag that is called
the applet tag. So, this special tag is basically to include the code that you want to
include in an HTML page. So, the tag looks like an applet, and this code indicates that
what is the class file in the Java class compile version of the Java applet program.

And then this is basically width and height that mean, it shows that what how much size
of the applet would be in the windows that the browser will take to display your applet.
So, these are the very nominal applet tag concept that is there. And then you can use it,
and you can so if you can do it, your browser can run your applet from the machine
current machine.

765
(Refer Slide Time: 05:55)

Now, so this is the idea about, but there are few hinge is there is that now applet is little
bit disregarded in the sense that many browsers, they do not support until unless you use
a special plugin for that. However, the chrome totally ignore any applet tag in the HTML
page. Internet explorer till version 4.0, it was supporting and after that, it stops
supporting.

Then Mozilla can supports if you use one special plugin for that. And this is the Netscape
navigator, it always favors the applet code applet tag in an HTML page which means,
Netscape navigator browse successfully. And the opera is another browser also which
does not support it. So, many browser they do not support many browser support
conditionally under the usage of the plugin, whatever it is there. So, these are the basic
restriction, and restrictions there is a certain reason for this kind of restriction, mainly it
is from the security point of view. So, many browsers have stopped supporting applet
code in HTML.

766
(Refer Slide Time: 07:19)

Now, see applet code; whenever it was initiated initially, applet code has many other
parameters for the complete specification of an applet.

(Refer Slide Time: 07:33)

The parameters that are there in an applet code are like which are some specification
optional, and some are necessary. Those are optional, which are written in the square
bracket look like. So, for example, this is the applet tag initial, and this is the starting of
the applet. And there if you see within this there is a few portions which you can include,
and then this is in the applet portion; so, this is very important. So, this and then curly

767
brackets is basically the different parameter that the applet tag will allow to specify for
the special viewing of your applet. So, this is there, and what is the special thing that can
be here you see.

And the codebase is the one parameter, archives are their code already we have
discussed, then an object, alt, name, width, height, align, vspace, and hspace are the few
things that we have. And apart from this param name also somethings are there. If the
param name is there, then separate angular brackets should be used for each parameter
name. Param name probably for passing parameter or passing input from HTML page to
an applet, we have discussed you can recall.

Now, here we can see out of this different specification that is possible for an applet, few
things are mandatory. These are code, width, and heights, these are mandatory that
means, you have to give it. If you do not give it, your applet the tag will not be executed
by a browser successfully. Whereas the other the code based, archives, object, alt, name,
and align, all these things are optional. And then param name also optional, you can have
you also may not have it. So, these are the different tags specification; so, for the applet
tag is concerned are there.

(Refer Slide Time: 09:37)

Now, in our next few slides, we will see exactly what is the meaning of each
specification in the applet tag?

768
(Refer Slide Time: 09:39)

Now, these are the ok, I have listed the few things that you can take your own time to go
through, and then understand about it, but I will give the detail description in next slides.

(Refer Slide Time: 09:47)

And as I told you HTML also has the different versions. And HTML5 onwards, the
applet tag is not supported. Rather instead of applet tag, they supported some other
concept, it is called the object, I will discuss this thing.

769
(Refer Slide Time: 10:07)

Now, first is basically the code. Code as it is the as you have learned it, within this
applet. The code indicates that what is the class file that you want to include width and
height specification. So, this is the minimum portion that it should have in your applet
tag to run an applet.

So, this is basically code is there. And then code is basically here one important point
that you should note. Whenever you run an HTML file hosting a class file, it basically
requires two things. The HTML file itself, it should be saved somewhere, and then
the .class file should be saved somewhere. So, if you do not specify anything explicitly,
then your browser assume that the .class file and HTML file belong to the same
directory.

If you want to explicitly mention that it is not in the same directory, but somewhere else,
then we should use the codebase. So, codebase usually accompanied by code, if you
want to tell that the HTML file is here, and then code is somewhere else. Regarding
codebase, we will discuss the details. ah

So, and another thing is that, so for the width and height whenever it is the applet code, it
is not necessary to maintain in this order. It also can be in any order like here width,
height. And also another thing is that this is the width in pixel, those things also not
necessary to put in a double quote, but is customary to for improving the viewer view
(Refer Time: 11:51). So, we usually put in the double quote, but this needs to be put in

770
the double quote always. So, here is an example like, so this is also correct, and this is
also correct. So, these are the code and this code and with height and width are the
mandatory things. Mandatory means, you have to use it without using you cannot do
that.

(Refer Slide Time: 12:07)

Now, let us come to the concept of the codebase. So, codebase is basically showing the
relative address of your or base address of your applet. Now, what exactly the idea it is
that if you want to I mean import your class file from a distance machine from your local
other than your local. So, browser from which machine it is browsing, it is called the
local to that browser. And if you want to have access from some distance machine
remote machine, then the through a browser that can be connected.

Here is an example say https indicates that it is the location of the remote repository,
where this class file is there. So, this means that your browser will connect to this size,
and then check this that class file import it into to your local machine, and then this
applet code will be executed. So, applet code is not necessary to be executed from your
own machine from the distance.

Usually, in case of internet programming, we are we have to do that. You can import
your HTML page from the remote machine, and importing means all the class file
applets, all the image, all the audio, video files, whatever it is required. Needs to be
fetched into your browser machine, and then it will be executed there in your browser

771
machine, so the codebase is for that purpose. We can explicitly mention that which is the
location where your class file is there.

Even if you use the same thing in your own local machine also, but it is that the HTML
file is in belongs to one directory, whereas the class file belongs to the separate directory.
So, the base is basically here, which is the base directory and with respect to this base,
which is the class file that you want to use. So, in the codebase also that we can use it,
but in that case, we have to use the file command here. So, file and then the location of
the directory, and then the name of the class file that you want to use it. So, this is the use
of the tag the codebase.

(Refer Slide Time: 14:29)

And the archive is there for this purpose is that say suppose, as I told you applet can be
viewed from your local machine containing its elements from the distance machine. If
you want to do that, then every time you want some things to be included in your applet,
it needs to be connected to your remote machine and then import it, and then store it, and
then display.

So, instead of whatever the files that are required for that HTML page, you can put into
an archive in a jar file it is called here, for example, all files that are required for an
HTML page can be put into one jar file. Then the browser that it will do is that the
browser will import only once with an only a single connection to the remote server, and
then fetch it into a local machine.

772
And then from this jar file whatever the file that is required image or video, audio or any
other class file will be extracted from there and will be referred to this one. So, this
archive commands will basically give an idea about that which is the jar file that needs to
be fetched only once in a lifetime of the viewing. So, this is an idea about the archive tag
specification in the applet code.

(Refer Slide Time: 15:54)

And then object. Object as I told you HTML5, and upwards version of the HTML, they
have stopped supporting applet code. So, in that case is basically allow to use the object
code. So, object code is the same as the applet tag actually; so an applet is not there. So,
here basically the same instead of applet, you use the object that is all; so, this basically
the idea about. And other code-based, then width, height everything is applicable to that
only. So, an object is an alternative to an applet tag that is the newer version in the
HTML page.

773
(Refer Slide Time: 16:32)

And here again if you want to suppose, you do not know whether your browser will
support, whether HTML4 or HTML2 or HTML5 or upwards so, sometimes to make it
more robust for images or compatible with any versions; so some HTML designer used
both objects as applet code here. For example, an object is there here, and then an applet
code is also there. So, if it fetches for the, for example, HTML4, you want your browser
supporting HTML4, then object will not be applicable to that HTML browser. So, in that
case, you can use this one; so all these will be ignored, but an applet will be considered
in that case.

On the other hand, another version which supports HTML5, then the only object; so, this
will be ignored by that browser, only this portion will be considered, and the applet that
file will be successfully browsed. So, this is the idea about that both object and applet
can be merged together, to make it more compatible with your browser system.

774
(Refer Slide Time: 17:44)

And width and height as I told you specification of the height and width by changing this
parameter, we can resize your applet view, and that can be done from your applet from
the HTML page itself, so that is why the ok. Before viewing the HTML, so HTML will
be footed in front of within a set of text in a multimedia document like it can include
audio, image, and then video also, in addition to the hyperlink text, hypertext we can say.

And then the applet is basically a window within this text also, it appears as a living on
things for the browser. So, in that case, we can specify the width and height, how much
space of the total view area of your display that it will take to display your applet. So,
this is the width and height is an essential one parameters ok.

775
(Refer Slide Time: 18:49)

And then the alt. Say suppose your applet, there are some mistakes in your class file or
there is a problem that it is not able to load it successfully, then the browser can give
some message to the user. So, here the message that can be given by means of all
statement. In case, suppose this is a problem right, your browser faces the problem of
fetching this class or executing this class file, then it will be there; otherwise, this will
not be executed.

So, this is basically for giving users good interaction or impressions about viewing a
page. So, alt statement is used there. So, alt is basically an alternate text within this
double quote that can be used. And you see one thing here all these things will be within
this applet tag, whatever this codebase, code, alt, width, height, name whatever it is
there. Those are the within this applet state and finally, this is called the final applet tag.

776
(Refer Slide Time: 19:55)

Next is the name. And in your HTML page, you can use many applets into the same
HTML page or sometimes applet can be used in a distributed programming system also.
From your machine, you are running an applet. From another machine, another user
running, another applet and both the applets need to be communicated to each other. And
for this communication, so that actually one specification that is required that which
applets communicate to which one that mean, each applets should have their own
identity; this identity can be mentioned by means of name.

So, name is the one specification that is there by which we can specify that if each applet
has its own unique name. And then by this name the applet in your applet programming
using the method get the name of the applet can be understood, and using this under say
some communication can be established or some communication protocol can be
implemented, so that is why the name that specification has been there in the applet. And
then so name can be obtained by the getApplet method not get name ok.

777
(Refer Slide Time: 21:17)

So, these are there are a few more method tags align. Align means you can view your
applet in a particular position. For example, these are so many positions left, right, top,
bottom, and absolute bottom, whatever. There are many other specification that you can
find you can mention, so that applet will be placed accordingly whether left side, right
side, top, bottom absolute top, top of some text like this one. So, these are basically
placing one applet in an HTML page HTML area view windows that are browsed by the
applets.

(Refer Slide Time: 21:51)

778
And VSPACE and HSPACE is basically the use of this say suppose, this is the total
HTML view of your total HTML page. And there some text like, and here also some text
like and where you want to display your applet like suppose. Now, so VSPACE,
HSPACE is basically how much gap that you want to give between the text and this
applet. And so it is basically VSPACE.

Similarly, if there is some other text, it is there or some other applet is where you want to
place it, then this basically HSPACE means what is the gap that you want to allow
between the text or this one. So, is basically VSPACE, HSPACE totally is say that other
than this is the applet view, this is the width and height is basically how much space that
you want to do it. Sometimes it is basically used for a good impression of the applets,
and then an artistical presentation of this applets that in there is HTML that can be
controlled using this VSPACE, HSPACE commands.

(Refer Slide Time: 22:59)

And parameter name param is another important parameter, extensively used one
parameter that is required to specify the input to an applet as you know an applet cannot
take the direct input from the browser machine or cannot take direct input from the
distance machine also. So, if you want to pass any input to your applet, then in the
HTML page the parameter names to be mentioned there.

Now, the syntax is like this. The tag specification is called the param, the name of the
parameter. For example, in this example, as we see the font name is the name of a

779
parameter, and value is basically the courier, so that means, this is the parameter the font
name the value is courier. Then font size is another parameter, whose value is 14 at
present. The name is image source, the value is basically the file location.

And then name is another is that audio source, the value is this one. So, here we can see
these are the different parameters, whose values are like this which we want to pass from
this HTML page to this applet when it is in execution. So, whenever the applets start its
execution, it will refer whatever the parameter that is mentioned there in this HTML
applet code will obtain the value from here, and it will use it.

So, for this purpose the parameters concept param tag is there defined there. And this tag
you see this is an applet, an applet is there, this is the applet part. Yeah, this is basically
the applet tag, but within this applet tag, separate parameter tags are to be mentioned
there. So, and then whole the things will be basically the applet tag for the HTML page.

Now, so param name, so how an applet can get these values. So, for this purpose, the get
parameter methods are there defined in the applet class, and which can be called for this.
And then can be can get these values from the HTML itself. So, if you change this values
from your machine, and then this will display the different values to your applets. Now,
let us see one example to illustrate the use of this one. And this is supposed the HTML
page that you have defined, and my class .class is our applet, which basically wants to
take input from this value. And then how the applet code will be there.

(Refer Slide Time: 25:40)

780
Now, here is the applet code which looks like this here if you see the paramdemo is the
name of the applet, which you are going to demo it, and these are the different
parameters called the field of this class like fontname, fontsize, leading, active. All these
are the variable as we have declared in a class; so this is the class members.

And here you see the methods start is basically to be either it is in the start method or
initializes method, you can read the value. So, here, in this case, we can read the value
from the start method or like this one. Now, here as you see all the parameter values that
will be read from the HTML page, they will read from a string. So, let the name of the
string be param and read. And then from this parameter string, we can convert into a
different form.

So, is a get parameter font name, which is there in an HTML page, you will get this and
then font name will be there. So, this is the basic parameter that is there font name, font
name from a courier. So, the value will be there, so the font name is currently the courier.
And it is basically the try-catch is mentioned, if in case suppose, this value is not present
in the HTML page like this one.

And then so there is another param is if you want to convert in integer also, because it is
read as a string, so we can change into integer. So, integer class, then present, it will
convert the string to an integer, so font size, and then this one ok. Now, so this way as
the different parameters, there are few more parts of the text that are there, code is there.
The different parameters can be read using this get parameter method is there.

781
(Refer Slide Time: 27:31)

Now, other parameters also gets parameter leading and then get parameter account to
enable. All these values will be read from the HTML page. And then the once the value
is loaded into your applet, and then we can use them in your paint method; so, here is the
paint method. And you see whatever the value that we could read, it from the HTML
page like font name, font size, reading, and active.

And then they can be printed on the screen like in this case, and then if you run this
applet using the HTML file that we have previously shown, it will basically like this one.
So, what we want to say here is that whatever the parameters, we want to pass from an
HTML page to an applet, they can be embedded into the HTML page itself within the
applet tag by the special tag specification called the param. So, this way we can pass the
parameter and we can run this like this. So, usually the HTML page designer have this
provision to pass the different values or there are many other ways also, it can be there.

782
(Refer Slide Time: 28:46)

One good example that we can have it, then we can see the applet is ok, it is just a
windows program. And this is the HTML page for this applet, it will look like.

(Refer Slide Time: 28:53)

The applet finding an applet size; now sometimes it is required to interact with the applet
size which some situations, then we need to know what is the current size of the applet.
So, the current size of the applet can be understood using another method called the get
size, which is defined in applet methods are there. So, this basically get the applet size
like.

783
(Refer Slide Time: 29:18)

And this example says for a current applet, what is this width and height parameter that
can be read here.

(Refer Slide Time: 29:26)

Now, there is also another method is also in an applet is basically called the show status
method.

784
(Refer Slide Time: 29:34)

So, here basically the idea is that this basically showing the status of the applet. If the
applets started its execution, it is called the applet started. If it is destroyed, it is applet is
stopped or killed or if it is applet is not yet started like not started this kind of. So, this is
called the status bar of the applet, and this is the title of the applet. Now, sometimes the
show status, we can for some reason that we want to display our own, what is called the
message on to this one. So, this can be done using the show status method.

(Refer Slide Time: 30:19)

785
And here is the one simple example, how this show status method can be utilized. Here
you see this method can be used here show status, and this string. And if you run this
applet, then it basically shows in this status bar there that this is shown in the status
window like.

(Refer Slide Time: 30:40)

So, this is the different methods are there that can be used to display the status concept
here. And there are a few more interesting facts that I want to give, before concluding
this module.

(Refer Slide Time: 30:53)

786
And let us see the first is HTML file is always necessary to execute an applet that means,
as I have mentioned that HTML code should be there, an HTML file is there, but there is
a trick that the tricks are basically HTML applet tag can be directly embedded into the
Java program itself. And then that can be used by the applet viewer actually.

Now, what is the policy it is here that means, whatever the applet tag, it is there? You
just write after the HTML file, either after or before whatever wherever it is there as
shown no problem. Then same .java file can be used, so no need to maintain two files.
One is the .java file or .class, and then .html, but only one .java, and then the
corresponding class file should be there complied version.

(Refer Slide Time: 31:43)

Now, here is an example as you can see here, this is the applet program that we have
already know; so, this is the .java file. And here is the HTML code, which basically to
host it. Now, I can maintain only one file, and then let the name of the file is .java. So,
this is the .java may be status window .java is the name of the applet file compile it.
Now, whenever you go for compilation, those are the things included within this
comment which means, your compiler the Java compiler will ignore this one.

On the other hand, whenever an applet viewer will come into their, applet viewer will
ignore, all these paths because an applet viewer cannot understand about this tag and
simply ignore it is just interpreted. But, whatever the portions it is there, applet viewer
can understand it, and then can be interpreted.

787
So, if we run this using applet viewer for example, here run it applet viewer status
window .java. So, here you have to write .java, this is an original file right. So, then as
the applet viewer will browse it, and then displayed. So, only one HTML file that you
can plan only one dot file only .java file can be maintained, and then no need to maintain
explicitly .html file. So, this is the idea about and many programmers prefer to do that,
what is the code HTML tag it is required, they usually use in the .java file within the
comment lines only; so this is the one.

(Refer Slide Time: 33:25)

And another is that it is applet the only way to create a graphical user interface or there
are many other ways are there. In our next discussion, we will discuss about the AWT
the Abstract Windowing Tool kit. The abstract windowing tool kit allows us to include
our code here. So, using this one also you can do it, but regarding this abstract window
tool kit, we will discuss all these things in detail there.

788
(Refer Slide Time: 33:52)

(Refer Slide Time: 33:53)

So, it means that in your program, you can write one application look like, it is not an
applet actually. But, it looks like an applet, it is basically called the frame or panel, and
that panel is basically a windows programmer. So, these are another version of the
windows program, which can come in the form of an AWT programming.

789
(Refer Slide Time: 34:07)

And this is the one AWT code that will be discussed in details, I just want to skip it.

(Refer Slide Time: 34:16)

And so this way we can run another windows program, other than applets. So, AWT is
an alternative to the applet programming actually. And applet regarding AWT
programming, we will discuss in our next module onwards. And then will discuss
another programming concept in Java the AWT concept.

Thank you very much.

790
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 37
Demonstration – XIII

Let us have a quick demonstration of few important facts so far the applet programming
is concerned. So, in this demonstration we are going to demonstrate you few things about
the different methods that can be included in an applet program.

(Refer Slide Time: 00:32)

Then we will see exactly the html file details, about the detailed html file needs some
more time. So, that will be covered in our next demo and there are some issues very that
is also we can say that interesting fact with the applet programming also will be covered
here in this demonstration.

So, let us first have the first demo regarding the simple applet java execution. Applet
execution is concerned we have already familiar to our HelloWorld, program.
HelloWorld Applet, so as we know so far the applet program is concerned we have to
import two packages, namely applet package and then awt package.

791
(Refer Slide Time: 01:21).

So, in your import section these two packages should be there. If you do not import these
two packages, you can face compilation error and in this applet as we will see exactly
there are many more methods, but in this particular applet, current applet as we see only
one method the paint method it is a vital method in any applet programming and this
paint method includes, so this paint method includes drawstring and this is right.

Student: Application.

Later

Student: No sir.

Ok. So, these paint methods include the drawstring methods and it basically display a
string HelloWorld in the paint area at a particular location called 150 is the vertical and
horizontal 150. So, this will display. So, these are the contexts already you have familiar
to this kind of applet program anyway. So, this is the first applet program and very
simple the most simplest applet program that we can have, but actual applet program is
not so, simple that we learn in our course of demonstration anyway.

792
(Refer Slide Time: 02:32)

And the two things there you have to write the applet code using the html, using the java
syntax and then, this applet code needs to be hosted using an html page following the
html syntax. So, two programming languages are involved; html and another is java.
Html stands for hypertext markup language as it is a tag based and in html this is the
<html> tag. It is there showing that is the html not necessary to be included here is an
optional, but this is the optional here that applet tag, and this <applet> tag the two
mandatory specification called the code specification and then, width and then height
specification. And the code base is also there although it is not mandatory. So, code base
if it is not mentioned explicitly, then it indicates that this class file, that means the java
program and this html file itself belongs to the same directory.

And we assume that this file and the dot, dot, this .class file and the .this html file if we
save it, should be in the same directory and then we can use any applet viewers.

793
(Refer Slide Time: 04:01)

For example, if you use the applet viewer, the applet viewer and the name of the html file
which basically hosts your class file and then it will display.

(Refer Slide Time: 04:05)

The applet and then the whatever the paint method is defined accordingly it will do the
job.

Here is an example as we see this is an applet view with a specification of width and
height that we have given there in your html page shows the applet completely. So, this
is the first and then simple most example that we can see for the applet programming

794
here. Now, our second example showing the different methods rather I should say the
standard methods. There are few standard methods like init, then start, then paint ,stop
and destroy. In this example we will see if these methods are mandatory or not, ok.

So, the methods are already defined in an abstract class called the applet. So, as you see
this is the Applet abstract class and as you know your this is the applet program you have
to give the name of this class as a Sample. So, it is the applet program and in this class
basically inherits the abstract class called the applet which is defined in java.applet
package. So, this class abstract class is called abstract because it has certain abstract
methods like say init is the one abstract method. Init is the one abstract method and then
here this is the start is another and then, paint is the another abstract method.

Init method does not require any parameters as an argument start also the same, but for
the paint method it always should be accompanied with one parameter of type Graphics.
So, Graphics is the class which is defined in java.awt and then, g is an object of that.
This parameter is required anyway. Now, this is the one method that we have discussed
here and we have to this one this class, ok. So, this method if it is there, anyway no issue.
So, this method if we there and this example will show that all these methods we have
over written here and the method over written is basically in init method as we see. we
just initialize the applet with background and foreground color.

The setBackground, setForeground these are the method is defined in java.awt and then
this is basically the string we have assigned, the string. The name of the sting is msg and
then its value is this one and in the start method as you see the method which is already
there in this init method will be appended by this one and here in the paint method it is
there.

Now, this program say says that it has 3 methods and then, the order of execution as
already we have discussed that init will be invoked first followed by the init, the start
will be invoked and then, the print will be invoked in this order. Now, this order of
execution if it is invoked so message will be fast initiate Inside init, then it will be
appended this message by inside start and then, in finally in the paint it will be again
inside init followed by Inside start and then, Inside what is called the paint and then, this
message will be then displayed by the paint method using this method drawstring into
this applet area.

795
Now, so this is the order right if and also in the initialization we see background will be
cyan and then, foreground. That means, the font will appear in the red color.

(Refer Slide Time: 07:59)

Now, let us run this program compilation with the java and then a hosting in an html file
and then compilation, ok. We can compile using applet viewer. So, applet viewer then
the name of the html file let the name of the html file is Sample.html and as you see fine
just come here, ok. So, this applet as you see the foreground color is red font and then,
background design and then this is basically this one as you see init method is executed
fast that is why message is there, then the start method and then finally paint method.
That is why this thing come into the paint method and ultimately it is showing there. So,
the ordering is there inside, then start and then paint that is the important thing.

796
(Refer Slide Time: 08:58)

Now, let us again see as I said already that all these methods are not necessary to be
defined by the programmer. It is mandatory. If you do not use this method also it will be
there. Now in this case for example we have overwritten, however overwritten without
any code the void this program is also one sort of overwriting and if we run this program
again applet viewer and then, this program if you run it and we will see as you see this
browser just little bit all right.

So, as you see here there is no setting so far, the initialization, background, foreground
because we do not have any code. So far init method is concerned no start, no paint
nothing is there and that is why it is a blank applet. So, is a that applet does not contain
anything else.

Now, so here you have overwritten although there is no code, but here also we can write
an applet program also without any code itself. So, I just want to comment all these
methods there and then let us commence this program.

797
(Refer Slide Time: 10:16)

So, this is the one see this is also one applet program, however this program does not
have any method definition, but still it is usable and this is a html file hosting this one
AppletSkeleton2.class. Now, we can see it, it will give it will not show anything, but
applet will be browsed, applet will be open, applet will start, actually applet will start
although without any valid execution valid content in it actually, fine.

(Refer Slide Time: 10:42)

So, as you see the same thing. So, applet is running applet has started, but without any
content in it now. So, we have discussed about 3 methods init start and then, paint

798
method and then, there order of execution and also we have mentioned that all these
methods are preferably to be overwritten, but not necessary. Now our next example
showing the use of stop method in an applet 4, right.

(Refer Slide Time: 10:32)

So, stop method as you know that this method will stop execution of an applet and will
see exactly one another form of the applet programming here and we declare first a
frame is basically the concept of awt.

(Refer Slide Time: 11:48)

799
Although awt is not covered and so, let us assume that this basically a frame will be
created and then, frame will be displayed and this frame used one event called the
WindowsAdapter event, ok.

Let us assume that this code basically it will create a frame, that frame can be created by
an applet. Our next part of the program code that is basically including this one frame.
So, here this is the main program main applet program we can say here, ok. So, this is
the main program here that applet frame is a extend applet. So, this is the AppletFrame is
our main applet program. We have the init code here.

The method, this method basically create a frame, the frame which is already discussed
earlier and then, the name of the frame object is f, the frame objects and we have just a
frame window a message that will be appeared on the title on the top of the frame and
this is the size of the frame that will be there and then said visible this is the one concept
that is required to make the frame visible and then, start method.

As you see it is very simple set visible true. That means, we make it and then stop it
basically f dot set visible false. So, whenever we just stop, we invoke the stop method in
there.

Now, one more thing is that init is implicitly invoked, the start also implicitly invoked
whatever the stock can be explicitly needs to be invoked in your applet. If you do not use
it, then applet will go on starting I mean viewing displaying, its content like this one.
Anyway in this applet method again paint is basically the simple. It will display this the
string in your applet area. Now, if we run this program successfully compiled and then
we are running this program and you will see exactly how the stop method come into the
its effect. In earlier applet there was no stop method declaration. Now in this applet, we
have used the stop method here we see that.

800
(Refer Slide Time: 13:59)

In this display as you see two things are there. Whenever you started this one, this is
basically our usual applet. Applet started and this applet basically invoked another frame
which is already in the applet init method. This is the frame and this is the title, it is
applet that is called the this is the frame right and then, within this frame some string is
there which is not displayable properly and this is basically the string that is painted by
the paint method there.

So, now here the applet is now in starting and in execution is active applet we can say.
Now, we can stop it. If we stop this one, then this frame will go on, but applet still is
running. So, if you stop it here then it, so that frame is no more exists and it is stopped
means we have to invoke it later on again running the same program. Now, here again
applet as you see applet is still running and if we just click it, then is basically it will stop
the applet execution. So, it is basically stopping the plate and here you can say applet is
stopped here and then cursor returned to the control command here.

Now, on the other hand if we stop the applet, so applet that mean thread will stop
everything all together. Automatically frame will be ceased to exist. I am stopping it here
and you see both the frame as well applet now no more exist. So, this is basically the
concept of stop. Stop is there in another context also. The stop method coming to the
play say as you see html page hosting an applet view, if you stop if you close the html
page, then what will happen this applet also will go out. Now, again if we run the same

801
applet, then the same applet will be displayed. So, that means stop does not make the
does not mean that it is stopped permanently. It is just from memory. For temporarily it
is not there, but in the memory it remains there.

(Refer Slide Time: 16:13)

So, in order to move this applet completely from the memory, we have to call the destroy
method. Our next example will explain this concept that how it can be clean completely
from the main method, main memory. Now, here you see this is another example of
applet as you see as you see here. So, this is the applet life cycle, this is the name of the
applet program here, inherit the applet class and it is basically used a string and also it
used add item on method.

The method is declared here in this part is basically just do two things. It print on the
console area as well as print on the applet string using the repaint method and it has of
the start. Start basically call add item using some string as an argument because this add
item require a string to be passed. The stop also doing the same thing and then, destroy
also doing the same thing. Call all three methods, called the addItem method. addItem
method basically display one string on the console control window, another is it display
some string appending all the strings there in the applet area.

802
(Refer Slide Time: 17:40)

Now, so here it basically as you see here in this program we use four methods; init, start
stop, destroy and then obviously paint method is there. All four methods are there in this
particular applet example and then, paint method is basically draw a rectangle and then,
within this rectangle it will draw a string within that like that. Now, let us see how this
and then, the repaint method here again. Repaint means whatever the previous content it
will be there, it will basically update and then the repaint in the fresh way.

(Refer Slide Time: 18:19)

Actually now if we run this program again using an applet.

803
(Refer Slide Time: 18:22)

Viewer let us see how it will look like this. Now here two things are there. You just I
taken here just come into for this one here, now here there are two things that you should
note it here.

So, this is the console area and in the console area you can note it is giving this
initializing the applet because of the init method that is there and then, also starting the
applet because these two methods are called automatically whenever the applet has
started and then it is also showing the appended text initializing the applet and then,
starting the applet as you see.

Now, we do not have any destroy or call any methods are there. Now, if we stop it then
the stop method will be in execution and this method will execution means, but a stop
method will call the add item. So, add item will just display it, but as it will the applet
will be no more once it is stopped. So, that will be no view actually. Now, let us stop it.

As you see here stopping the applet and then unloading the applet, those are the basically
by virtue of call of the stop method and this is the by virtue of the destroy method. Now
whenever you call this and console return to our main common from area, this indicates
that applet is no more in memory and no more thread, nothing no more execution.

So, this basically says that how the destroy method can be invoked immediately after the
stop method. Now destroy method can be called only the stop method is invoked.

804
(Refer Slide Time: 20:07)

We cannot destroy method until a stop method is invoked.

(Refer Slide Time: 20:11)

So, this example illustrates 5 different methods; init, start, paint, stop and the destroyed.
There are few more methods are there update and repaint method and it is more
fascinating to have a demo about the update and repaint method using a very interesting
one applet is called the banner applet. Now here is the code for the banner applet, ok. It
may be little bit difficult to understand, but if we are little bits meticulous about this, then

805
we can see what the contents are, the code elements, code things are there in this
program.

Now, here these are the import section as usual and here is the name of the applet. Now
you see extends Applet is, but this banner applet needs a thread to be executed. So, it
implements Runnable thread and you know the thread means we have to declare a thread
and then, we have to define the run method. Now, here a thread is declared in the start
method. As you see here, this is the start method where a thread is created and this thread
is basically thread of the entire applet is basically itself a thread here.

So, this is parameter to this thread. So, this thread is now created thread, instance is
created and now t.start() means thread has started its execution. So, init method will
basically change the background and foreground automatically invoked, start also will be
automatically invoked by virtue of this, the thread will be automatically in execution and
then whenever the thread is executed, then it basically execute the code that is defined in
the run method.

So, run is basically accompanies the thread class since the run method that is the
runnable interface, the overeaten method here a little bit. This is a tricky code, right. We
should not explain much about how these code works actually.

(Refer Slide Time: 22:12)

806
It basically select one character from the string which needs to be mark quick actually.
That means, string will move and then that string will be painted and then, repaint and
update will be invoked. So long this thread will be in execution, this thread is basically
execution and intermittently the thread goes on sleep state for 250 milliseconds. It is just
for perception of your views that one character is displayed.

The next sub string of the character will come, it will be again repainted, update the
things I mean area and then, again repaint, update, repaint going on and this process will
go and then if we do not close it, it will continue. So, stop method is there and then event
can be maintained for that if we just click button here is no event like that anyway. So, it
is stop means we just stopped whatever the procedure we have discussed here. So, stop
means the banner will or starts a complete and its execution.

Now, let us see have the demo of this applet class here. Only here the run method is bit
difficult to understand, otherwise everything is very simple ok. I am just enlarging this
applet window little bit, so that we can understand about it. Now, here our applet is in
execution as you see. So, applet started and here you see the banner is working the state
that the string is moving a simple banner come there. Again a simple this is a banner
actually look like actually the display digital display look like banner you know. So, it is
basically in the applet that you can do it and then background, foreground it is already by
the init method.

Now, so here our thread is still it in execution and then, in order to stop this thread we
just simply close it. So, now we come control return to our execution I mean in the
execution in the runtime manager. That means applet has stopped now. So, this is the one
example the banner example that we have planned it and then, we see that how this is
possible using writing a simple applet program here.

807
(Refer Slide Time: 24:35)

And then one basic thing so far the applet programming is concerned is, hosting using an
html page. We have an idea about applet programming. So far the applet program is
concerned different methods the standard methods are there.

I want to mention one more thing is that in addition to these are the standard methods,
we can use you can include many other methods defined by the user, user defined
method as well as the method can be inherited from other API class also, ok. So, those
are the things is possible and that is there regarding the different methods that user can
define, we in the different application context all those things will be again discussed
once we know many more things regarding applet programming and awt programming,
ok.

So, that will be discussed then. Now, just I want to think is that two important things
there. Two programming rather I should say one is that java programming. By means of
java programming we can define our class file that can be the code in our applet and then
html right. That means, that that class file should be embedded into the html there.

Now, what exactly an html file is there. html is there, html as you know html stands for
hypertext markup language. It is a basically a language specification that a browser can
understand this code and browser can understand this html code by understanding or by
recognizing the tag. So, html is basically is a collection of html tags and here we can see
the different tags and then tags has the starting and closing what is called a syntax.

808
For example, html the starting syntax within the angular brackets(< >) as we see and is a
closing is this one, then whatever the portion that will be within this starting and closing
is basically the portion of this tag and your html page. The browser actually this basically
can be executed by a browser, browser can open this html page and tagged by tag, it can
interpret what exactly the content.

Now, here in this example as you see html within html again another tag body and then,
within this body as you see some other tag is called the applet. Now this is a very typical
one look like, but html is not that all the tags is necessary or mandatory. There are all
those tags are optional also. Now here is an example that we can go how a typically
simple html page usually look like without any applet code in it here.

(Refer Slide Time: 27:33)

This is a typical look of a simple html file which include many other important things are
there. As you see here title is another tag <head> is another tag <body> is another tag
within the body <Applet> is there now.

809
(Refer Slide Time: 27:50)

Here you can see this is the title and these are the simple text within his, right. Html will
not be able to process it. Simply it will just pass it to the displayer, it will just as a string
only whenever html not able to pass it is just string contents as a string and then, these
are <head> <TITLE> <H1>.

These are different html tags for the different meanings those know the html. They can
understand about it anyway. I do not know want to discuss about the meaning of each tag
and whatever it is there and the comment can be post in html tag using this notation and
then, this can be opened by applet viewer also, but applet viewer can recognize only
applet code. All other things those are there applet viewer is these are not recognizable to
applet viewer.

But html page can be better recognized by any browser. So, any browser in our machine
say chrome or browser here I am just opening this one using our chrome browser you
just where is the html file is stored, go there and double click automatically the default
browser which is there in. Your system will be invoked to open it as you see this is the
html content and this content will be interpreted by our browser here and display it and
you see the html image is there which basically image is there.

So, image is displayed and then link hyperlink it is there. So, link means it go to this one.
So, link is if you go to the link, if the machine is connected it will automatically go to the

810
NPTEL web sites. From this browser automatically is a hyperlink it is there and then, it
will be executed.

Now, so another thing is that html browser, your chrome browser in this case cannot
recognize this part that is there because they are not embedded within any html specific
code. So, it is basically coming there in this here and here is a title you see a simple html
and the browser you can see the title bar.

Actually it is showing a simple html page is there. So, these are basic concept of html
display it is there and one thing is that all these tags are basically not case sensitive. You
can write in capital letter or small letter. Absolutely it is not an issue. It will run it. So,
html browse html page is case in sensitive and obviously, if there is any mistake in the
tag that html will not be able to recognize as you say, then means it has just simply
ignored.

(Refer Slide Time: 30:31)

But the next part will be it goes there. So, it is interpreted successfully. If something is
not correct, then the rest thing, which are there correct thing will be executed there, ok.

So, this is about this and then one important tag that can be included in this html file is
applet code and then, if this code is there and applet viewer can recognize this one only,
but applet viewer will not be able to understand this one now. So, now we have used this
applet code and then appletviewer can process it, however it will not process any other

811
things that is there because other tags those are there in html page is not executive to
applet.

Now, let us run this appletviewer as you see it will not give the same impact as the
browser has given it to us. So, I am running this html pages applet viewer then right ok.
As you see applet class is not there, that is why it was not executing hello world class.
So, here applet viewer has could not be able to display this class file because in the same
html file where this program is there, it is not there for dot java is not correct. You have
to do the dot class, ok.

Now, dot we have changed this one save it and then, the .(dot)class file is there. There
are some mistakes there. So, we have included in the code file.(dot)java. Dot java cannot
be interpreted by the applet viewer. So, it did not give any output actually now we have
changed it. So, as you see this hello world class is giving there are some mistakes are
there anyway. So, it is basically the applet viewer can recognize this code, but it can
again if the earlier without any applet code our browser or successfully display it.

Now let us see using this applet code if we again run this app chrome this html file what
will happen, ok. So, now here you can see our chrome browser cannot interpret it. Applet
code is basically simply ignore it, however other has been there.

So, it is basically the applet viewer and then, browser as a point I just want to mention
here is that the current browsers those are available at the moment, they do not support
the applet code now a days.

812
(Refer Slide Time: 33:07)

If in your machine internet explorer version 4 and lower onwards is available, they can
be supported and then browser that IEEE the internet explorer browser can recognize this
one, but version 4 upwards or not that is not support is possible, however there are few
browsers they are called java enabled browsers like Netscape navigator and then, hot
Java.

They can do it, they can support everything whatever the html tags including the applet
they can browse it properly and more specifically Mozilla also which in a restrictive
manner if you use certain plugin code, for that plugin is available in the free plugin in the
net. You can install it and then, that Mozilla with this plugin can process both all the
html tags as well as applet tags always and again html 5 version onwards applet becomes
obsolete of applet. You can use the <object> tag. Their <object> tag is very similar to
applet tag.

That includes our today’s first demonstration on applet programming. Our next
demonstration on applet programming 2 in our next module onwards and then, we will
discuss another programming concept in java.

Thank you very much.

813
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 38
Demonstration – XIV

Now, here is the second demonstration on the applet programming.

(Refer Slide Time: 00:22)

In these demonstrations we are going to highlights about the specification of HTML


documents and then, we will conclude this demonstration with two applets; one is the
calculator and the banner applets. Some let us have the HTML contents is there.

814
(Refer Slide Time: 00:40)

Now as you know HTML is coming into the purview of applet programming because the
applet code should be hosted by an HTML page.

(Refer Slide Time: 00:50)

And in an HTML page the applet tag is there as you see here in this particular example
here this is basically the HTML page content and then, applet tag it is there. Now, this
the applet tag is coming here in its simplest form, but an applet tag is there with many
other parameter specifications. Now, we will discuss one by one those are the parameters
which are more relevant. So, for the applet programming, it is concerned. Now, the first

815
parameter that is there is the code itself and then, width and height these are the masked
parameter. The mandatory parameter any an applet tag these two parameters I mean code
and width and height are to be there. If there is an applet tag without this, this means that
it is an invalid or incorrect applet tag.

Now, in addition to this valid and then necessary parameters, there are few more
parameters are there and the width and height as you have already shown and you know
exactly what is the meaning of width and height.

(Refer Slide Time: 02:05)

This basically whenever an applet we want to display, it is fluidic in the sense that its
size can be specified by these values. All these values are expressed in pixel. So, 460 by
160 pixel-like and we can control the size of the applet by showing the changing these
values there. Now for example, here 460 and 160 being the applet size, it will give and
display and then let us have the display with this 460 and 160 it is there,

816
(Refer Slide Time: 02:39)

So, this basically total if this is the total computer resolution is 1 0 2 0 divided by 1 0 2 0
whatever it is there, then it basically coming into that specification there. Now, let us
change this again HTML page a little bit by say 200 by 200. As you see the side will
change again. We have just do not change any code. Only you have changed the HTML
file, save this HTML file, again the applet we are no need to compile it again as you see
the applet yes come. So, an applet has changed its size. So, this is basically the parameter
width and height by which the size of an applet 2 if it can be controlled.

Now, our next important tag that is possible next important parameters the specification
that is possible in an applet is called the codebase. Now, codebase basically the idea it is
that the class file that needs to be executed by an applet viewer or browser should be
available somewhere here and there. So, codebase is basically said were this the location
of your class file. In this case, we can see our HTML file and then, class file by default if
they present in the same directory, then no code base specification is required.

On the other hand, if your file is in one directory for example here in class directory
whereas, your HTML file is in some other directory like in this case as you see in the
different directory, then we have to give the relative location of your base and then
formal finally the class declaration.

So, here again you see in the codebase the value that we have specified using this file is
in E drive. One directory is there under this directory, another subdirectory, then there is

817
subdirectory class within this class this file is available. So, this is a complete
specification about the location of the .class file which is there and it will be able to
locate it and then, execute it.

In alternatively the here basically in the same machine if it is the same machine, but in
different directories; on the other hand, if it is not in the same machine, the browser will
browse from your own machine is a local right browser machine. And your this class file
can be from a remote machine in any server or in a remote PC and then, we can and this
machine it is connected to the net, then we can give the complete location of the URL of
that machine then and then the class file. So, it basically browser will browser or applet
viewer will probe into that remote machine.

(Refer Slide Time: 05:59)

And then we will access it, so, this is the idea about the codebase. Now, archive is
another example ok. You can have this demo as you see we have changed the codebase.
Here we can maintain the HTML file in different directories and then, class file in a
different directory giving this specification will find its own source and then it will run it.

Now the archive is another right now in your code, in your applet tag or in your applet
rather if it needs many other things to be imported from a distant location and every time
it basically refers to an import item, then it needs to be connected to the machine and
then, fetch it and then execute it.

818
This will claim time communication over. It also will increase in order to avoid it in the
applet took. There is a specification called the archive. Archive basically whatever the
files or items that is required to run this applet can be punched together in one jar file and
then, the same file can be pasted or can be imported only once and find it.

Here, for example, our source file is .class file is here which is there and some other files
it is there which is required there and this file is put in the jar file there. Now you will go
to this there and then, jar file location you can see it there. Here is the jar file go to the jar
file and you can see the jar file contains many other important necessary file it is there
ok.

So, right we can find it and then it will basically as you have made it compressed also,
so, compression is good. Now so, it will basically all components will be pasted once
and then, automatically from the jar it will find its own file. If it does not file, it will not
do the correct execution of course. So, this is the concept of archive it is there.

Then our next is object specification as you know the object is an alternative tax
specification in an HTML 5 which basically supported by HTML 5 version and upward
compatible language actually and it is basically the object is basically the same as the
applet. Now, here you can see in live of applet the object tag is used there and if we run
it applet viewer, as well as the browser all, can recognize this object now because we are
using this browse right applet viewer.

So, this basically you see here no object code, object tag, and no applet tag, but object
tag and within the object tag we can do it. So, it is basically HTML version compatibility
and sometimes to make the version compatible irrespective of the different HTML
versions that a browser can support. We can use both the code together.

Here is an example. So, object and applet code can be nested in the same HTML file, so
that whatever there is a browser, it can support whether HTML version 4 or 5 whatever it
is, it will basically support and this is an example as you see object code is there, a plate
code is there which is basically applicable relevant to a browser it will get it and then do
it.

So, this is the one HTML file is an alternative way that is basically compatible with any
version of HTML page. As you see here it is basically executing it basically gives a

819
thread to whichever is applicable. So, an object is first encounter object is started and
then, it will basically HelloWorld class code will be executed properly.

So, this is the object tag is there, there are some more tags. All tags all specification and
the v space h space name and everything name are there. Name actually you can mention
the name of an applet that can be used for an internal purpose of applet execution when
they are in a distributed environment.

That means, 3-4 applets are running concurrently, but from the distance machines and
they can communicate with each other and this process of communication protocol
applet names needs to be recognized by which the applet should be specified by this
applet tag. The name of each applet here actually in this applet tag we can mention name.
Let the name of this writer code there right no here right name.

So, just simply give the name specification name this equals within double quote and you
can give the name XYZ whatever it is there. So, these basically specify the name of the
current applet that needs to be executed like this way and this is basically networking
communication and everything which basically we are not in a position to discuss. So, I
just want to skip this discussion.

And then, few other applet specifications which basically not so much relevant in the
context of appletviewer usually do not consider all those things like v space h space align
all these things. Those are coming in the purview of HTML browsing. If you have the
internet explorer version 4 and onwards, then you can understand about it this basically
positioning the applet and then in a proper or in an aesthetic manner.

So, that applet we will look looks good. So far is the for a feel-good impression applet
can be managed or it can be arranged and for arranging to align v space and h space is
there as it is HTML specific and also not specific to applet viewer. It is better to skip it
there. Now let us come to the end of this one; I just want to conclude these things by
giving details about more sophisticated and more useful programs first we have to have
the idea about.

One thing I have just skipped it as a parameter passing and this parameter passing can be
done by the param specification within the applet tag. Now, here I can see this is the one
applet class, the ParamDemo .class and then this class is basically yes and then you see

820
this param class we will get the parameters here. The parameters are named as font
name, font size and then, leading and account enabled and their values also supplied side
by side like for this first param name.

The font name value is courier we can include in double quote whatever it is there. So,
double quote please yeah. So, easily it is customized to include all the parameters in a
double quote because HTML we will treat all these parameter values as a string and then,
so all these things will be treated as a string and then and then basically than in the
HTML they should be specified here.

Now, no it is not like that what you have done it is now let us pass the parameter
ParamDemo java class ok. We can come to the HTML file here, that is ok. This is the
HTML file. Now let us have the class file for this one. Here is a class file as you see font
name font size leading and boolean actives are the 4 parameters which is basically local
to this class we have declared here and those values you see how we can extract it either
using init method or in the start method whatever it is there. Now in the start method, we
have used this param basically the temporary temporarily string one and then you see it
gets its values font name from the parameter.

(Refer Slide Time: 14:36)

Now here in this HTML, this hosts the parameter .class which basically the compiled
version of this one and the param name font name. This parameter font name is basically
Courier and here you see font name get parameter, this method get parameter is defined

821
in applet class. This basically gets these values of this font name which basically here
and then, Courier and you see the name which is there in the font name in the HTML file
and within this double quote, these should match.

If there is no matching, then it will basically gives an error. To handle this error we
usually put a try-catch block. Now so, this will be just font name. This parameter is get
the value here the value. For example, Courier and it will store in the param parameter he
as a string and from this string we have to process it either into the integer. For example,
for this font size, the value should be passed as integer here, fontsize for others. For
example, leading value also integer we have to pass into integer and for this action
enable is a Boolean its value to be passed into Boolean value, right.

(Refer Slide Time: 15:55)

So, string to Boolean conversion and store inactive. So, what we can see is that the
HTML we supply the different parameters which can be extracted by an applet while it
in execution and then, gets it values and then this value can be used in the paint method
or some other method to process it. Here we are using all those values to simply display
it.

So, this way we can pass the parameters from HTML to an applet execution and this
parameter passing is very much important because we cannot give direct input from our
console keyboard or any other input to the applet as you see this applet got the value and
then display it anyway. So, this is the idea of the parameter passing techniques. We have

822
an idea about the applet construction by virtue of many methods that are there
overwriting those methods which are defined in abstract class.

Now, let us come to the demonstration of the calculator applet. So, a calculator applet
typically we will look looks like this here let us have the first a look of a calculator that
we are going to design it here, run this calculator program.

(Refer Slide Time: 17:15)

So, that we can have the look of this, then we can explain it here. Yes now, this is a very
simple and innocent look of a calculator because I just want to make it more simple so
that we can understand about it in this calculator. What we see there are 10 buttons
numbers digits 0 to 9. So, basically, these 10 buttons are essential to input 10 numbers I
mean digits I mean typing from the keyboard.

So, if we type two it will go into this one and then, like this one. As you see here
whenever we click a particular button actually you can say button two, right. It will
basically the corresponding character that will be selected is basically digit or number
will be selected numeric will be selected and then, it will display in the area. This is the
text area where whatever the selection is there, it will be displayed; in addition to this
numerix.

There are few more buttons we can see those are plus-minus, then star and then divide
and finally, there is a button is called equal and then another clear. So, these are the few

823
buttons, this is a very simple one applet with altogether as you see total 16 right buttons
are there those are arranged in that way and they are enabled, so that if user can click
using mouse that particular event will be there in this applet in this background and they
will sense it and then get it. So, it is basically an event handling concept is there although
we do not know much about or on anything about event handling concept, we will just
simply give it assuming that some events will occur there. If events will occur, they will
be handled here.

Now, let us have the calculator program here. We will emphasize about only the design
point of view and then, even handling point view we will be just simply mentioned here,
but details event handling will be discussed in our another class.

Now, here we can see first of all we have to create the button as you see we have created
total altogether 15 Buttons and then on another Button is not Button is the text fill area.
Now, let us see how we have created 10 Buttons. First, we have created 10 Buttons here
as you see here we can see the Button is the one class. It is there in AWT by which we
can create the Buttons here. So, a list of Buttons is created here. We can see 10 Buttons
are there and then, in addition to these 10 Buttons, other 5 Buttons that we have created
they are named differently and then in the init method.

(Refer Slide Time: 20:42)

We just background color we know how to change the background. This is a Background
Color of this one set Background and also we have created another area. This area is

824
called the TextField area. So, the TextField is another component and this is the size of
the TextField means how many characters it can hold. So, 10 and then all these patterns
and text fields are arranged in this arrangement. This arrangement is basically obtained
by means of great layout pattern it is called all these classes like button the text field the
great layout is defined in AWT package.

So, they will basically do it that all these buttons that you have created will be arranged
in this grid form. So, these basically look like a grid and then, we once the button is
created we have to add the button using add method there in the AWT class is there.

(Refer Slide Time: 21:41)

So, adding these all these buttons one by one into these grids and then, altogether all
buttons are placed there now. So, this design completes all buttons are arranged, all text
field is also created and next basically this basically look like, but here at the till this time
we do not mention about any event handling concept. Now, in order to have the event
handling concept what we have to do is, we have to register that a listener object will be
there.

Now, this we do here in the start method by adding the action listener 1 method. Its
interface is there in again AWT package it is. So, the action listener we have to include is
there and this action listener you will basically once it is implemented and then, we have
to include one method add action listener as a registration purpose. That means, action
listener is an interface and add action listener is basically is a registration purpose that we

825
want to listen to this concept or element or the component, the button component and the
other components are there.

So, for this so this is the mandatory one thing that we have to do it. So, this basically is
basically starting point of handling your event and then, all these classes that we have
declared here we have to add into this action listener here at and all these there. So,
whenever we have already added all these buttons are there.

(Refer Slide Time: 23:20)

And then all these add action listener performance needs to be specified properly and
here we do this. Here the get action commands are another method who basically gets
exactly what is the character that you have to type while you click your mouse. So, it is
basically mouse clicking and whenever you type it is basically passed as a string get
takes and then, converted into the string to character or integer or whatever it is there and
then, it gets the value.

So, if we press it here get the text is 2 and then, it parts into the value as a number and in
the number will be displayed in the text field area.

826
(Refer Slide Time: 24:00)

And these are basically how the event can be handled. That code is mentioned here is
basically whenever a click action is there, it gets a text from there and then, store into a
number and then, that will be displayed in the text field that is the event handling
mechanism at the moment.

(Refer Slide Time: 24:16)

You may find a little bit difficult about dealing with this event handling mechanism is
there nowhere for example, if this operation is plus. So far the action handling is
concerned if we click plus, then it will work in this way and then by the resultant the plus

827
operation will take place. Anyway so, this way the applet contents few components they
are called buttons and one component is called the text field area.

That is all about this applet content is concerned and for each applet components, there
is an action to have listened and that action listening what we actually the action that will
be to listen has been defined by means of the implementation of action listener methods
are there. So, this is the applet code that is there and how it executed it is there.

Now it is as you see this is a very simple and then, very initial stage of an applet, but for
this initial stage it is enough and there are many more things. The color can be changed,
then size of each button can be configured properly so that it really looks like a good
looking applet calculator it is although it is not at the moment.

So, it can be done all those things will be discussed whenever we discuss about AWT
programming followed by the event handling programming there. So, this is at the
starting point for our applet programming and so far the advanced use of an applet
concept is there. Now, another is the banner applets. We have a view of the banner
applets or have already displayed it how the banner applet works there.

(Refer Slide Time: 26:12)

Now this banner applet that we have already discussed is basically a text which will be
given from the banner the program class itself, but this is a little bit extended version of
this one where the message will be passed through a parameter passing technique.

828
(Refer Slide Time: 26:34)

Now if we see the HTML file here, HTML file right and here you can see we want to
pass the value to our the banner applet that we have already discussed earlier. Earlier the
banner applet use the static message which is there in the code itself, but here we want to
pass this value from the banner from the HTML page itself and the HTML page we will
take this value and then, it will pass it to the applet and then, our banner applet we will
run with the passed value it is there. Now, here is the demo we can see how it will work
for us ok.

(Refer Slide Time: 27:18)

829
So, there is nothing as such details change about the compared to the previous one, the
same concept banner everything only the message is there and then if there is no
successful inputting from the HTML. So, a try-catch block is put that is the only extra
part that we have added here, otherwise, everything remains same and as you see it will
basically this applet banner we will run with the message java makes the wave move like
this one and then, it is executed. So, it is another form of applet right ok.

So, the programming concept is there. So, we have learned about few more things right
about how the applet tag is important. So, for hosting an applet code in HTML file is
concerned, we have learned about it and then, we have discussed about the banner. It is
an advanced version; a little bit in the sense that parameter can be passed from HTML
and the very initial or beginning loop of a calculator applet. So, that is all for today.

Thank you very much.

830
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 39
A W T Programming – I

In Java, all programming’s can be broadly classified into three categories, the core
programming, applet programming and AWT programming. Now, AWT programming
and applet programming they are alternatively called the graphics oriented programming
or more precisely we can say window based programming. So, here basically we have to
develop windows and through windows the programming aspects can be carried out.

(Refer Slide Time: 01:01)

Now, today we will discuss about AWT programming. AWT programming actually we
have to see exactly both applet and AWT programming just now I have mentioned is a
graphics oriented programming which is the main difference from the core
programming.

Now, what is the difference between an applet programming and then AWT
programming? So, as we know an applet is basically a java program which can be
executed through a browser. On the other hand, if we see the core programming we do
not run it using a web browser, rather we can run independently from the console itself.
Now, AWT in that sense similar to core programming that here we do not need any web

831
browser to run a program which is developed using AWT. Now, so this is the one
difference, there are many more difference also.

Now, so, for the applet is concerned it is basically a small program as we have seen and
usually this small program is mean for internet-oriented programming or more precisely
is basically web programming we can say, where the browsers can browser the net and
can access their web page and this web page will usually include applet. So, if you want
to design web page then definitely you can think for applet. However, AWT and core is
not in that sense web programming actually.

And as you know that applet, whenever we have to design an applet we usually follow
the package applet where applet class is defined. So, that is why all applet programs are
called subclass of java.applet.Applet. Applet class basically is an abstract class which
you have to inherit for our applet program. It is also alternatively called an instance of a
sub class of java.applet.Applet. So, this is basically the different way an applet can be
defined; however, the core and AWT is not like the applet is as it is mentioned.

(Refer Slide Time: 03:31)

Now, what an applet can do for us? As you have checked it using applet it user can draw
any pictures on the interface, I mean in graphic input screen, display screen rather we can
say. It can create a new window, and this window can be enable to draw any graphics. It
can play sounds audio video it also can receives input from the user through the
keyboard or the mouse, but not the input the conventional way that a core program can

832
allow in reading an integer or float or string like this. It only the sense the keyboard or
mouse whether there is a clicked or keyboard is pressed, mouse is dragged like this. And
obviously, applet is for internet programming in the sense that in the distribute
environment applet can communicate to another applet to serve the some communication
need. There are many more applications of the applet is also there.

(Refer Slide Time: 04:42)

On the other hand, an applet which has many limitations as well as for example, an
applet cannot write any data into any hard disk even in the local machine hard disk also.
It cannot read any data from the host machine; that means, from which the applet is
running. It cannot delete any files, it cannot read from or write into any arbitrary memory
in any non-memory protected operating system like MacOS or like these.

So, basically applet is heavily restricted, so far memory access is concerned. And it
basically enables a network connection to I mean host the internet or any other from
which it was download; that means, it cannot establish connection of its own. And it also
cannot call the native API directly. If you develop your own API it cannot use this
things, whatever the methods those are declared there in the applet class you can use it
and if can extends then through extends only, it can access all those methods otherwise
native API cannot be utilized in this applet whereas, core programming or AWT
programming can do.

833
As we see core programming has many way resembles with AWT programming on the
and the difference from the core programming and AWT programming is that, core is
totally controlled console based; that means, giving input or output whatever it is there
from the keyboard or whatever it is there is no graphical user interface component, there
is no window component. Whereas, AWT is totally graphical user interface based or
windows based.

Now, let us have the more elaborately the different concepts of the AWT that we are
having. So, AWT as we are telling AWT, AWT it means that it is a full form of a big I
mean 3 words actually Abstract Windowing Tool kit, as the name implies it is basically a
tool kit. This tool kit a java programmer can utilize to develop their own applications
software and is an Abstract Windowing Tool kit, it is called the abstract this is because it
gives a line gives an way how the different method can be utilized. However, time to
time user has the flexibility to over write that method and can used it is there.

So, in usually all AWT programming we can say little bit light weight programming
process whereas, the core programming is heavy weight if you want to do something you
can develop of your own other than those are the facilities available in the APIs. In
general, so for the graphics oriented is concern core programming is heavily heavy
weight whereas, using AWT it is light weight. Light weight means all methods almost
are there you just play a plug and play that is all; that means, you can use and then solve
your programming development.

834
(Refer Slide Time: 08:09)

So, this is the AWT. And as it is a tool kit this means that it has lot of packages and all
this packages is defined in AWT package. So, java.awt., AWT is the package where all
AWT tool kit classes are there. Now, using AWT what can be done, I have given an idea
about it. This is basically a screen shot of a application which is running while I was
preparing the PPT slide I took this screen shot actually. Now, I made this PPT slides
using PowerPoint, PowerPoint is an application software which helps a programmer to
develop their slides presentation slides.

Now, here if you see there are many components are there, many, it is basically a
window also. Now, in this window as we see there are many, so this is basically a one
view area where the content the user is preparing can be displayed here. Now, apart from
seeing this is the another what is called the area where it will display some other
elements also.

Now, here are many other components for example, here this is the there, right this is all
these are basically is a small small; if the entire region window then all these are the
small small window actually it is there. And every window has its own item some items
are called the least of items, some items are called the menus, some items are called the
choices, like this one.

And there is also some other these are called the bottom like. So, if you click it using
these things corresponding some pop menu will appear and it will give other options

835
there by which user can select and can do many things are there. And other things are
very similar to the applet look like. So, these are the basically close, these are
minimization, maximization and also and similarly the status bar is also there.

Now, this basically is a product of an AWT programming and this is the product that is
used in Microsoft PowerPoint. Similarly, there are many other application softwares you
usually used nowadays those are basically graphics oriented or we can say more
precisely GUI oriented, Graphical User Interface oriented and or more precisely based on
window programming. So, AWT is basically a window programming which is
graphically user interface oriented or graphics oriented. So, graphically user interface
popularly called GUI; so it is G U I short form is called as GUIs.

Now, if you want to have back GUI in your programs, in your software then AWT is the
one best solution that I can recommend. So, this is the idea about AWT. And now the
question is that if you want to develop a software we can that is application software like
PowerPoint or Microsoft or Paint brush or something like then how we can do it.

(Refer Slide Time: 11:18)

Obviously, we can do it using AWT package. Now, AWT package in fact, is a very vast
package. It includes a lot of classes and the sub classes there. Now, all the entire
packages can be broadly segmented into few categories the first thing is that there is a
graphics oriented components are there. So, it is a graphics a related packages are there.
So, is a for example, graphics and then this is the point polygon all these things are

836
basically the graphics-oriented things are there. And then there is another is called the
component-oriented concept is there. So, component-oriented concept it is like these are
the component-oriented concept are there in this, these are the basically component
related facilities we can say classes, sub classes all these things are there. And then
image related some facilities are there or classes are there. So, image related classes are
like these are the image oriented things. So, if you want to process image and everything
then AWT will help with so many classes and others.

And then and layout management, so this is called the layout manager in general; so like
these are the different layout managers are there. So, this is the layout manager related
packages are there. And in addition to this event is a very important in any windows
programming, regarding event there is a tool kits are there, that is the event handling
basically by which we can do it and other than all these things every packages needs to
be very much provide the programmer to develop the robust software. So, error and
exception handling somethings are also there in this package.

So, as you see there are so many things are there graphics-oriented, image-oriented,
component-oriented, event-oriented and then others exception handling oriented facilities
is provided by AWT. Now, in our discussion we will try to learn all these concepts, ok.

(Refer Slide Time: 13:43)

So, applet versus AWT as you have discussed it is, we have our understanding it is I
hope it is clear. Now, AWT how this is whether it is a free or not, it is absolutely it is a

837
part of the APIs whenever you install JDK as a part of this JDK installation the AWT
package will be automatically installed.

So, it is the part is there. And then you can use this AWT to inherit many other classes,
some other there other classes to solve your problem or the access the different methods
those are there in the package component or classes in that package. Now, AWT is
therefore, developing graphical user interfaces are there. And mainly the component is
responsible to build GUI or GUIs. Now, what are the component? Those are very
important to learn at this stage or whether I can say at the beginning stage of your
programming understand learning I just want to include it.

(Refer Slide Time: 14:41)

There are many classes it is there or sub classes it is there, I have included those are
related to the component here like say Button, Canvas, CardLayout, Checkbox, etcetera.

838
(Refer Slide Time: 14:52)

And like there are many classes also, these are few more classes.

(Refer Slide Time: 14:56)

And there are many interfaces also, those are things it is included here.

839
(Refer Slide Time: 15:59)

Now, so there are many class and interfaces are there. If you want to use AWT
obviously, you should need some understanding about all these classes and interfaces
and then the methods in all these classes and everything. As it is very exhaustive and
elaborate, so it is also not possible feasible to discuss each and every classes one by one
discussing their methods, but in my slides I will include all the classes, and the interfaces
the methods in them, so that you can have the ready reference from here. However, if
you want to learn it then definitely you will have to consult the many other sources
which I have already given in the my first lectures of introduction.

Now, I will just discuss GUI development using the component that is there in AWT.

840
(Refer Slide Time: 15:51)

Component is basically itself is a class which is there in AWT and it has many other
subclasses like button, checkbox, choice, frame, panel, label, list, scrollbar, TextArea,
TextField which I have been included here. By name itself it means that what exactly
this component elements is can do for us. Probably we have familiar with the button. So,
if you want to create a button as a graphical user interface in your application then
definitely you have to use this class.

Like, like button there are many other graphical user, so these are basically GUI
elements we can say. They can be created for your pro software, and they can be added
in your software, they can be used, they can be developed and they can be designed, they
can be modeled whatever it is it basically gives all facilities for the programmer.

841
(Refer Slide Time: 16:43)

Now, I will discuss about the component classes. As we know, so first you have to create
a component and to create a component, a component is basically a window I can say.
So, if you want to add some other component into that window then there are many
methods are there which is which are defined in component class itself. The methods like
here add; as we see add means if you want to add button.

So, definitely add method should be there add, then there is a component we in which
component you want to add it. And then set size, you can just resize the component and
set layout a component can allow you to have many layouts. We will discuss about what
are the different layouts that is possible for a window. And then, set visible it is basically
you can sometimes a particular component or a window make it visible, make it invisible
all these things are there, so methods.

These are the 4 methods which are very important methods. And all these methods are
defined in component class, we have to just call this method in your program and then
that method has their own facilities; that means, it is a light weight process actually.

Now, first let us discuss about how we can create a frame using or AWT tool kit and a
frame is basically another container we can say. A container, basically an component
basically same thing an applet is also container, container means it basically contains
many graphical user elements GUIs like button, checkbox, scrollbox, whatever it is
there; so an applet can include all those things. Now, we will see a frame is also similar

842
to this it can also include many components in it. So, frame is very important one items
or important one component which is defined in AWT package.

(Refer Slide Time: 18:39)

Now, how actually a frame look like? So, here basically we have displayed one frame
whose background color as you see with color blue and in the top is basically the status
bar is a that that basically showing that what are the windows are there and as we know
for any windows there is a minimization, maximization and cross symbol includes that if
you want to close this window.

And there is a title also it is showing that is which application is PowerPoint or Microsoft
or whatever the user wants to make it that this one. So, it basically is a container. And the
frame also more precisely it is called. So, a frame has its own title and then some area,
and in this area, we can include many other components graphical user elements in to it
here. So, a frame is typically look like this.

843
(Refer Slide Time: 19:34)

Now, let us see how this kind of frame can be designed. Now, a frame if you want to use
it definitely you can call many constructor which is already defined in the class
component class, class frame actually, a frame is define frame is a sub class of
component class. Now, these are the 3 constructor as we have mentioned here. So,
details you can just go through whatever the point it is written. I will not elaborate
whatever the different construct it is there.

(Refer Slide Time: 20:02)

844
And apart from this constructor it also has many methods. Those are the methods which
we have listed here.

(Refer Slide Time: 20:09)

And here is an example, we can check it how we can create a frame. Now, this program
is interesting to watch it and I will just example this program actually.

So, this program objective of this program is to how we can create a frame. Now, here
we have created one core main program, basically we have defined one class called the
MyFrame class and the main method we have defined is here and here the Frame is
basically created of the class Frame. So, and then this is the title that will be displayed
here like and frame dot resize( ) is basically what is the size of this frames. So, it is 500
by 500 size it is there and frame set back background color blue if we use it then it will
make the background color like this one.

Now, here one thing is that this methods resize, set background, and these are constructor
of course, the constructor is already defined in the frame class itself, but this resize set
background and here is for example, show, show means the frame will be displayed is
basically defined in the component class itself. As we have already used these class
frame, so by virtue of this all these methods are accessible to this program itself. So,
these are the, this is the way by which we can just create a frame. So, creating a frame is
very simple. We have to use this and then define their size, their background if it is there,

845
if you do not do it the default background is a white will appear and then finally, we have
to show the frame; that means, frame is we have to make the frame visible.

So, this is the simple way the program can be used to create a frame. Now, so frame is
one container as we have discussed, there is another also panel.

(Refer Slide Time: 22:03)

But the difference between frame and panel, basically frame and panel same the
difference is that a frame as title whereas, a panel it does not have.

(Refer Slide Time: 22:14)

846
(Refer Slide Time: 22:16)

So, here is an example the constructor, these are the constructor, these are the methods
that is defined.

(Refer Slide Time: 22:19)

And this is one example by which we can create a panel and this panel can be included in
a frame. Now, obviously, a panel can include a frame, a frame can include a panel and all
these things can be plotted in a contained which is not a frame, not a panel whatever it is
there that is a simply a container like.

847
Now, here this is the idea again how we can create a panel which basically a content in a
frame. So, you can just watch out this code here, again the same this is the class program
that is to create the panel actually and here you see we have created a frame and we have
created then a panel. So, the default constructor it is there and this is the constructor that
is there for the frame. And then this is for the frame resize setBackground layout and this
is basically for the panel resize and setBackground is there. So, as you see all these
things can be managed or controlled using this method.

And finally, frame dot add (panel) this is important; that means, we add the panel into
this frame. So, this is the panel and this is the frame, we add this panel into this frame.
So, by default it will be there, but again another option will be there this panel can be
placed here or anywhere by deciding other parameters So, there is a overriding method
of course, so overloading method other parameter can be used. So, that this panel can be
placed anywhere you used and finally, once the frame is ready which includes panel it
can be shown.

So, this is the idea about how a frame include a panel or more clearly how a panel can be
created it can be. And likewise, previous example of creating frame independently a
panel also can be created, but this does not have many used rather it should be is a part of
frame or container or an applet like that, ok. So, we have learned about how the frame
the panel can be there and all these container say may be applet or frame or a panel they
can include some other components say for example, button.

848
(Refer Slide Time: 24:29)

Now, we will discuss about how a button can be created and how this button can be
added into frame or container or in an applet like. So, a button as you know it typically
look like now whatever it is shown here, a button actually it is look like a button has
some label like this one. It has some design style all these things can be done. So, all
these things basically you can do it, if you want to have what exactly you want to do you
do not have to do much coding only just invoke the different methods which are defined
in the component class.

(Refer Slide Time: 25:10)

849
So, this is the button, button let us see for the button these are the constructors.

(Refer Slide Time: 25:14)

And the methods are also there are lot of methods included here. You can go through this
slides and then have the full understanding about the methods and that is, ok.

(Refer Slide Time: 25:21)

Now, let us see how we can create we can create a button which can be plotted on a
frame. So, this example is like this. So, button if you want to create a button. So, this is
the standard common that you can follow, and this is the label that button will be. So, it
is a click like. And setBounds this methods is basically says that what is the location of

850
the button this is basically 30, 100 is the this location and 80, 30 is basically this is 80
and this is 30, this is the width and height like this one.

So, setBounds methods is declared in a component class. So, it can use it and finally, add
(b); that means, is basically these button class extend frame; that means, it will overwrite
on the frame itself. So, basically include in the frame or contain in the frame. So, add b
means these button can be added into the frame. And then setSize, setLayout and
setVisible are basically for your frame. So, this is related to the frame because it extends
Frame all this methods are automatically for this method implies; so this basically the
size deciding this one. And then finally, this ButtonDemo b, if we created then this class
will be instantiated and the frame will appear look like this.

So, this is the way here the button can be created. Now, in the same way many buttons,
with different what is called the labels with different background foreground and then
different sizes can different location can be added into this frame. I have included on one
example, so that for the illustration only.

(Refer Slide Time: 26:57)

So, this is the button, and then button can be also included in a container that is a
component without any frame or panel it is like this is the same example. Like we create
a Frame f and this is a button example and then Button b is created and then all these
methods are there. Now, here see button example extends component as is the frame is

851
also sub class of this component; so all those things will be there. So, this is the one way,
another way of creating button or adding component into your content container.

(Refer Slide Time: 27:32)

Now, so and another also how we can add the GUI into applet this example explain it.
So, in that case you have to develop the class which inherit the applet class then is
basically applet will be there, so applet will be created. And all these method here (Refer
Time: 27:47) b1 and b2, two buttons are created, one button having the label another
button without label and they can be added into his applet and it will look like this. So,
button can be created, the button can be added into the frame, button can be added into
the container which basically is a frame or panel and button can be added into the applet
also.

So, there are the different way; this an example that button can be like this button there
are many other component like checkbox and all these things that we are going to discuss
quickly. So, all these things are also can be included in your windows.

852
(Refer Slide Time: 28:21)

Now, if the checkbox how a checkbox look like. So, typically a checkbox is called like
this one a checkbox has this kind of things and then there is a label and then this can be
clicked or keyboard can be pressed there and then whatever there. So, this checkbox can
be selected. For example, this checkbox is selected if selected it will keeps there. So,
here we see 4 checkboxes are there which basically contain in an applet like.

(Refer Slide Time: 28:55)

853
Now, so, so now, let us see how the checkbox can be created. Definitely there is a class
for the checkbox and for this class there is a constructor, and for there are some method
also there.

(Refer Slide Time: 29:00)

These are the checkbox method.

(Refer Slide Time: 29:02)

And this is an example how we can add checkbox into a frame.

854
(Refer Slide Time: 29:04)

It is basically same thing the button look like. So, this basically two checkboxes are
created the C++ and this checkbox is Java. So, this is the way the checkbox can be
created. And as you have created a frame, so this is basically frame. So, this is our frame
and these are the two checkboxes as we have C++ and Java, and whenever you make true
so that means, a default selection is there and if you do not make it is basically there that
will be uncheck like; and then we can add this one.

So, f dot add (checkbox1), f dot means these are the two checkboxes that we have
defined can be added into the frame and finally, frame can be resized. So, this is the
concept that, checkbox can be designed. And you can see all these ideas basically same
only the different class corresponding the different class the different component can be
realized.

855
(Refer Slide Time: 30:03)

Now, Label, it is basically just like label is basically a component is like here you can see
this is an applet and this is a label this is the one label. Label means anything that we can
write you know in the applet. Like say g dot drawstring if we using g dot drawstring also
some label can be putted here, but label is the one class which is there which is explicitly
used for making different label.

For example, I can write say first name, last name, roll number and these are the label.
So, first name, last name, roll number we can write and then some other things can be
included there like. So, label is just basically string which can be floated on a on a screen
like. So, now, let us see how the label can be created.

856
(Refer Slide Time: 30:43)

So, there are constructors here, you can see 3 constructors are there in the label class.

(Refer Slide Time: 30:49)

And then few methods are also there.

857
(Refer Slide Time: 30:50)

And this is an example by which the label can be created a see this is basically frame it is
all obvious two Lables, l1 and l2 are created and they are redefined here using this one;
that means, first level second level, as you see this is the first level, second level. And
this is the setBounds basically size; that means, where it will be placed and where how
long it will be placed and then how long it will be. So, basically total with and this
everything is been mentioned here; adding into this frame and finally, frame is size. So,
this is the idea about how the frame can be label can be added into frame.

(Refer Slide Time: 31:27)

858
Textfiled, this is the idea about the TextField. As you see texfield is looks like this. So,
this is the one TextField area, this is the another TextField area, this is the another
TextField area; so this is an applet which contains field TextFields in each.

(Refer Slide Time: 31:46)

Now, let us see how this TextField can be created. Again, there is a class called
TextField that is defined in the components as a subclass of the component class. It has 3
constructors and then few methods are there.

(Refer Slide Time: 31:52)

And this is the one ask few more methods are also there.

859
(Refer Slide Time: 31:55)

And this an example you can test it how that two text field like two TextField like this
one and this one is can be used.

(Refer Slide Time: 31:58)

So, welcome to IIT, Kharagpur, NPTEL, Java. So, we just created t1 and t2 are TextField
and for every component you see setBounds to decide the location of the placement of
this elements into the container as well as the size and everything. So, setBounds is
always there and finally, this is the frame should be casted, and then frame can be
visible, can be displayed.

860
(Refer Slide Time: 32:40)

Now, so this is the way that TextField can be created. And TextArea is just like a
TextField, but multiple line very long text can be used there and you see whenever you
text area is there it has the scrollbar automatically will be there. So, we can define
everything and within this thing any text can be out and then displayed.

(Refer Slide Time: 33:03)

So, idea of this TextArea is like this and for this TextArea if you want to create the
TextArea, there is a class defined in called the class name is TextArea. It has the
constructor as we have listed here.

861
(Refer Slide Time: 33:09)

And few methods are also here.

(Refer Slide Time: 33:10)

And this is an example by which a text area can be displayed on this. The method is
there, the TextArea, this is the class that we have, this is the name of the TextArea and
then setBounds and then added into this frame and then frame can be resized. So, this
way the TextArea can be displayed on the screen.

862
(Refer Slide Time: 33:39)

Now, List, it is another item another graphical user interface item we can say. A List
typically look like this. So, here two list we have displayed here, this is the one list
contents some elements it is just like TextArea, but it is called the list this is another list.
And the idea is that we can scroll we can just, over our mouse to select any one list. For
example, here the mouse whenever come here it will highlights and this basically list is
selected we can say; so these are the example of a list.

(Refer Slide Time: 34:13)

863
And the class definition is also there the name of the class is list. This, class has a
constructor as it is mentioned here.

(Refer Slide Time: 34:17)

And then method also, these are the methods are there.

(Refer Slide Time: 34:20)

And then, this is an example which basically shows how the list with 3 items can be
created. So, it is the list basically the 5 items so; that means, it has 5 items, right. And,
but although we have created 5, but we have loaded with 3 only, so 2 more are blank

864
actually anyway. So, we have added 3 items in the list and they are added into the frame
and then frame is displayed on the screen. So, this way a list can be created.

(Refer Slide Time: 34:52)

And then Choice is also similar to list. So, idea is that initially a choice will look like this
only and whenever you click here all the elements which is there in this choice will be
displayed here and then you can hover your mouse to go to particular choices and then
we can select that one, whichever the choice is under focus can be displayed here. So,
this is the idea about this one and for this kind of graphical user interface the class which
is there in the AWT is called the choice class.

865
(Refer Slide Time: 35:23)

It has only one constructor.

(Refer Slide Time: 35:24)

These are the so many methods are there.

866
(Refer Slide Time: 35:26)

And here is an example about how we can create a choice with 5 elements in it. So, this
example is similar to the list example that we can see. We have created a choice, add this
choice into the frame, and then frame is ready to use it. So, this way a choice items can
be created and then it can be included in the either is a frame or it can be included in
applet or it can be included in any other container itself.

(Refer Slide Time: 35:54)

Now, here is a Scrollbar, we are already get familiar about the scrollbar, but
independently we can use some our scrollbar. So, this is the vertical bar and this is the

867
horizontal scrollbar. And then scrollbar has few things are there this is basically called
the visibility portion, this is the range; that means, scrollbar will range from 0 to 100. So,
if we click here, so whatever the value say may be 150 will be the value of this point
actually and this is basically the visible space is called the 60 pixels and here also
scrollbar has width and height and everything.

So, these are the elements that is the scrollbar and it can be a vertical as well as
horizontal, as you see vertical this is the vertical one this is the horizontal one.

(Refer Slide Time: 36:40)

Now, let us see how the scrollbar can be created. Scrollbar for this there is a class called
the Scrollbar class we in AWT package. It has 3 constructors, and few methods are there.

868
(Refer Slide Time: 36:44)

And then this is an example, and this example shows how a horizontal vertical scrollbar
cab be created.

(Refer Slide Time: 36:46)

Now, here frame this is as usual previous there and scrollbar this is the instance by which
a scrollbar objects can be created. And you see the method we have used the default
method, if we use the default method a it will automatically the vertical scrollbar only
and no other parameters are there, but here we can define the vertical or horizontal, and
then the size, and then visibility, and the range all these parameters can be defined. There

869
are 3 constructor we have shown using any one constructor the different way the
scrollbar can be instantiated. And then this scrollbar can be added into the frame, the
frame can be resized, frame can be displayed. This is basically a simple AWT program
that can use the scrollbar, and then you can use it.

So, this is the scrollbar that we have discussed about it. And few elements that we have
discussed, there are many more elements that we are yet to cover it. So, in our next
module we will discussed about many other components those are very much essential
for our AWT programming.

Thank you.

870
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 40
A W T Programming-II

This is the next part in our AWT learning. We have discussed about few basic
components and those are very very much useful to build our window program. Now we
are going to discuss about layout manager in this module. So, there are different layouts
that are need that needs to be I mean managed your windows and that we will discussed
about it. So, so basically this discussion related to GUIs GUIs with layout managers.

(Refer Slide Time: 00:51)

Now, what is the different layout managers are there? Again, layout managers are
defined in the AWT package and it can be used either explicitly or implicitly, if you do
not mention it also some layout by default will be there. And mainly java has the four
different types of layout manager classes called the FlowLayout, the BorderLayout,
GridLayout and then CardLayout and all this layout is basically to manage how the
entire container, either is a frame or panel or a container whatever it is can be managed.

Now, we will discuss about each manager individually one by one with example and also
we will see exactly what are the different constructor and methods are there to manage
all these things. Let us first have the discussion on FlowLayout Manager.

871
(Refer Slide Time: 01:44)

So, what is the meaning of the FlowLayout manager? It is there. Now this manager helps
the programmer to manage the different elements into the container. Now so how so if
you can go on adding adding adding. So, how they can be added to the container? So,
layout manager this FlowLayout manager tells you that if you add the first component
then it will go here in this position.

Now, the next component we will go automatically here, then next here and once these
all the this are the special field then the next we will come there. So, it is basically this
row and then this one. So, row-wise and then this one. So, this way container we will go
on automatically filling. Now here the idea is that you do not have to explicitly mention
that whether this button will go there this button you just go on creating the button and
then just add into this using the FlowLayout manager then FlowLayout manager
automatically adjusts them.

But; however, you can say there is a gap between the different elements and everything
that you can specify and there is a facility to do this things using this FlowLayout
manager.

872
(Refer Slide Time: 03:00)

Now, let us see what is the class definition for this manager it is and, so this manager has
three constructors as we see here FlowLayout and then FlowLayout integer alignment;
that means, which is the whether horizontal alignment or vertical the last example that I
have seen that arrives horizontal element. And then vertical element means it maybe this
then this also. So, this way also it is there otherwise this way is there.

So, there are different elements are there actually. Anyways; so there are different
constructors are there and again if we see this is another constructor hgap and then vgap;
that means. So, if this is the one component is added here another component. So, if this
is the hgap, now if it is another component so this is basically vgap. So, all these things
you can mention in your an I mean FlowLayout manager class constructor and then they
can be automatically adjusted.

So, this is the different way the FlowLayout manager helps a programmer to maintain or
to include the different components in them.

873
(Refer Slide Time: 04:11)

So, this is the usefulness of this FlowLayout manager. Now let us have the methods and
these are few fields are there center leading left-right trailing that is the different way that
manager can be decided. Center means all is centered, left means left alignment all these
are the usual meanings actually.

(Refer Slide Time: 04:24)

And here is an example let us see how we can use this FlowLayout manager in a
program. We have defined one class MyFlowLayout is the name of the java program that
we are going to create it. First, we create a frame and then we create 5 buttons here, all

874
these buttons are labeled as 1, 2, 3, 4, 5 like; so 5 buttons are created. Now, what is our
objective? Our objective is to add this button into this frame.

So, these are basically the statement by which we can add all this 5 buttons into the
frame. Now here next point you see there is that this frame can be set with layout, this is
the one method which is defined the component class and then component class and f f
the f is the frame being the frame as a subclass of component which is the setLayout is
accessible to it and then setLayout we just made the setLayout using this FlowLayout,
FlowLayout RIGHT.

That means, it is right alignments, now as you see these basically the manager
FlowLayout manager FlowLayout manager manages all the elements in the right
alignment and right alignment, but in this direction, this is basically this direction like.
And if you can add more then it will come again this then this and then this it is like. So,
always right alignment way.

So, after f 5 is you can f 6 f 7 f 8 f 9 f 6 f 7 f 8 f 9, but align will right only. So, this way
this is basically the role that the layout manager, in this case, FlowLayout manager can
be played can play here and you see how the FlowLayout manager can be assigned into
this one. Our all earlier example the default manager is basically FlowLayout manager
we have not mentioned it, if you do not mention then default is there, but here we have
mentioned FlowLayout with right alignment this is the second constructor that we have
called it and this is basically setting the size of the frame and then make the visible true;
so that the frame can be visible to the user.

So, this is the way the FlowLayout manager can be used in your program to manage the
different classes are there. Now we will discuss about the applet in discuss applet there
are so many buttons so many other component element is there. So, they all can be
managed using this FlowLayout manager or some other manager may be other managers
also there.

875
(Refer Slide Time: 06:58)

Now, let us see what are the other managers that can be considered now next example is
called the BorderLayout manager. So, idea of the BorderLayout manager is basically if
this is your entire if this is the entire say let it be frame or applet whatever it is there then
BorderLayout means it basically has few borders, one this is the one border and one
border, another border, another border, and center is there.

So, this is basically north, south, east, west, and center. So, this called the border
nowhere the idea is that this layout manager we will place some component in this area
then some component here some component here some component here; so whole the
frame can be managed in this form actually. So, this is the idea about the BorderLayout
manager. Now let us see how the BorderLayout manager can be invoked and where it is I
mean how it the class it is for this one.

876
(Refer Slide Time: 07:54)

So, it is basically a general look of the BorderLayout manager as I have told it. So, a
button for example, includes button 1, button 2, button 3, button 4 and this 1; so this is
basically the view of the BorderLayout manager actually.

(Refer Slide Time: 08:16)

And the class definition so for the BorderLayout manager is concerned, it has two
constructors the first is the default constructor and second constructor by which we can
specify hgap and vgap; that means, that gap between the two borders we can say and
then align also alignment can be mentioned.

877
(Refer Slide Time: 08:35)

So, these are the constructor that can be there these are the few fields are there center,
east, north, south, west there are a 5 fields showing center means at the middle east
means left side right west means right and north and south means top and bottom like.

(Refer Slide Time: 08:50)

Now, here is an example that you can see how the BorderLayout manager can be used to
play there to develop one window and in this example as you see the frame is the frame
which includes the 5 buttons those are the 5 buttons are declared here. All these 5 buttons

878
are labeled as north south east and west this is the button label like for example, this is
the one-button actually, this is the one button, this is another button.

So, 5 buttons are there ok; so those 5 buttons are declared here and here you can see we
did not decide the size of the buttons using set boundary like. So, if you do it then all this
button can look like that, but here if you do not this the entire this portion is basically
meant for this button this is another button which will be there and everything.

Now, let us see how all those buttons can be placed in which portion of this one. So, our
next statement is basically f dot add; that means, we add this button b one into this frame
using this BorderLayout dot north. So, this is basically to say that this button will go to
the north position like this one, button b2 go to the south one and button b3 east button
b4 west and then finally, 5 button is basically center and then finally, the size of the
frame it is there and then visible these are usual statement there.

Now you can find the difference between the FlowLayout and BorderLayout. If you use
the FlowLayout in this case for example; so, it will be like this and then go come here
then this and then this like this one, but here actually it basically once you plan it you can
place your component according to your own wish.

So, this is the idea about the BorderLayout manager and now let us have the discussion
about the next manager, this next manager is called the GridLayout just this is also very
important for one layout manager many ways similar to FlowLayout, but it has little bit
different meaning also.

879
(Refer Slide Time: 11:00)

A grid means in case of FlowLayout you can just go on adding but in case of
FlowLayout you just go on adding and then automatically it will adjust it and adjustment
can be control maximum by hgap vgap and whatever it is there. But what is the idea
about this GridLayout is that if it is like this we can make the entire container into a
number of grids, then the number of grids same may be n cross m.

If n cross m it means that n number of rows and m number of columns are there. So,
basically, the entire container will be pan like. So, n cross m; that means, so many things
are there now again it is a difference from the BorderLayout is that in case of
BorderLayout only 4, but here n cross m means n into m and. So, the number of per
elements can be placed here and there now in this example as we see this is the applet
which includes six buttons.

So, in first row two buttons, second-row another two and third-row two buttons in each
row two buttons are there. So, it is basically we can say 3 cross two is the GridLayout
size it is there. So, GridLayout is like this only now let us see how this GridLayout is
defined in your component class.

880
(Refer Slide Time: 12:33)

So, there is a class called the GridLayout, this class has few constructors a the three
constructors it is there in the GridLayout if it is the default constructor only one grid; that
means, only one element can be placed there otherwise you can mention the row and
columns in it and then hgap vgap can also be planned there. So, that you can make the I
mean distance from each grid to its neighboring grids like.

(Refer Slide Time: 12:57)

And here is an example as you see this is basically an example to create 9 grids in the
GridLayout form, and here the 9 grids contain the 9 buttons as you see here. So, we

881
create the 9 buttons and frame is here we add all this button into here. Now whenever
you go on adding so it is basically going in that way, 1 2 3 just like a flow layout
manager like and now see how we can do that. So, a setLayout new GridLayout three
cross three these basically indicate that what will be the size of your grids in this case.

So, this is the most important point here to invoke the GridLayout manager and grid; so
it is in this case. So, if you use the flow I mean FlowLayout then is an instead of
GridLayout, FlowLayout almost is the same things it will come there, but in that case,
the size and everything can be specified. Here no size needs to be specified for each
component, rather we can just mention although we can for each we can mention the
gap.

So, here you can GridLayout three cross three and then what is the gap between these
and this we can mention between these and these, in that case then it will basically the
smaller size also can be mentioned if the gap is specified like this one. So, there are more
good looking is there, but we have a default gap means there will be no gap between two
adjacents components. So, it is it will look like this.

And so these are the way the different buttons can be created they can be added into the
frame and they can be added using the help of GridLayout manager and then the program
can be executed as it, we can see it. So, this is the idea about the GridLayout example
and then CardLayout, it is just like a panel, of course, the what exactly card is a card is
basically one another we can say panel sort of thing, but there may be many cards can be
added into the frame. So, that is the idea about the concept of CardLayout.

882
(Refer Slide Time: 15:07)

So, the idea is to look like this. So, if this is the applet as it is so, the first Card3 is
showing. Now, if we click it then it will go to the next card, Card4 Card5 like on.

(Refer Slide Time: 15:20)

So, every card is basically one element in it there. Now, this layout is defined in the form
of a class card layout which is there in the component subclass of the class component.
And this has it has the two constructors as you see the default constructor the example
that we have seen is the result of the default constructor otherwise we can mention the

883
hgap and vgap between the cards also so that the card will be reduced in its size like. So,
the size of the card can be maintained using hgap and then vgap.

(Refer Slide Time: 15:57)

Now so this is the few methods are also there next method past method previous method
this one; that means, if we click it in which card it will go if we click by default is an
next otherwise a previous if we can control previous and what are the methods are there.

(Refer Slide Time: 16:11)

Now, this is an example as you can see we have added cards into an applet like. So, it is
an applet program and here the layout that we have the use the CardLayout. So, this is

884
basically to say that we want to follow the CardLayout as our manager for this container
and the setLayout layout.

So, this is basically the method by which the CardLayout or the otherwise setLayout new
CardLayout also can be used directly also here. Now here we add what we have added
here is basically 4 5 buttons into the in the form of a card. So, these are the basic 5
different applets view actually here, in the first applet view we just go on clicking and
then automatically this will be there I have used the three 5 different examples of course.

So, first, say suppose the card five. So, so the idea it is here is that Card5 is basically the
button. So, the entire button is basically one card should look like this. So, here the entire
button looks like a card, but instead of button some other things also can be included
whatever it is there it can include some other applet also in it and. So, here actually we
created 5 cards in the form of a button look like and they are added into this applet and
then we declare on key down that is totally again different concept of event handling.

So, KeyDown is one method which is defined in event class, we and then that event class
is apart of the component KeyDown is basically an abstract method we have to overwrite
it. So, this KeyDown key KeyDown method is a basic event handling if we press an I
mean mouse button so that is the KeyDown or not mouse button we can say KeyDown is
related to the pressing a key.

So, if we press a key then event e will be generated; that means, pressing a key is your
event and then it basically return which key is that the user has pressed it and then
layout.next is basically here exactly saying that this layout has the next I mean if you
press it then it will go to the next card. If you use instead of next previous if will go to
the previous card like this one.

So, either previous or next whatever it is there and return true means it just simply a
matter of return. So, key this is the KeyDown event, this event is automatically defined
there and you just simply press it and then automatically this event will play it and then it
will generate whatever the next action it is there. So, those methods are there and. So,
this program actually it is if you run this so initially, it will Card1 then if you press a key
then Card2 then Card3. Again if you press then Card4 and Card5, again after Card5 if
you place it again then Card1 and so on so on.

885
So, it basically pops up look like; that means, the different cards will be pop up and then
you can then display it. So, this card can contain few images or some other elements or
some other things likewise. So, different cards can be planned to give the different
facilities to your user look like. So, this is the way the CardLayout manager can be
designed and then decided. And here is an ok; so interactive applet I just want to give an
example about how the interactive applet can be created.

(Refer Slide Time: 19:40)

Interactive applet let us see I can explain it like this. So, for example, this is the one
applet, in this applet, this is the one text field this is the other text field. So, two text
fields are there and this text fields initially by default it has the value 0 and it has the
value 1. And we just display one thing like this another thing enter two values you can
give a prompt.

So, if the user enters two values mean they can give the value from the keyboard typing
the keys on the keyboard and then the value will be there and another value will be there.
So, this is gone typing and then once it is typed enter please enter then. So, after typing
enter then one the two values are filled there the automatically sum will be displayed this
one. So, for example, if I (Refer Time: 20:37) is a 5 and if it is a 6 then is the eleven will
be displayed like. So, this is the one simple example of an applet that we are going to
have it.

886
Now, let us see what is the program for this a very simple program here. And so is an
applet program so extends applet this is the name of the applet program. Now there are
two text fields text field inputA and inputB as we have said. So, this is basically inputted
a and input b like two text fields and then this is the init method this basically creates two
text fields. So, input a is created a is a basically declared and they created instantiated
and 8 is basically the size; that means, maximum 8 digit can be put into these areas like.

And then add input an additional input means. So, this input they text field input a and
input b are the two text field added into this one and now this default is basically grid
default is flowlayout. So, it is basically displayed like this one and then graphics we can
just use the paint method to control the value and then take the event from the there,
actually here the event also because typing some numbers is basically an event also
corresponding to this one.

Now, here you see what the paint method we will do for you. So, we declare x and y are
the two values, two-three different integer elements variables are declared x y z like and
s is a string. Now here one important thing is that whatever the things it is there, java
treat them as a string. So, it is also one string, if you type something it is a string actually
and then that string needs to be converted integer. So, it is basically to input a get text
basically the string and then string this is converted in integer by using integer.present so
x. So, x is basically whatever the user input here is stored as an integer now.

Similarly, other is y from this text filed area z is basically the sum and then we have to
display it. So, we convert this z into the string using this formula, expression and then
finally, g dot string the sum is 10. So, this we will print and then the value will be printed
here. So, this is a simple example which basically shows using the whatever the applet
we know and using the GUI components the here we have only used two text in. So, this
is interactive because we use it and then entre automatically it will take and the result
will be displayed there that is all this is very simple once you see how many less course
are there to do it everything it is there.

So, that is why this programming is called the lightweight programming, because you
just may just put it and then done the job readily and then there is a lot of supports from
the p is the AWT package they will give you and then implement everything. So, only
this is very simple actually compared to other programming concepts it is there. So, this

887
is the one example about that interactive applets and event handling is a very important
one concept that needs to be discussed thoroughly. In our next module, we will discuss
about it, but I want to give a glimpse of the event handling concept it is there.

(Refer Slide Time: 24:00)

These few slides are basically explained what exactly the event handling is because we
have decided that whenever you click a mouse it becomes an event whenever you press a
key it become an event if you drag a mouse it is also an event. So, it is basically called
the event.

Now, if this event is occurred, if you click a mouse key mouse then and suppose if you
click a button then the button click basically should generate certain facilities for the
user. Say suppose if you click a button and then button is basically whenever click either
it stops an applet or it basically play a video then you can automatically video we will
come into the play and it will display it there. So, it is basically the event handling
concept it is there. So, mainly two devices are used handling the key is basically mouse
and keyboard those are the standard mouse and keyboard are basically means for
generating an event. And then once the event is generated they can be handled by the
corresponding program for each event that is there.

So, here is a programmer, we have to decide that if an event occurs then what will be the
corresponding action that event we will produce to the user like. So, an event can be a
source of the event is basically different component and at the background you have to

888
write the program that if that event is triggered by a mouse or keyboard then what will be
the consequence it is actually there.

Now so far the different ways that the mouse event can be here we have listed few
things. So, so for the mouse event is (Refer Time: 25:35) the mouse can be moved it can
be dragging it can be entering it can be exiting keyboard event are pressing and releasing
windows events is there its basically destroying when means is a cross button is selected
is basically iconifying smalling. Or assuming and then it is basically moving also a
window can be dragged by clicking this mouse also and then scrolling event is basically
scroll bar page location and everything.

These are the few events are possible in our event handling mechanism or event add
ability programming and regarding. So, many events we will discuss separately in details
in our next module.

(Refer Slide Time: 26:12)

Now, here is a n example of how the event can be here, I can say it is a very simple
example for illustration purpose only. Now you can see what we have done here it is an
applet and in this applet what is the I mean container is there actually we see 1 2 3 4
these are the 15 buttons. So, 15 buttons are labeled as 1 2 3 4 like this one and all these
layouts you can follow which layout manager I should follow it.

889
I have used it here as a GridLayout actually because it is in the form of a grid if it is a
GridLayout then what is the size of the grid 4 cross 4 and here you see. So, out of 16 that
the grid components the first is 1 2 3 4 to 15, these are basically 15 components are there
and then the last is basically not the button it is basically called the text field.

So basically, we want to create a window that includes 15 buttons labeled as one two
three 15 and one is this one. Now here we want to add some event handling. What is the
event? If I mouse click the mouse here then whatever the mouse that is clicked it will
automatically display here. So, if we click here this one, if we do not initially it will
display with a star mouse-like nothing is clicked like.

So, here basically an initial view of the applet will be it is star and now if the user clicks
here then automatically it will display 6 or if we user clicks here then it will display 8
like this one. So, this is just a simple other interactive windows like the user can interact
with the interface and then the effect will be should be obtained to the user accordingly.

Now so, this is the event handling; I just want to have the code actually here right now
and then the details about how the event handling needs more elaborate discussion. Now
here is the code for this kind of programming, I hope you have understood exactly what
is the thing we are going to do it.

(Refer Slide Time: 28:22)

890
Now, the code is very pretty simple here as you see the code is very simple and first is
that n is 4; that means, we have to create four cross four layouts it is like this. So, that is
done by setLayout GridLayout n cross n this is; obviously, clear that we want to use the
GridLayout as a manager for my layouts and then here actually setFont, we create the
font as the Helvetica bold font 24; that means, all the fonts that we have already set to
display in this case is actually here.

So, these are the fonts that we have discussed here. So, this is the these the font that we
have discussed is Helvetica font actually anyways. So, this is like that we have discussed
here setFont and then we have to arrange the different buttons there. Now here is the
different button that can be arranged here, I have just make a loop that this one and
automatically this is a tricky loop you can just follow yourself and you can understand
that how the different button can be created with the label 1 to 15 and all those button
can be placed in this 1 2 3 4 5 then 1 2 3 then 6 like this one this way only the button will
be placed there.

And then the next the last place in the GridLayout will be placed by a label, and that
label has this label center and default appearance is basically called the star. So, it is
basically a label component is created there. So, it is a label and then these are labels also
have the font setFont times new roman font italic that means that label that will appear in
a different font it looks like this add label; so the label is added there.

Then next is the event to be handled because it is just simply the windows are created or
we can say applet has been created, but not an event has been added here. So, our next
part is there how the event can be added to it.

891
(Refer Slide Time: 30:27)

So, here is the event it is there. So, the event that we have planned here is the action, the
action is basically again is an abstract method which is defined in the event class and
which is there in the java.awt package is there we have overwritten it. Now Event e; that
means, whatever the key placed is basically event e or mouse click it is Event e and then
it is result written; that means, if we click a button say 5 then object obg is basically that
this is the button 5 has been clicked.

So, this basically the method that it will basically return it and if e.target instance of
button; that means, if we create a button then label.setText string object here basically
object means it is which button it is an object is already defined there here and then
object is basically a string and then that string will be displayed there and this is very
pretty simple the action method which has been overwritten here and that is all. And
once it is done your actually that that program is ready for your working.

So, that program output as we have already shown it will give it. You can test of your
own so that you can get more fun about it and accordingly instead of number you can say
a b c also you can check it, the one also you can put in the button itself get these things
and check it; so a lot of other manage what is called the experiment you can do with this
concept.

So, this is about the layout manager is very important one concept and then there is a
graphics also there. So, as I told you in case of component class there are many other

892
things or other AWT package that graphics is one essential component also to have the
graphics. If you want to develop an application software look like say paintbrush then
definitely graphics is to be considered there.

(Refer Slide Time: 32:21)

And graphics have many methods are declared there, graphics is a very important one
class there and it has many methods all these methods are basically how to draw different
graphics objects.

For example how you can draw a rectangle, how you can draw an ellipse how you can
draw polygon and how you can make the background of different, how the different
styles can be whether dotted or different style can be fixed and there are many other
things can be. Also, there are many other methods to position it zooming so many things
are there I have listed few methods that are declared therein graphics class, it is basically
a huge number of methods all methods are basically to handle the graphics related issues
are there.

Now, if you have different methods of understanding and everything and then if I ask
you to have a solution from your sides.

893
(Refer Slide Time: 33:12)

For example here; suppose we want to create this kind of thing are there it will display
this kind of text as well as it will draw this kind of figure. So, in this figure, as you see
this figure as one rectangle to be drawn another rectangle to be drawn, within this
rectangle other small rectangle windows. And all these things are there the ovals ellipse
will be there the rectangle will be there here is the one polygon will be drawn, another
line will be drawn, the line has the different thickness, the different colors and another
line will be also there.

So, basically, if you have the graphics methods and then different methods that are there
using this method I can draw all these things, and only the thing is that coordinate needs
to be specified. For example, say suppose this ellipse I want to draw here. So, ellipse is
basically this is the coordinate of center and we have to mention these are the major axis
and minor axis that is all.

So, center, major axis, minor axis and then background color and then these are the
different line color and the style also they are many constructors for ellipse drawing; you
just use it and then press it. Likewise for this rectangle also this is the position width and
height if you position and then background line color and everything it will draw
automatically. So, this way the different component can be placed and drawn and a
picture look like this also we will appear to you.

894
I will be left it as an exercise for you; try to have of it is your own and you can enjoy it a
lot, I believe. I am sure that with this you will be able to enjoy a lot. And really the AWT
program is a lot of interesting facts are there we have just started about basic things and
then in our next module we will discuss about event handling so for the AWT is
concerned which is more important to understand also and more we have to develop our
own skill for that.

And then all this AWT also can be down in a more advanced way using the swing also.
So, all those things in our pipeline we will discuss first event handling, then we will be
discussed about swing concept in our next lecture slides.

Thank you very much, thanks for your attention.

895
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 41
Demonstration -XV

So, this is a demo class, in this demo we will see exactly whatever the topics that we
have covered in the last 2 modules related to AWT programming.

(Refer Slide Time: 00:25)

And in this demonstration we will discuss about few things right.

896
(Refer Slide Time: 00:27)

So, how the applets can how the different GUI elements can be included in a container in
a components and the different containers also like say frame, panel and the different
components GUI components like Button, Checkbox, Label, List, Choice, Scrollbar
Menu item and everything and also how the layout can be managed by the user layout
mangers that is there in AWT and finally, we will also see exactly an application point of
view how these kind of things will be useful to develop our application. So, this is the
overall what is the agenda for this demonstration.

Now, let us have the first program; in this demonstration you will be able to see how we
can create a Frame and then the same Frame can be added and then the Frame can be
executed and we will just discuss about non-applet versus applet program I will just
discuss about the non-applet program right now. So, here basically we want to create a
Frame and the same Frame can be the displayed on a screen.

897
(Refer Slide Time: 01:35)

So, this is a program as we see here. So, this is a program as we see here in the first lines
as we see we just higher the class basically we define, this class is basically MyFrame
the name of the class as it is shown and then the main class basically application. So, we
have used the main method here and in this main method we create a class in this method
we can see we create a Frame here and then this Frame is basically passed with an
argument at String the Frame in Java; that means, as you know Frame is a container with
a title.

So, it is basically in the title bar it will appear this one and this is the size we have to
resize the frame that how it will be there and background that we have discussed here,
the color of the frame will appear with the blue background and then finally, the frame
dot show(), indicates that Frame is visible.

Now, so, if you run this program using java interpreter and then you will be able to see
the output that it will show to us. So, this is basically a Frame. Now I am just going to
little bit doing the changes here in the main program here in the resize method just 500,
500 that we have given it, now let us change it to 500 300 versus 500.

Now, we will see the size of the Frame will be changed automatically. So, you can see
that size of the Frame has been changed it is like this. So, if we change it then size of the
Frame will be changed again 100 versus 500 then you can understand how the size is
affecting because it is even minor change. So, very small changes in the pixel, now you

898
have to shape the program class why it is not. So, giving the different sizes you have
change the size save and then compile it they are not compiling right.

As we change the size and we have just seen that how the size has been changed. So,
accordingly we can for example, if we see the 500 if we change this 600 versus 100, then
you can see how the changes will be there. So, that just for you can test up to your own
also you can see it how the different sizes of the frame can be created and the same can
be displayed it. So, this is for 600 100; 600 100; 600 100; 600 versus 100 if you give it
then its fine 600 600 is not good. So, 600 versus 100 listen to me then yeah exactly it is
like this. So, you can understand that if we change the size parameter it will change this
one.

(Refer Slide Time: 04:14)

Now so, this is the about how we can create a Frame and our next demonstration related
to the creation of a panel, just like the Frame creation will be panel Frame and panel
basically the two things are mostly same , except that the panel does not have any title
bar and here we can see we first create a Frame and we include one panel inside the
frame.

899
(Refer Slide Time: 04:33)

So, this is the basically method as we see first statement to get a frame and then Frame
having the title say Frame with Panel and then next means create the panel with the only
constructor it has there no string to be passed here like the frame.

And then resize frame and then resize panel everything we are doing here and then if we
run this program and here we can see we have not mentioned that the location of the
panel where it should be. So, by default it will go to the left and then top most corner
actually. However, we can paste the here you can see the panel the color background has
been chosen as yellow and then background of the Frame is blue and we can change it. If
we change anyone parameter accordingly the things will come into the change effect. So,
this is about creating panel and then frame.

Now, let us have a very simple example from the components, as you know there are
many components that is possible in java.awt we will just give a discussion about the
Button. So, Button however, a Button can be created and then how this Button can be
resized and then the same Button can be added. Now in this example as we see we first
create a Frame and then Frame inside this Frame we are planning to create one Button
we create a Button b as a Button and having the level on this Button as Click me and
then we decide the setBounds it is basically first two values indicate that x and y location
and then the next 2 values indicate width and height of the Button if we change anyone
value automatically Button will be changed.

900
And then size is basically setSize is basically give the size of the Frame actually because
it is a related to the Frame only and then setLayout it is basically now we have to make it
there we are not using any null layout manager. So, that is a null and then f dot set value
it is 2 that this is visible actually; that means, the whole the things the container con
containing a Button will be displayed to us.

Now, so, let us run this program I will be able to see the output here as you see this one
there many more things also can be done a Button can be with different color different
context and everything for this is the different constructor that we have discussed in the
Button class can be used for this purpose.

Now, setBounds as we see the size of the Button can be controlled here. So, as we have
mentioned the last two Buttons are re regarding the width and height if I change into 50
and 60 like. So, it is basically change of the Button size will be changed automatically
say may be yes. Now, let us see we have changed the Button size is there, yes now we
are save it ok.

(Refer Slide Time: 07:33)

So, compilation is done and then we are running it as we see here the Button is created
compared to the previous example as we see size has been controlled there and you know
the size of the Button also if we use a layout manger, that can be also controlled by h gap
and b gap that is another example we will discuss while we will give a demo of the
layout manger.

901
Now, let us have the next demonstration on the Checkbox. So, how the Checkbox can be
created as you know the Checkbox basically contains a number of items to the did there
and then it will have the Checkbox check window actually where the check can be either
ticked or without untick that is basically check or uncheck can be there now here the say
creating the checkbox as similar to the Button actually in that case we should take the
help of checkbox plus.

So, using the Checkbox plus we have created a checkbox1 button here and then title is
basically C plus plus, then another checkbox also we have created like Java and then we
just add this checkbox in to the frame. So, f dot add(checkbox one) and f dot
add(checkbox two) it basically says that checkbox1 and checkbox2 is added into the
Frame and the rest of the thing is same as regarding the configuration of the Frame.

Now, here you can see for the checkbox2 we make the second parameter as true whereas,
for the checkbox1 we did not mention any second parameter by default it is false. So, if
the true means this checkbox will appear with a tick mark like. So, now, if we see the
output of this program this is basically a Frame base not an applet base. So, we can see
exactly here. So, the two checkbox C plus plus and java where the second checkbox is
tick; that means, it is true checkbox is true.

Now, if we click the mouse there and there you can see the tick button will be check
changed there so, but here in this case we ticked it, but there is no event generated
because we have not used any event handling mechanism here in this particular example.
Whenever we add some event when handling concept then it will be basically do if we
check this one.

902
(Refer Slide Time: 09:40)

Our next example CheckboxGroup; it is similar to the Checkbox or itself, but is a group
of items can be padded together here. Now here you can see we create a CheckboxGroup
with 3 items 2 items one is fine. So, create the CheckBox1and CheckBox2 add these two
Checkboxes into the CheckboxGroup. So, this is basically the procedure and we have
done it and we add finally, all the CheckboxGroup into the frame.

So, here this is basically we adding the CheckboxGroup into the Frame. So, it over and
then if we run it, then we can see the CheckboxGroup how it will look like. So, as we see
here and so, it is just similar to the Checkbox where actually, but it is a group this one
and little bit difference as we see here in case of simple Checkbox the check window
appears is basically square, but is a color as a round shape circle type and it is a
difference between the Checkbox and then CheckboxGroup.

903
(Refer Slide Time: 10:59)

Now, we will see exactly how the Label can be included in a count container, in a Frame
suppose. Here we create a first Frame and then we can see in this example we create a
Label the 2 Label are created l1 and l2 and the 2 Labels are labeled as First Label and
then Second Label and then we just position the Label into certain location which is
mentioned here including its sides and then Second Label also and finally, we add the 2
levels l1 and l2 into the Frame and Frame is configured. And as we see that it will
basically gives an output containing 2 Labels on the Frame. As you see here the First
Label and the Second Label as these are name of the level here 2 Labels are the space on
the container.

So, this way right. Now whatever the example that we have considered in a particular a
program we can include all these things; that means, your container can contains many
components; although here in every example we are using the different components to be
included into the Frame. Our next example TextField. Now how a TextField can be
created this example will tell us and then within the TextField something can be written
also if you write it and then that component will be sensed by the event generator event
handler and event handler will do could accordingly anyway.

So, event handling now skipped here in this example simply we will see exactly how a
TextField can be added into a Frame. So, for this we just write an application program
here first create a Frame and then we create a text for there are 2 TextFields are created

904
t 1 and t 2 are there. So, t 1 is basically text 4 with initial default ha what is called the
levels are there will come to IIT. And then the setBounds is always there in which
location this TextField will be floated and then what is the size of the TextField, as you
can change the location automatically different positions it will float and then size also
accordingly can be changed.

And then again second is a second is also used with different level NPTEL Java Tutorial
like and then setBounds also decided the same as the first t1 and then finally, we had t1
and t 2 into the Frame and then Frame is to be configured and then that is all this is about
the creating TextField in our program.

(Refer Slide Time: 13:20)

Now, we can run this program and as we see here yes. So, this is there and we can move
the mouse pointer into any TextField and if we mouse it here and you can type anything.
So, there is a type whatever you can type it is there and this type will go and then we can
include it there. So, this way the TextField is basically allow a user to type something
from the user using keyboard, positioning the mouse pointing first there and user type
the text there. All these things will be illustrated in the next demonstration session.

905
(Refer Slide Time: 14:01)

Now, like TextField there is another one example it is called the TextArea; now text like
TextField the TextArea is there, but TextField has the limited number of character that it
can accommodate whereas, TextArea is basically is a sufficient area of the things are can
be accommodate here. So, as you know if you want to include one para like say then you
should consider the TextArea instead of TextField actually and so, it basically give a
display a good volume of strings actually.

Now, here as the example as we see here we create a Frame first and within this Frame
we create a TextArea a and then we just this TextArea include the default text like
welcome to IIT KGP and then that size of the TextArea is decided as setBounds is there;
that means, this is the amount of string characters that you can include into this area and
then finally, we add this TextArea into the Frame and then Frame is configured and then
Frame is visible as to so, that we can see the output.

As you see here these are default text we can write as much space it is possible total
within the TextArea it is shown there and one more thing that you can note is that the
TextArea whenever you de can define with the. And then TextField the difference
between the TextField and TextArea is that TextField is a smaller in size of course,
whereas, TextArea is larger in size, but there is one more difference that you probably
noticed it where there is both side the two scrollbar area is coming.

906
So, if you go on typing much more text and everything. So, within the Scrollbar area you
can I means scroll the entire area of the TextArea that is possible to have it there. So,
Scrollbar automatically it is coming into your TextArea. So, usually TextArea is always
accompanied with both scrollbar horizontal and as well as vertical we do not have to
explicitly prepare it to be added, although scroll bar can be added in the independently
other than this one also.

So, this is a very good example of TextArea and then it has many application in the
context of many application since actually. Our next example is basically showing
exactly List is ok.

(Refer Slide Time: 16:22)

So, List of items that can be included and those can be processed. So, here basically an
windows program people many times use the List and then from the list one item can be
selected it is like this is basically objective and here we can see there are 2 types actually
List and choice item , this example is basically List; we create l1 we create one List is
called the ll and we just create also a Frame because we want to include this List in a
Frame and then; obviously, the List is size of the List is specified by the setBounds
method and then l1 is added into the List.

So, in l1 List we add few items here as we can see if we go on adding it will just add into
the items like in this example as we see 3 items has been added namely item 1 item 2 and
item 3 although we have discussed that List of size 5; that means, two are remained

907
vacant actually. So, even if we do not do it also it is there; however, if we go for adding
more than 5 actually. So, only it will consider up to maximum 5 and the rest of the things
will be automatically discarded and then finally, we add this list into the Frame and
Frame is size.

So, now we will see here this example includes a List of 5 items presently it contains
only 2 items in it and it shows this one. As you see here if we select anyone item as we
see it is basically showing the selection. So, automatically it is done within a very simple
code you can see, how many things that we can do it. Now we will see alternate it to list
items also there is another variations of this list is called the Choice. So, Choice is
similar to the List, but the difference you can see if we run the example here.

First let us see the example run this one Choice, we can see exactly what is the different
from the List and Choice here you can see. The Choice basically List shows all the items
which basically it has. Whereas, choice will not show it, but if we there is a small
scrolling see if we click it all the items which are there inside the choices will be
included here and if we select anyone that will be highlighted into the choice item. So, if
we like that ok.

So, this is the idea it is very similar to, but it is more elegant in case of Choice than the
list and after all you have faced many application where you can see this kind of
examples in your example.

(Refer Slide Time: 19:07)

908
Now our next example is Scrollbar. We have already shown that using TextArea how the
Scrollbar can be automatically coming into there, but the Scrollbar can be used in a
different way let us see exactly how the Scrollbar can be created and it can be included in
our Frame.

So, first we create a Frame and then we create a Scrollbar for this the class Scrollbar is to
be used. So, Scrollbar h is the name of the Scrollbar in this case and new Scrollbar and
here we have Scrollbar object for this we created some values are there HORIZONTAL;
that means, this is HORIZONTAL Scrollbar and then is basically starting and then
location actually in which location it should come here and then finally, it basically
visibility how much portion of the things Scrollbar will be visible. And finally, it is a
range some from which value to which value it is there although values is basically not
excursively to be there, but whenever Scrollbar is negotiated then the value automatically
then be handled by the event handler actually.

As we have not discussed the event handler. So, this part will be skipped here anyway
when later on and then finally, the size of the Scrollbar can be decided in the setBounds
and it can be added and then it can be added into the Frame. Now like HORIZONTAL
Scrollbar another VERTICAL Scrollbar also we have created and the same VERTICAL
Scrollbar is added into the Frame and the 2 Scrollbar. So, this example includes 2
Scrollbars one is HORIZONTAL and VERTICAL now let us see the output of this
program this way you can understand exactly how this thing it is working.

So, here you can see the 2 Scrollbar the first one is HORIZONTAL and second one is
VERTICAL. Now so, if we design one graphical user interface then accordingly you can
position these two Scrollbar where you want to do it and then finally, you can use it and
if can move it the using your mouse drag then you can move it and if you can release the
mouse like at a particular position it basically says that in which location of the mouse
drag is basically stopped if there location is basically what is the range that you have
mentioned according to their range.

And then again size of the Scrollbar you can see the Scrollbar window actually those are
basically dark one this is a size as a size is basically you can decide also very smaller
size larger size depending on the your program. So, you can customize it like anything.

909
So, this is the ScrollbarExample and so, far all the examples that I we have discussed
there are no applet is involved this is basically the Frame. Now we just discuss about one
example where all these things will be utilized I am discussing about a simple example
where a graphical user interface can be created by which user can enter the two what is
called the name and then idea of the students and then it can be used and then finally, it
can be stored in a file or like this one. So, this example we are creating using an applet.

(Refer Slide Time: 22:21)

So, here if we want to create a GUI using an applet. So, basically you have to create an
Applet. So, this is an Applet class extends Applet and here the event handling is
ActionListener we can skip it right. Now here you can see in this example we create one
TextField TextField we create a 3 TextField rather one two and result we like this and
also we create 3, but 4 Buttons namely add ,sub ,mul ,and div.

Now let us run this Applet then we can understand exactly what you are going to do it.
Now I am giving you the view of this Applet first and then I will explain the program so,
that you can understand ok. So, here now you keep it little bit bigger in size please.

910
(Refer Slide Time: 23:24)

So, now, let us keep this not so, much big size fine. Now so, this is basically the Applet
as we see. So, here we can see the acute TextFields which basically shown here these 2
TextFields also to understand that which is the TextField. So, 2 Labels also we have
mentioned here 3 Labels actually 3 TextFields 3 Labels.

The first Label is basically First Number and the Second Label is Second Number and
third Label is result and as we see for the First Label First Number there is a TextField
and then for the Second Number is called another TextField and another is the another
the result is another TextField and so, these are the 2 TextFields 3 TextFields are created
and then labels also there now in the next example as we see here.

So, Label l1 is created that is a first and then it basically Label.right means right
alignment actually so, the second Label and then third Label. So, 3 Labels are created
and then also we have defined TextFields like say one two results and then Button also
add sub mul and div and then for this one two three these are the TextField that we have
instantiated here and this is basically size of the TextField area as we see this is basically
the size.

And so, this is basically the and then finally, we add 4 Buttons the Label as adds then sub
mul and div and we add these Buttons. So, we define 4 Buttons here and finally, we see
we add all the elements. So, add Labels 3 Labels like and also we add TextField. So, this
is the add now here we are adding it and but adding you see following some order

911
because we do not have mentioned explicitly where they will be added here by default
they will be flow follow certain default what is called the layout management.

So, in this case actually there the different level management. So, this completes the look
of the applet that will be there and rest of the parts is basically relate to the action
handling. Now again go to the applet again that we have already created there if we type
something go there in the first one say 25 and then next is say 15 and then the result if
we see. So, the result add may be add. So, the result will be automatic.

Now, this basically here the event is generated and the event some result is completed
and then it will displayed. So, these are the next part of the program is related to this one.
Now, here you can see how an applet can be planned or can be designed so, that it can
include the components it is there. Our next example is the same thing, but not using
applet, but using frame.

(Refer Slide Time: 26:29)

So, here again the same, but using Frame little bit bigger in size right so, that you can
understand it. So, this you can see here the example is similar to the previous example
only and here we create the three TextFields now namely number, name and marks and
then Button enter and done.

So, two Buttons are created and then 3 TextField it is created, but you see it is not an
applet it is rather a component container window we can say and that window is created

912
in this program. As you see it is basically we create a Frame actually. So, this is a Frame
based right and so, we create a Frame in this Frame we create 3 TextFields then 2
Buttons and they are added into the Frame and then finally, Frame is resized and rest of
the things is relate the event handling.

Now, here if we type something here so, that type right. So, first name and then second
second name and then done or enter means it will go there and then again clean it. So,
this means one record is enter next you can do it like say a b c right and then done means
it is complete and then the application will closed it ok.

So, fine. So, this is basically an example and obviously, it is the idea is that how a Frame
can be designed and then how it can be handle and everything that is the most important
idea to discuss in this demonstration.

(Refer Slide Time: 28:17)

Now, we will discussed about. So, the layout management. As we have learned in the
theory class there are 4 different type of layout the FlowLayout, GridLayout, Border
Layout and card layout and. So, there are 4 examples that we can discuss here we can
give a demonstration for the 4 layout management scheme actually, let us have the
demonstration on the FlowLayout management.

As we know FlowLayout management by default will flow will arrange all the
components that you can add into a Frame like here and they can be added from left to

913
right in that sequence only the sequence you have mentioned here in your program. So,
here we have added say b one to b ten, 10 different Buttons and then that Buttons are
labeled as 1 2 3 right like and then we have added one Frame and those what Buttons are
added into the Frame into the Frame in that sense actually it will go into the layout
manager layout manger will place them from left to right; that means, Button one first
then Button 2 and so on till the size of the Frame occupy then actually.

Then the next row it will come next row then alignment may be from left to right in this
example we can by default is the right alignment and then something also can be done in
the LEFT also here actually if you see setLayout new FlowLayout this is the way that
layout manager can be involved.

(Refer Slide Time: 29:33)

In earlier example we have not mentioned this one. So, default is the flow outlet
manager, but here we are explicitly mentioning that we want to use the layout manager
as a FlowLayout and this is basically left aligned. Now let us run this program and we
will change the alignment the LEFT or RIGHT something like some sometime there is
center arrangement is also possible here ok.

As we see here. So, let now if we change this right like I can you will see exactly how
different output will occur for you. Now here if you see alignment is basically in the
same order, but alignment is basically from RIGHT. If this how it will change as this is
very small size whatever the portion it is possible to include it can be shown here, but if

914
the change size is changed then automatically they can adjust automatically into the total
area. So, in that sense it is basically little bit fluidic that mean it can maintain it, but is
left to right or right to right that is the only thing it is you can see it. So, this is about the
FlowLayout manager alternative to FlowLayout is the Border layout.

(Refer Slide Time: 30:50)

Here actually the total area canvas we can say can be divided into 5 regions center LEFT
RIGHT and then NORTH and SOUTH like.

(Refer Slide Time: 30:57)

915
So, this is a convention of the layout specification according to the BorderLayout again
we create here type what is called the components 5 Buttons actually here they are Label
as NORTH SOUTH EAST WEST CENTER and like this one and then we just adding
them into the Frame and following the layout manager is called the border layout. So, it
is basically we have to mention that in which location which particular component will
go.

So, BorderLayout dot NORTH basically we are adding Button b1 into that region it is
like this. Now if we run it we can mention it here as we see here. So, we have 4
components mainly the 5 components rather 5 Buttons are had been there, and you see
the size of the Button in the earlier example where we have to mention the size of the
Button explicitly by using setBounds, but we have not mentioned here.

By default whatever the area that is will be there this is basically default size is there.
However, size also can be controlled either using setBounds or using the h gap and b gap
of the this one. So, here for example, add(b1,BorderLayout.NORTH) then h gap in pixel
and b gap in pixel also can be considered. So, that this is a gap between two neighboring
either top or bottom or sides components the just the gap can be automatically mentioned
and accordingly the size will be fixed there. So, this is about the BorderLayout and then
next is basically the GridLayout.

(Refer Slide Time: 32:31)

916
As GridLayout basically Border Layout has only limitation that only 5 components can
be placed in the 5 distinct region where the GridLayout you can mention as many
component as you can place there, but in the form of a grid.

So, usually grid is basically having the number of rows and columns specification m
cross n. And now in this example as we see we create a GridLayout of size 3 cross 3 so;
that means, total line 9 is an example of 9 grids there we can mention what. So, 1 to 9
Buttons are there and they can be followed according the GridLayout pattern and then
they will be automatically from order the order they have mentioned in this or the order
we which we have added into the Frame actually, in the same order it will place it ok.

(Refer Slide Time: 33:33)

As we see here this is the display little bit bigger in size. So, I am just resizing by using
the mouse zooming here right ok. So, we can see it here that the different Buttons. See in
this case 9 Buttons are arranged into the GridLayout pattern following the GridLayout
manager. Our next example is CardLayout.

917
(Refer Slide Time: 34:06)

So, this is the last layout manager in the example. So, CardLayout means it is basically 3.
I mean you can add here in this example as we see 5 cards have been added, and all these
cards can be clicked so, that the next card can be popped in this example as we see the
layout dot next has been; that means, if we click the mouse then the next card will be
popped and ok. So, this is right here now the ok.

(Refer Slide Time: 34:35)

Let us see example about it we have actually each Card in this case includes one full
Button actually. So, little bit bigger in size fine. So, this is the one Card now if we click

918
on any portion here then the next Card will be displayed here as you see the next Card
then again click it next card. So, the different cards are there and again go on; so, then
fine right. So, Cards there is a 5 after that 5th Card is displayed if we again click on. So,
Card1 will be there so.

If it is a next means, in the order they have added according to that order card will be
there instead of next if we say previous, you can see the different result you can go
obtain. So, instead of next you write previous. So, layout dot previous this ok. So, in the
layout manger we can define next previous exactly ok. So, it is now created and if it is
previous means, Card1 after this it will go to the Card5 and then Card5 then Card4 and
so on. So, these basically gives an idea about how the different Card can be played
actually.

Now, it is basically Card means on clicking the different Frame will be popped up and
then this will give an output like this. So, we have discussed although the different
components individually, but actually in an application all the many components can be
included in one application in Applet like this one then the whole thing say for example,
in a calculator. So, there may be TextField, some label, some other Buttons and other
checkbox and everything can be included and they can be added there and this way you
can do it.

And finally, the manager so, layout management it basically helps a program
automatically fixing in which way all the component can be managed. We have
discussed about the FlowLayout manager, Border Layout manager, GridLayout manager
and then Card Layout manager all these managers I mean classes they there they are
defining AWT package as we have already disussed in theory and all the components are
also discuss they are readily defined in the Java dot AWT dot component class. So, they
are basically all Button Label they are the sub class of the component class and we can
add it.

We can add them either into an Applet or you can add them into a frame. So, you have
already discussed about how the particular component can be added, how a number of
components can be added either into a Frame or into an Applet, how the components can
be added into either Frame and Applet using say layout manager border card flow or
GridLayout manager like.

919
So, that is all this is basically illustration about the AWT and our next part that we have
to discuss about event handling because we are referring the event handling concept
many times now we will discuss event handling that will be the our next module
actually.

Thank you very much.

920
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 42
A W T Programming – III

Java is truly exceptional because it offers many supports to the programmers one
offering in the sense is A W T package. AWT package helps a programmer to develop
window programs very convenient conveniently and we have discussed many features
those are there in an AWT package and today we are going to discuss more important
possibly to my understanding is very important one features it is called the event
handling.

So, today our topics basically to discuss event handling mechanism in Java, this is
essential for any window based program development, now first we will discuss about
the concept of the event.

(Refer Slide Time: 01:08)

And as we know exactly what is an event in fact, in the context of any program
execution. So, as we know we are already familiar with few things about say applets and
as we see in case of applet there is a keyboard like right and then the applet contains say
calculator applet it contains a key now that key can be typed or key can be pre-pressed.

921
Now whenever key can be pressed then it will basically sense that which key has been
pressed. Similarly, if we move a mouse and then point a mouse on a component like say
button then and then the button is clicked, then the event is occurs in the sense that
button has been clicked and then for this event there will be some execution and then
system will do something whenever a user clicked a button.

Now, this basically is an event look like, now so for the graphical leisure interface is
concerned even it looks like this, but the event has more many implications in many
application areas. For example, when you are driving a car or a driver there are many
things are to be controlled and actually whenever the driver wants to control, for
example, to break a car. So basically, an event recreates similarly if we accelerate then
another event is created.

Now, in case of driving a car at the same time, many events can be generated can be
triggered, then the car has those machineries the mechanism by which all the events
which occur at any instant at any moment can be handled. So, there is basically handling
the events by means of some hardware mechanism or by means of some software
mechanism.

So, event handling possible in Java is basically to manage the event using some software
mechanism and that is also particularly in the context of GUI.

(Refer Slide Time: 03:31)

922
Now, here exactly this is a small example that you can see as you see here this is one
frame or you can say a plate which contains a button which is a Click Me. Now if the
user clicks this button then what will happen automatically the system can sense that user
has clicked a button and then it pops up a message another frame may be which is shown
here. So, it is basically the event that may be triggered by the user and corresponding to
the event there will be some action that will be performed by the system.

(Refer Slide Time: 04:12)

So, this is the idea about the events so for the event different types of events are
concerned there are two all the events that can be categorized into two broad categories
they are called the foreground event and background event. The events that we are going
to handle or discuss, this is in the context of graphically or interface is called the
foreground event.

On the other hand there are some events occurs in our computing system allow it they
are called the background event like operating systems handles background event
whenever press say any start button or alt tag alt to delete or there is a some response
from the timer or some other software when it is executing it faces some execution errors
divide by 0 errors like it basically causes some interaction we say and this interaction is
basically triggering an event and corresponding to the event system know exactly what to
do. So, this is called the background event.

923
Now, we will discuss mostly the foreground event and in Java what are the event
handling facilities that are most important.

(Refer Slide Time: 05:19)

Now, in the context of graphical user interface as we know a container may contains
many components here I have listed whatever the main components are possible that is
in GUI like button, checkbox, choice and all these things are there.

Now, so, here whenever a button is there this is basically button, checkbooks, the choice
all these components are created as a source of the event, that mean event can be
generated from this points only. An event can be generated from the scrollbar and event
can be generated from the list item, an event can be generated from the checkbox like
this. Now whenever a particular source of the event is excited; that means, triggered then
that basically the automatically one program that is there in the Java system which
basically watches that whether an event occurs in any component or not.

Whenever it says that some event has been triggered has been occurred, then it generates
one event and there are many events corresponding to the many different components.
For example, as we see in this slides from the bottom if it is a source it generates action
events. Similarly, if it is the list then also it is an action event wherever it is a check item
or choice the events that are generated automatically is called the item events likewise
scrollbar, it is called the adjustment event or text field it is for the text event.

924
(Refer Slide Time: 06:52)

What I want to say is that all the events are basically categorized according to that here.
So, what are the possible events that are possible in a GUI is listed here, as you see
action event, item event, component event and then container event, adjustment event,
text event focus, event windows event key event and mouse event.

The last two events are very much important because usually user gives any event I mean
creates your creates many events using these two device devices namely keyboard and
mouse. So, if the event is generated by the keyboard it is called the key events if the
event generated by the mouse it is called the mouse event and you note that they are not
exactly the component, but they can interact with the component that is the thing what I
want to me mention here.

And all the action items for example, related the button, list and then menu items like
this similar item event is related to checkbox, choice, checkbox or checkbox menu item
list like this. Now this list is very important you should know that which is the name of
the event corresponding to the which is the source, this slight in this is very important
and you should have the complete familiar about because the event that I have mentioned
is created by a particular class which is defined in AWT package.

925
(Refer Slide Time: 08:19)

Now, I am going to discuss about what are the different classes and interfaces that are
possible in an event. In a nutshell, what I want to mention here is that a source like a say
button or a checkbox or any window whatever it is there can generate an event and
whenever there is an event occurs it goes to listener items. Now, therefore, we should
have the two things in your mind, that event and correspond to an event the listeners
know what exactly the listener it is.

Now, event will be triggered by the user and then there should be some mechanism by
which if an event occurs any time at any moment it should be listened by someone else.
So, listener is another what is called the object I should say which basically listens to any
event if it occurs at any instant anywhere.

Now, so there is a listener who is watchful to receive any event if occurs in the device in
any windows elements. Now in Java all these events are basically; that means, that the
see basically whenever a source the source can create an event. So, it basically create an
object actually, the object is of type event and that object is defined I mean type of the
object is basically event, this is defining java.awt.event is a class, so there everything is
defined there.

Now, here the most important thing so for the java.awt.package is concerned is that all
the classes and interfaces which are basically responsible for either creating an event

926
whenever a source is interacted by a user or whenever an event is created is listened by
the listener.

So, these two things; that means, the event creation and then listening to an event is
basically handled by two items in the Java, that classes and interfaces which are defined
in java.awt.package.

(Refer Slide Time: 10:24)

Now, I will discuss first about event handling class truly there are many different types
of events possible and according to these events each events there are different classes
are there. Now, for example, there is one class called action event, now action event is
class basically responsible to hand to create an action event. Now action event occurs
because of the button, because of the checkbox, because of the choice like this one. So,
as we have already discussed that this is a different event from this different source.

Now, here again this continues or adapter, this is another type of event that occurs from
the container itself if there something changes happens or that means, any event is
triggered there.

927
(Refer Slide Time: 11:01)

So, likewise there are few more classes also here and I have listed all the classes that are
for your information and I should advise you to go through all the classes those are there
which basically causes an event. And whenever you are whenever dealing with a
particular elements particular components, then corresponding to those particular
components which event may occurs and corresponding to that event which class is
responsible that information you should have, so that you can do all the programming
correctly and effectively. So, these are the classes that I have already listed here.

(Refer Slide Time: 11:35)

928
Similar to the classes there are I will just discuss about ActionEvent classes those are
there is basically handling any ActionEvent which may occur whenever a user clicks a
button or a list item or menu item these are the things, so this is related to all this
components.

Now, the class details I do not want to discuss elaborately in this I have mentioned the
slides here I advise you to go through the slides read everything. And what I can say is
that for every class that is there in related to the handling event there is a constructor,
there is some constants involved and some methods involved and for this action event as
we see here in this slide 3 constructors are there and this constructor is basically as you
know the ActionEvent is automatically called.

So, there no need to call create any object explicitly; that means if you click a button
automatically the action event object will be created and we have to just say exactly hold
these objects for our further processing we will demo we will illustrate the concept
clearly whenever we discuss some example.

(Refer Slide Time: 12:47)

So, for this action event these are the constructors, apart from this constructors there are
only these constructors are there is no other methods and all these things for this an
action event. Now, this is another AdjustmentEvent it is the event that is related to the
scrollbar item whenever user negotiated the scrollbar then this event occurs and also this

929
class deals with constants and then constructors only 1 constructor and 2 methods are
there.

(Refer Slide Time: 13:12)

Now, ComponentEvent whenever some component is changed or component is resized


component is configured and all these things is there and so component event is involved
and these are the constructor there which is there in the ComponentEvent and then
constants also few constants as we have mentioned COMPONENT HIDDEN,
COMPONENT MOVED, COMPONENT RIZE, COMPONENT SHOWN.

Here component means a frame like, so if you resize a frame it basically triggers an
event if your component is closed there is an event occurs. So, corresponding to the
event it is basically these are some activities that action can be listened by some listener
objects like.

930
(Refer Slide Time: 13:51)

Now, so like this the container in an event is also there, a container is similar to the
component. So, here either container can be added or container can be removed,
whenever we close that event occurs, whenever we open that time it will occur if the like
this.

(Refer Slide Time: 14:07)

The FocusEvent is basically whenever there is a focus say keyboard needs to be focused
like whenever some event that has to be listened to like this. So, FocusEvent is there, it
has few values constant it is called and then constructors and methods.

931
(Refer Slide Time: 14:24)

And then InputEvent is basically is a superclass, is a superclass of that KeyEvent and


MousEevent which we are going to discuss shortly and this is the two most important
event handling mechanism by which the key and mouse can be controlled.

(Refer Slide Time: 14:35)

An ItemEvent is also, ItemEvent is related to the menu items or list or checkbox and
dealing with this and this is this class contains some constants constructors or method
which has been mentioned in the slides.

932
(Refer Slide Time: 14:52)

And then KeyEvent; KeyEvent means whenever there is a KEY PRESSED or there is a
KEY RELEASED or just typing a key. So, these are the three things that may occur they
are called modifiers. So, whenever I have the things is say per either KEY PRESSED or
KEY RELEASED or KEY TYPED, this event is generated. And for this event there are
two constructors as they see here the two constructors has the different parameters all
those parameters has their own meaning, say components source means from which
component it occurs because there may be more than one component in a program, it is
(Refer Time: 15:29).

And integer type means what type of component, whether KEY PRESSED or KEY
RELEASED or key typing long event means, it is at what time that event occurs and
integer modifiers means what is the modifier mode actually an integer code; that means,
what is the character that can be coded from this KeyTypes and a character key if it is a
KeyType like this one.

So, these are the different what is called the parameters that are there in the constructor,
what I want to say is that whenever one keypress is occurring all these values are
basically pa initialized; that means, object is created means all these values actually and
those values are very important to use in our program.

933
(Refer Slide Time: 16:05)

Now, MouseEvent like this KeyEvent, MouseEvent has new constants as we have
mentioned in a MOUSE CLICK, MOUSE DRAGGED, MOUSE ENTERED, MOUSE
EXITED, MOUSE MOVED, MOUSE RELEASE, MOUSE PRESSED MOUSE
WHEEL; MOUSE WHEEL is for the three-button mouse actually.

Now, so, these are the things that may happen; that means, the out of many types. So,
anyone of this things related to the mouse may occur and those things can be handled
and there are two methods I get KeyChar and then get KeyCode these are the basics if
you select one character, then which is the get key all these things can be selected and
can be obtained. And it has only 1 constructor as the name of the constructor is
MouseEvent same as the name of the class and the different parameters that is there in
the constructor it is there.

So, these are the constructor means these parameters can be generated automatically
whenever an event occurs and then the value. For example, if you want to note that at
what time mouse has been clicked I can get it from the long win. So, win value gives you
that if there is a MOUSE CLICKS, a MOUSE PRESSED or MOUSE RELEASED then
at the what is the time. So, these are the very important information that can be obtained
intake seen to the eye; that means, in which location in the component the mouse has
been clicked or released those kinds of things are there.

934
(Refer Slide Time: 17:39)

So, thus values are variations here whenever we have to process the event and TextEvent
is related to the handling the text filled area. So, it has only one value TEXT VALUE
CHANGED or not and then is it true or false like and it has only 1 constructor that the
constructor is basically what is the source and what is the type of the things there?

(Refer Slide Time: 17:55)

And this is a last one class that is there it is called the WindowEvent it has also few
constructors and then constants methods all these things related to this one. Now, related
to these classes so far the event handling is concerned whenever an event occurs the

935
event of any type of the class which I have discussed an object of that type will be
automatically created that is all.

Now, this is so, for the event so event occurrence is concerned. Now there is a for every
event there should be certain what is called the consequence now this consequence like
event generation it is not automatic. So, a user has to mention that what is the
consequence or what is the action that should be corresponding to an event. So, interface
basically gives the programmer facility to define their actions for every what is called the
events occurrence.

(Refer Slide Time: 18:54)

Now, here the different interfaces are there in those are defined already in the Java dot
AWT package as you know interface is basically in there is method is there, but a
methods are abstract. So, we have to implement the methods, we have to define the
methods according to our own need; that means if this event occurs then what will be the
action the consequence that you have to discuss.

So, using this interface co object you will be able to create our methods provided that we
know the name of the methods which are to be defined precisely corresponding to each
event.

936
(Refer Slide Time: 19:36)

Now, like say action listener is an interface only the method it is there action performed
ActionEvent. So, that is basically which action event that is the object automatically
created we have to pass an argument to that and then action perform interface will be
defined accordingly.

(Refer Slide Time: 19:53)

And then the adjustment listener is basically the method is there value change that needs
to be defined by the programmer.

937
(Refer Slide Time: 19:59)

The component listener has many methods like ComponentResize, ComponentMoved,


ComponentShown, ComponentHidden and those methods are need to be implemented.

(Refer Slide Time: 20:08)

Similarly, container listener, it has only 2 methods ComponentAdded and


ComponentRemoved, this has to be considered and then the object that has to be passed
is basically container event.

938
(Refer Slide Time: 20:21)

And then focus listener the object that has to be passed as a focused it event; that means,
this listener related to the FocusEvent.

(Refer Slide Time: 20:33)

And then FocuGain or FocusLost is a method and then item listener is the focus change
is the method needs to be mod overwritten.

939
(Refer Slide Time: 20:39)

And then key listener is the keyPressed or keyReleased or keyTyped, these are the three I
mean methods that user can modify in their program. So, there according to keyPressed
what will be the action, according to the keyRelease what will be the action, if a key is
typed then what will be the action like this one. So, the method can be customized by the
programmer according to their needs.

(Refer Slide Time: 21:01)

940
KeyListener is another important or listener is there it has method mouseClicked,
mouseEnter, mouseExited, mousePressed and mouseReleased those methods are need to
be modified.

(Refer Slide Time: 21:13)

And mouseDragged and mouseMoved also are the two other interface method.

(Refer Slide Time: 21:6)

MouseWheel listener the 3 button mouse you know so the mouse will have the mouse
wheel method is the listener here.

941
(Refer Slide Time: 21:25)

And text listener only one with a textChanged.

(Refer Slide Time: 28:28)

WindowFocusListener it has two method windowGainFocus, windowLostFocus.

942
(Refer Slide Time: 21:34)

And then window listener is a many method as we have mentioned windowsActivated,


windowClosed, windowClosing, windowDeactivated, windowDeiconified and
windowIconified and windowOpened.

Now, these are the interfaces we have mentioned here and it is also not possible to
discuss each event classes and corresponding to each event classes what are the action or
listeners are possible because it is too time-consuming you are advised to refer to some
materials, that is I have already mentioned in the first week of my lecture strikes where I
have given very a number of sources you can console all the sources to have the full
knowledge about it.

And that is this way you only you can learn much and much, but this is at the starting
point of course. So, at the starting point you should have the full concept about what are
the different classes are there to dealing with the inference, what are the different
interfaces are there to generate the event consequence all these things are there.

How to the methods are everything that you can have in your repository at your disposal
so that you can process then and accordingly the program can be written. So, I will give
you some examples so that you can understand how the events can be handled using this
one.

943
(Refer Slide Time: 22:48)

As the time is short I will not be able to cover all type of event source only mouse and
keyboard are the two events will be concerned. Now, anyway so what is the basic idea if
you have to write a program dealing with the event handling? So, there are only 2 steps
these are the very simple 2 steps in the first step that is called the registration procedure,
here basically we have to register an event listener.

So, here the idea about just simply in if you use the applet programming than in the init
method you just add one method like public wait at type of listener whether it is an
action listener is a mouse listener or keyboard listener, key listener or like this one or
mouse motion listener whatever it is there. So, public void adds say key listener; that
means, we are adding to key listener and what is the type of the object that it can handle,
for example, action event for the key mouse event for the mouse these kind of things are
there so it is like this.

And then implement the listener method, so, if it is supposed action event then the
method that you have to implement with the key pressed, key down key released
whatever it is related to this one. Similarly, if it is an add mouse listener is the listener
interface; that means, and then mouse event is the event occurs, then we have to
implement the method like say mouse pressed, mouse drag, mouse release, mouse move
whatever it is there.

944
So; that means, what will happen if there is a mouse pressed, mouse clicked and
accordingly we have to write the listener method, so that it happens then what will be the
actions that I mean event corresponding to the event, what will be the action are to be
performed. So, that is not, so these are two things are there so registration and then
implementation. So, better some illustration is required, so that you can understand these
two processes.

(Refer Slide Time: 24:44)

Anyway, so as you have just started summarizing this for fact is that whenever an event
occurs; that means, a user interacts any source like saying button or any list or items
whatever it is there automatically to this there will automatically an event will be created.
And this event will be created corresponding to this event there are many other
information since automatically stored in the objects and then event object is forwarded
to the listener method which is already registered in the program.

So, you can register as many as listener as it is possible or relevant so your program is
concerned. So, we just have to do it and here is let us have some example so that you can
understand the first I will discuss about handling mouse events.

945
(Refer Slide Time: 25:34)

And so for the MouseEvent is concerned as we have already mentioned these are the
mouseEvents that may happen MOUSE CLICK, MOUSE DRAG, MOUSE ENTER like
and these are the basic field value that can be; that means, if every mouse event have
occurred then these are the on value so the can be read by the program. So, that program
programmer can understand which it occurs because we have to do it automatically.

(Refer Slide Time: 25:59)

And then there is a constructor which basically, automatically the MouseEvent object
will be created, by these problems these are the different value that we can process it.

946
(Refer Slide Time: 26:08)

And then the methods that are possible so get x get y; that means, in which location a
mouse click or char that can be obtained like this one.

(Refer Slide Time: 26:16)

Now, there are two I mean interface as you have already learned about MouseListener
and MouseMotionListener interface. So that means, if it is a mouse click mouse pressed,
mouse released, a mouse listener if the mouse dragging is involved then mouse motion
listener interface are to be registered in your program.

947
(Refer Slide Time: 26:34)

And so for the mouse listener interface is concerned these are the method already you
have mentioned.

(Refer Slide Time: 26:39)

And for the mouse motion listener these are the two methods already there this means we
have to implement it.

948
(Refer Slide Time: 26:41)

Now, so for the dealing with a mouse event handling, so first what we have to do is that
either in init method or any beginning of any class declaration that is way to event
handling program we have to add this one. So, add MouseListener add
MouseMotionListener and then this is basically for the current object; current object
actually.

So, this is the public wide at mouse listener, there in now should not be any blank space
actually if is so blank space should be avoided and then the implement the interface
method as far the requirement of the programmer and that can be done immediately after
the init method so, that is the two procedures is there.

949
(Refer Slide Time: 27:24)

Now, let us have the examples for these things, as we see this is a small example that we
are going to discuss this is a scribble one applet and as you know the scribble applet
basically allows the user to I mean draw something on the some component or container
on a frame or maybe on applet. So, in this example as we see we are declaring one class
call the Scribble 1 extends Applet. So, it is a basically Applet so Applet will be there and
then it implements MouseListener and then MouseMotionListener. So, is two interfaces
are involved in this content, so this is a customized thing that you have to do it.

And these are the x and y are the two variables that needs to be maintained so we have
discussed it here and now let us see the public init method in this init method we have
registered the two interface the two listener actually here the add MouseListener and
addMouseMotionListener objects are to be registered.

So, this basically inputs or registration there and the this registration followed by the
declaration of the interface methods namely mousePressed and then mouseDragged the
two methods we have implemented here. So, it is very simple it will basically get the
current location of X value and the current location of Y value and then it will store into
last x and last y, so that is all.

So, whenever mouse pressed, is there it will just read what is the value of x and y it is
there and you know that e is the event. So, that event means whenever this an Applets

950
will occur so it will corresponding to this event that event e will be generated. So, that
this will basically be written this object event is there.

Now, so or here basically mousePressed, MouseEvent e as we see them whenever mouse


event occurs, so an event e is created and this is basically for that event the x and y
location is the coordinates of the x and y position in the area. And then mouseDragged it
is basically what we have done is so basically if this is the last position and this is the
current position so dragged means draw a line.

So, if the mouse is moved here and here so it draws a line automatically, so here line will
be drawn. So, if the mouse move and like this then automatically the line will be drawn
by the system and this is a routine it is here we have mentioned here. So, it basically so
just a graphic subject is created; that means, it is basically related to the drawing a
graphics when its line drawing will be there and that is why g dot line we have then and
for the g draw line we see last x last y and x y.

So, it is basically co what is the previous x y and that is the current x y draw line. So,
previous x y current x y like this, so this way you just dragging and as the dragging
continues it will draw the line whether the straight line or any curvy line whatever it is
there and so these are the methods so for the mousePressed and then mouseDragged is
concerned. Now there are few other methods also so for the MouseEvent a there is
concerned like mouseClick, mouseEnter, mousExited, mousePressed; mousePressed and
mouseReleased mousePressed is there already we have declared so it is no more required

And so these are the other methods those are remaining, now here I just do not have any
code for any method I to remain the wide method like. So, otherwise you can just simply
ignore all these the only two methods are involved, then you can define the two methods
and this completes the scribble applets and if you run the scribble applet you can see it
will to give the output and that will be discussed whenever we have the complete
demonstration.

951
(Refer Slide Time: 31:06)

Now, another example let us see the scribble 2 applets it is little bit earlier one it is
basically using the latest Java JDK version so and this is the one example which is
basically oral one using the Java 1.0 version, but it is pretty useful and then very simple
little bit different methods and classes are there I quickly mention about. So, here
basically as we see in this example we have to create one-button call the clear and also
we have to create one checkbox the checkbox will if you click it the checkbox will give
you the number of colors that are there.

So, user it can clear it then basically it will whatever the user has typed it will be cleaned
from here and whenever user click this one so a list item will be generated from this list
item which is if the user can select any item corresponds this is an item the color will be
selected. So, here as we see the 2 components are created one is called the Button and
then another is called the current color choice, so these are the two components are
created here.

Button this is for the button and this is the choice this is choice basically are this one so
these two buttons are created. Now in the init method as we see we have just simply set
background all these things we have already known about it here and these are the
variable that is declared they have been initialized that one and then all the buttons and
then choices those are declared they have been added into the same it is basically this is
applet so it is added to the applet.

952
(Refer Slide Time: 32:46)

And then finally, we just create the choices so these basically quote to create the choice
component it has the so many elements in it and then finally, we add these choices into
the container, so this is the method that we have declared here. Now, here see this is
basically the method that we have to overwrite this method is defined in Java dot AWT
MouseEvent declaration and there Event e, int x, int y is basically showing there what is
the event; that means, if it is a mouse event and x and y means in which location the
mouse event occurs.

So, this is basically the method as per the old version of the Java 1.0 package and then it
is basically same as the earlier one. So, this basically define mouse down; that means, if
a mouse if fixed and this is a mouseDragged, it is similar the mouseDragged listener
method actually that we have already discussed in the last example Event x and y is a
same thing. So it is there setColor basically if the color is chosen by this. So, the current
color set color according to this color it will draw; that means, here as we see user can set
a color and according to this color if it is drawn then it will draw like.

So, if it is a pink color and then it is pink color will be drawn and so on. So, there is a
very nice applet is very simple only few lines quotes are there and that is why this AWT
program is called a lightweight process you see you can find many things which are
automatically done by you only you have to just play and plug that is all and which is
basically not possible in any other programming language actually that you can do it

953
from here. So, this is the idea about; this is the idea about the two examples, so mouse
event handling is concerned.

(Refer Slide Time: 34:35)

Now, I will discuss about another example this example is MouseListener is very same
similar example I will just quickly have it. So, add MouseListener is basically
MouseListener in this case, this is basically creating the graphics for us; that means, this
is a frame where it is basically create a frame in this example and here these are the
method that we have overwritten it is very simple MouseEvent method, mouseClick it is
just simply mouseClick and like that.

954
(Refer Slide Time: 35:07)

So, this way it will just whenever some clicks or occurrence click is occurred so it will
basically response through that and then object will be created like this kind of output
you can get it. Now, handling the keyboard event this is then let us see how the keyboard
can be handled.

(Refer Slide Time: 35:17)

Here as we have already discussed it is basically whenever keyboard event occurs there
is a key event object will be created and this object has the three different values are
there means keyPressed, keyReleased and keyTyped.

955
(Refer Slide Time: 35:30)

(Refer Slide Time: 35:32)

And then it also has the many other this is also there so for the different keys are
concerned because in your keyboard whatever the qwerty keyboard that we use it in
general, it has many function keys alter control c then modifier and then some are non
functional keys and then character keys numeric keys all these things are there.

956
(Refer Slide Time: 35:54)

So, according to these things it basically deals with the different values that it can need
from the keyboard and it has the two methods the get Char and then get Key, basically
what is the character that is in the thing and get Key is basically written ASCII values the
right.

(Refer Slide Time: 36:04)

And so for the listener, it concerned it has only one listener keyListener method is there.
So, add a key listener to the accomplished any unique method or any at the beginning of
any program that you have to implement and then in addition to this add keyListener that

957
you have to use also requires focus method to be included here. So, these are the two
things that need to be added first and then once it is there this is a registration procedure,
then rest for rest of the part is implementing the three methods whichever relevant to
your program execution the keyPressed, keyReleased and keyTyped.

(Refer Slide Time: 36:39)

Now, I will discuss about a small example by which you can understand about my
methods here. Now in this example as we see here these are the registration process and
these are the basically interface implementation related to the keypress event as we see
whenever key event occurs key is automatically generated we can read the values of this
key objects whatever the according to the constructor that we have already defined and
then we will be able to handle it.

So, if this program is run it will basically all the times it will prompt that what are the
key events it occurs in your system.

958
(Refer Slide Time: 37:13)

And then this is the another example and then if this example is a similar to that one also
it has also like registration method as the previous one, but here are different function
key that it can be because the different function it can identify and accordingly it can
bring it and other keyEvent also keyPressed, keyReleased, keyTyped for the sake of
simplicity I have mentioned here. So, that you can write the code of your own according
to this event and then you can get the result here.

So this is basically the just a starting point we have discussed because event handling is
not a simple task to understand so easily, but as the time is short, so we do not have any
other things to discuss here. But in our next demonstration when we will discuss it a lot
of many things also will be demonstrated to you so that you can understand about it more
in a detailed manner.

Thank you very much.

959
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 43
Swing Programming - I

We have learned about AWT and AWT is sufficient enough to develop any graphical
user interface based program. However, Java developer was not so, happy with the
AWT, they dream to give something more than AWT which should be more elegant and
then user friendly I should say rather programmer friendly; that means, programmer will
find it so, easy to include there those components into their program and that is basically
the process of it is called that in a light weight way to develop this thing without much of
the code details they can develop their window program.

So, with this m Java developer introduced from version 6 onwards another utility
package API it is called the Java swing. So, in today’s lecture we will discussed first part
of the Java Swing because it is so, vast that we should take at least 2 modules to cover
the entire package one by one. So, first we will discussed about exactly what is the
Swing.

(Refer Slide Time: 01:25)

As I told you Java developer introduced it in version 6 onwards, but version 5 and lower
version Java Swing is was not available. Now Java Swing is basically is a part of Java

960
foundation classes which is the one foundation programs it is developed usually the
oracle to make the Java Swing is more platform independent.

So, Java Swing in fact, provides a better light weight components than AWT in the sense
light weight means we understand that user a programmer can do many things without
knowing exactly how all those things been done. That means, we do not have to bother
about the implementation details only just idea is that, if this thing is available just use it
and then solve your problem. So, it is just like a very good library we can say very
sensible library rather ok, so, that we can get many different utilities easily comfortably.

Now, so, Java that is a Swing the swing is included in one package you see it is not
exactly same as the java dot package name like, but it is the new thing javax dot swing.
So, javax dot swing package is there it is again whenever you install jdk right with your
latest version then you will be able to automatically install it is bundle with jdk itself.

Now, the these javax swing package contains many components as we have already
familiar to some components like button test field list menu item like this it is there, but
whenever the to make it difference from the swing component to AWT component, then
they use basically one more capital characters preponed to each component like say
JButton is for button in swing, JTextField is a text field in swing and like this one.

So, a ‘J’ characters are preponed to each component to. So, indicate that it is from the
swing actually. So, a now all those buttons are there; obviously, question that are is then
what is the difference from this button to JButton or like this and why JButton is more
preferable than the button we will able to understand these things when we will start our
discussion about the swing component, definitely it has more advantages and first of all
the thing is that all the component that will appear in a interface looks may much elegant
than the component that you can develop with the AWT.

961
(Refer Slide Time: 04:13)

Anyways, so, there are some salient difference between the two things that is AWT and
Swing. The first thing is that AWT components are platform dependent this means that is
java environment is required in order to run all those things no other environment you
can use it.

However, Java Swing is platform independent whatever be the environment absolutely


you so, you do not have to bother you can use it. And AWT a components are heavy
weights; heavy weights means many thing that you have to write the codes of your own
and they are not they are much abstract rather whereas, Swing components is much more
abstract than the AWT components this means that you do not have to bother about how
all those things coming and then how all those things will be implemented you just
simply plug and play.

And AWT does not support pluggable look and feel; that means, whatever the idea that it
looks like it is really coming it is not like that. So, sometimes it show something it is
appearing in a different form like, but it is basically pluggable look and feel. So, what
exactly it looks like you can find it like that. AWT provides less component compared to
the Swing because it has only few; however, Swing provides much more components
then the AWT components such as tables, lists, then scrollpanes, tabbedpane and then
colorchooser, etc all those things were not there in AWT, but those are there here in Java
Swing.

962
And another advantage of having the Java Swing is basically they follow one concept in
graphical leisure intersplit programming is called the Model View Controller. So, it is
basically called MVC actually AWT does not follow MVC then model view controller
whereas, Swing follows MVC I do not want to discuss details about the MVC which is
not so much relevant to this discussion. Anyway this is the one way how the graphical
user interface can be developed.

(Refer Slide Time: 06:22)

Now, java is basically from the JFC; JFC developed by the oracle Java Foundation
Classes for developing the graphical interface related to oracle systems. So, it is from the
JFC only.

963
(Refer Slide Time: 06:37)

And then here is basically whatever the different classes are there so, for the JF Swing
package is concerned we have shown here as we see here as it is right. So, JComponent
is basically related to the component it is very same as the AWT components and in
addition to these things there is a container and then container has say panel and then
frame and all these things and other that thing dialog is there and container may be also
an Applet. So, it is the basic idea and that is basically called the Swing components ok.
So, Swing components basically as you see the JComponent is basically subclass of the
components; that means, whatever the facilities that is available in AWT, you can have it
here in swing; that means, both swing and AWT can be used together.

You can use anyone. So, that is why the idea it is there. So, they are all basically subclass
of the AWT component class that is there in AWT package. And that is why whenever
you have to use it we should import Java dot AWT dot star as well as Javax.Swing.*;
that means, to avail all the facility that is there and particularly the event handling
facilities are defined there in AWT itself.

So, that anyway you have to use AWT package while when the whether you use AWT or
in addition to AWT you use swing. So, this is the idea about the basic about the classes
that is there.

Now, we will discuss about the different components that is there in swing as it is there
is a large number of components as you have show told.

964
(Refer Slide Time: 08:28)

So, definitely it will take much time to discuss all the components. So, I will be little bit
fast about I am just showing what exactly the component it looks and then what are the
methods and then what are the other constructors that is there this is for your
information.

So, my suggestion would be that if you practice it with the example which is here given
in the slides as well as in the link that I have given and also you can practice any
program collecting from any other sources from net like an if you practice it if you run
then you can understand. Actually it is very difficult to learn from the very scares level
another in the very in depth. So, better idea would be to learn it by your own practice.
So, you have to practice it vigorously so, that you can learn it.

Now, first of all the component class that is there as you have already familiar to it has
few methods like say add component. So, if you use the add any component can be
added into some other either it is in a frame or it can be added into the applet like this
one. And it also has the set size method we have already familiar to that and set layout
and set visible those methods are already there and those methods should be also used in
when whenever you include some Java Swing component in our program.

965
(Refer Slide Time: 09:50)

(Refer Slide Time: 09:54)

And the Java Swing is basically first is that we will discussed about how the components
can be added from a more precisely, the Java Swing component can be added into our
program. There are mainly 3 ways I am giving you using a Frame we can add it. So, in
this example as we see we create a Frame and in this Frame we can add the thing these
are the most simplest way.

On the other hand we can create another way also by using the constructor and here is
one thing you can see in this example, we create a frame and then this frame is basically

966
using a constructor of this class which is basically the main program, there we can in
include it and then that constructor can be called for that.

So, this is the one way of doing these things, it is basically same impact. So, this is the
one way within the main program, without any creating subclass we can do it, but here
creating a subclass we can do it and then you can use it. So, this is more useful because if
we developed one and then same class can be used in some other program also this is an
example like.

(Refer Slide Time: 11:05)

And another way the third way it is basically it is extending the Frame. It is almost the
same as the previous one what is that this is basically class extend the frame and then the
same way it is like this one. So, basically whether you can inherits a frame or not, in that
case this basically program is limited to only Frame, but in the previous example you can
create a Frame you can add it you can get other maybe panel, you can add some things
into that panel or something else like.

So, whatever the way you want to have it you can do it. So, these are the different way
that we will follow we usually follow to include the swing components in our program
anyway. So, any one method you can use it, but for the demonstration or for the
illustration, we will consider the second method that we have discussed ok. So, these are
the different way the frame the Java Swing component can be added into the frame and
we will discuss the different classes one by one.

967
(Refer Slide Time: 12:10)

The first is JButton. JButton is basically as we have already familiar to this it is similar to
that.

(Refer Slide Time: 12:16)

But in addition to the concept that is there it has something different than the previous
one as we can see it is here. So, JButton icon as you can see this is basically default
without any level and this is basically a button which will appear with certain level on it
and this is basically one important Icon i; where icon is a class that is defined in the java
dot Graphics dot Image and in that icon is basically shows an image; that means, a button

968
can includes an image. So, this is the idea about this one so; that means, a button can
include nothing a button can include simple a text as a level, a button can include as an
image also.

(Refer Slide Time: 12:57)

So, here is an example as a simple Button as we see this button is created and floated on
a frame and then level of the Button is clicked here. And then another Button which is
here as we see here text field and then the Button is also can be just here the basically the
idea it is that if we click here and then this text field will appear.

(Refer Slide Time: 13:08)

969
So, this is basically action. So, what I want to see here is that all the event handling
routine that we have already learnt also equally applicable to it also; that means, add
ActionListener and then you can define the listener methods all these things.

As we see here in this program we do the same thing, we add action listener all the
button and then we define the method for that action perform and then basically here is
that whenever a button is clicked it will appear this kind of text. So, all.

(Refer Slide Time: 13:58)

So, whatever the action handling mechanisms we have already learnt, that they can be
applicable to this also. And this example indicates that with a Button can include an
image as you see an image is also there on the Button itself. So, there are many small
image can be embedded into the Button to go some more good feeling and good looking.

970
(Refer Slide Time: 14:19)

Now, JLable same as the AWT Lable is basically same.

(Refer Slide Time: 14:19)

There is such different it has 3 4 different constructors.

971
(Refer Slide Time: 14:27)

And also it has 5 different methods for accessing its or related to the JLable we can have
the different information by virtue of all these methods it is there.

(Refer Slide Time: 14:32)

And this is an example as we see it basically display 2 Lables First Lable and Second
Lable, the methods is almost same AWT which we have already discussed. So, I do not
want to elaborate it.

972
(Refer Slide Time: 14:52)

Same thing is there and then again any event can be added into this Lable as we have
seen here. So, we can type it something and then if we type it, then the button you can
use it and then to have many other things are there. So, it is action listing all these
performance is also added can be added to a component as we have discussed.

(Refer Slide Time: 15:16)

JTextField is not similar to the same text field it is there.

973
(Refer Slide Time: 15:24)

And it is an example of the text field area it is there and it has so, many constructors 4
constructors and then 4 methods.

(Refer Slide Time: 15:28)

And here is an example as we see is very similar to the same example as AWT, this
program includes 2 Text Field with default state welcome to IIT Kharagpur and AWT
tutorial like.

974
(Refer Slide Time: 15:40)

And then action also can be added into any program like. So, here also another example
JTestField with certain action added into there. Here is basically if you type something in
this example if we type something say 5 and 10 and then plus you can add. So, 15 will
appear. So, here is basically 3 Text Fields which is initially empty, but we have added
event so, that if we type something here and there and then add it then result will be
automatically come into this Text Field. So, the idea it is like this. So, action can be
added in this. So, you can understand that how these kind of things can be utilized in
your actual application.

(Refer Slide Time: 16:26)

975
So, this is the TextFieldExample that we have discussed this is an example.

(Refer Slide Time: 16:33)

And then text area also similar to the text area that we have discussed in the context of
AWT. It looks look like that.

(Refer Slide Time: 16:38)

It has 4 different methods and then 4 different construction and 5 different methods.

976
(Refer Slide Time: 16:41)

(Refer Slide Time: 16:45)

And these are very simple example that text field area that will come here like this.

977
(Refer Slide Time: 16:54)

And action listening can be also added with action listener how the text will work it is
shown there. Here is basically in this action listener one very important thing that you
can note it is very interesting. So, this is basically your text area, in this text area you can
add some type cut and paste also you can do no issue and then there is a button we have
used it which basically count words. Now if we click it then automatically all these word
count and then character count will come.

Now, how it is there you do not have to write any explicit code for that, you see what is
the code it is here? So, setText the l1 and l2 are the 2 lable l one and l two and then l1 dot
setText (“words ” “ plus words dot length ) that mean here this words dot length already
defined in the java dot at till how the lengths how many words are there in a text can be
calculated similarly text dot length also this is a method which will return how many
characters are there in this text.

So, it will display there. So, it is so, easy we do not have to do much programming
actually, you do not have to account how many words is with a very critical program as
you know probably in c or whatever it is other programming language. So, counting
character also not that you have to stand one by one for the entire text. It is just simply
the simple method that will help to do it very efficiently and effectively. So, this is a
different application that which is coming in my mind to explain then I have just
mentioned it.

978
(Refer Slide Time: 18:27)

And then PasswordField it is a new one item which was not there in AWT components
and you know the password is basically usually look like is it appear as a some wild
character like they will star star star. So, it hide the actual character that you have typed
it. So, this is this look like a text field area only, but it will appear with that kind of things
are there.

(Refer Slide Time: 18:46)

Now, so, first we the PasswordField constructor can be defined using these are the 3 4
constructors.

979
(Refer Slide Time: 18:54)

And it does not have any method and then this is a very simple example by which we can
see you can practice it that how a PasswordField can be included in your frame and this
is an example that you can find if you run this program.

(Refer Slide Time: 19:09)

And action listening also can be added there; that means, after getting the PasswordField
you can verify that whether this is a correct password or not and then through
verification you have to store I have to compare these things some store value
somewhere else like. So, all these things you can do it here user name password user

980
name may be the text field and password may be say PasswordField and then login if
you click it, then whatever the things that you have typed it login will be there.

(Refer Slide Time: 19:41)

So, here you have to write an event handling methods for login whenever a user click the
button login after giving text field login and then PasswordField password. So, this is the
example that you can see. Here is basically user name Debasis password is something as
it is there corrected. In this case we have just simply that value you have correctly read
from the user interaction and then you can print it.

(Refer Slide Time: 20:04)

981
Now, checkbox is JCheckBox is similar to the AWT checkbox and as we see the
checkbox is basically which lay option one. So, in this example as you see this is the
basically checkbox, it has the 3 items and then we can click here multiple click is also
possible or single click is also possible that you have to define it by means of its
appropriate constructor, whether you have to do the single click or you have to do the
multiple click.

(Refer Slide Time: 20:34)

And it has got 4 constructors and two methods only.

(Refer Slide Time: 20:37)

982
(Refer Slide Time: 20:40)

And this is a simple example how the JCheckBox can be done using a single multiple
click C++ and Java are the 2 checkbox choices in the checkbox is included and it looks
like that.

(Refer Slide Time: 20:54)

And JRadioButton radio button we have already familiar with the AWT it is also there,
but here the loops of the JButton is much more elegant than the AWT and this is an
example of a RadioButton.

983
(Refer Slide Time: 21:06)

Say button group actually the object that you have to create it and it has the 3
constructors.

(Refer Slide Time: 21:09)

And these are the so, many methods as you see.

984
(Refer Slide Time: 21:14)

And then this is an simple example and if you implement this example you can find this
kind of output that you can find it and this is a self explanatory. So, it has basically 2
RadioButtons as we can see one is A Male and then B Female and then you can select
anyone whichever you select it will be highlighted by a Button form.

And this is the example you can add more Buttons and then you can run it and you can
find it how it will appear.

(Refer Slide Time: 21:42)

985
And then JComboBox it is just similar to the list items there in AWT and here the in this
example as we see 2 ComboBox; ComboBox1 and ComboBox2 is created and in the
ComboBox1 there may be some items and in the ComboBox2 also some items. So, as
many as ComboBox can be included in any frame or any effects also and then anyone
items can be selected, which item you select that item will appear in the text field area in
the main ComboBox slide.

(Refer Slide Time: 22:11)

And these this has 3 constructors and then there are five methods declare in it.

(Refer Slide Time: 22:13)

986
(Refer Slide Time: 22:17)

This is a simple example for your practice, as you can run it then you can find it that this
is a one ComboBox that will appear and in your program.

(Refer Slide Time: 22:27)

Now, Java Swing JTable this is a new one addition compared to the AWT it is it was not
there in AWT, but it is here now this class JTable is basically showing how the entire
table can be displayed.

So, if there is a table already stored in your machine in a memory then that table can be
displayed here.

987
(Refer Slide Time: 22:45)

But in I have just these are this for the creating JTable it has only 2 constructors.

(Refer Slide Time: 22:51)

And then this is a simple program by which you can display one table here we have just
created a table in program itself.

And as you see this table has three rows and then column heading is ID, NAME and then
SALARY and the table will look like this as you see here. So, it is like this. So, here the
table is just for an example here, but you can create a set of objects having the different

988
fields and then we can get the value and then we can put in the table and then table can
be displayed.

(Refer Slide Time: 23:25)

(Refer Slide Time: 23:27)

JList is also similar to the list actually. And we do not have to discuss much about
because it is been in many way very similar to AWT list it has 3 constructor 4 methods.

989
(Refer Slide Time: 23:36)

And this is simple program you should practice it here actually it shows a list with 4
items it is defined there.

(Refer Slide Time: 23:45)

And JOptionPane it is also a new things which was not there in AWT. JOptionPane is
basically is a popup dialog box or sometimes it is called the message box whenever you
make some mistake automatically windows popup with a message box or window
actually. So, if you want to create any window like this with certain messages, then this

990
is the right way and if you select then means you have accepted and if you select stop
this view then you can do it.

(Refer Slide Time: 24:15)

So, this is the way the option pane can be created there are 3 constructors and then few
methods are there.

(Refer Slide Time: 24:18)

And this is an example to create a simple option pane with a message hello welcome to
IIT like. So, it is sometimes time to time we have to give our message to your user, then
you can do user the option pane.

991
(Refer Slide Time: 24:31)

And then JScrollBar bar is similar to the scrollbar bar that is there. So, is basically same
thing horizontal and vertical scrollbar can be created.

(Refer Slide Time: 24:39)

There are 3 constructor to create a Scrollbar.

992
(Refer Slide Time: 24:42)

And here is a simple example by which one Scrollbar can be created it is a vertical
scrollbar that we have created likewise horizontal Scrollbar, Scrollbar with more
animation and everything can be also done.

(Refer Slide Time: 24:55)

JMenuBar is very similar to JMenuBar is also a new things which was not there in AWT
is basically as you see this is the MenuBar actually this is the MenuBar if you click it
some other some Menu will appear like this one. So, the many MenuBar also can be
included in your program and this is the idea about the JMenuBar.

993
(Refer Slide Time: 25:20)

For this JMenuBar there is again few constructors are there. So, usually JMenuBar and
JMenuBar related to each other.

(Refer Slide Time: 25:27)

So, I will just give an idea about JMenuBar which is basically include some JMenu and
there is also JMenuItem. So, this is an example as we see here it basically includes
MenuItems 1 and i 2 and then it basically shows there and as you know for MenuItem
there will be sub menu. So, it is sub menu under sub menu all these things. So, those
things can be cleared. So, this program you can practice for your own understanding.

994
And then finally, the JPopupMenu; JPopupMenu is basically is a whenever something is
appear the menu will popup like.

(Refer Slide Time: 26:02)

And it is look like this. So, PopupMenu whenever you create it and then some menu will
appear.

(Refer Slide Time: 26:07)

It has 2 constructor as we see here on constructor without any argument another is which
string argument.

995
(Refer Slide Time: 26:15)

And here is a simple example that you can see this example as you see whenever some
things clicked. So, it will basically a PopupMenu will appear this is the PopupMenu and
then you can select anyone cut copy paste like.

As probably you know whenever you use some word or some other text reaching
document and whenever you have to a select the edit and then usually cut copy paste all
these things are there. So, it is just as the idea is very similar to that concept only. So, this
is the PopupMenu and then JavaSwingCheckboxMenu.

(Refer Slide Time: 26:52)

996
CheckBoxMenuItem is very similar to the CheckBoxMenu CheckBoxConcept there is a
AWT class.

(Refer Slide Time: 26:57)

It is basically under the component class in the other.

(Refer Slide Time: 27:03)

It has the so, many constructors usually little bit complex to use it.

997
(Refer Slide Time: 27:07)

And then this is an example. So, this example we you can see here in this example you
have added many thing button then JFrame Menu MenuBar MenuItem in the same
example and also action in (Refer Time: 27:25) event is also used here. So, you can
verify this algorithm this program and then you can check that how it is working. So, it is
just look like a JCheckBox menu item file, and file open close save as all these things
you can add it.

(Refer Slide Time: 27:38)

So, this is the part of the program that you can run it.

998
(Refer Slide Time: 27:41)

Anyway so, we have discussed about the Swing components, not the all components
there are few more components are there and from this understanding probably you have
heard about that the Swing is a new one compared to the AWT which was very old. And
using the swing components we can built many other we can include many elements
many components into our programs which was not possible in AWT. There are few
more what components are also that we have yet to discuss. So, those things will be
discussed in our next module.

Thank you very much.

999
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 44
Swing Programming – II

We are discussing about java swing and in the last module we have discussed some
components in it, and there are few more components that we are going to cover in this
module.

(Refer Slide Time: 00:33)

So, the first component that here JSeparator; JSeparator is a new one which was not there
in AWT and then JSeparator basically as it is shown here it looks like a separator in the
sense that it will basically divide the display area into two parts with the different setting
look like.

1000
(Refer Slide Time: 00:55)

(Refer Slide Time: 00:57)

And it has two constructors and the two methods.

1001
(Refer Slide Time: 00:59)

And there is a simple example that will show the usage of JSeparator in any widow
program as we see here.

So, this is basically the JSeparator. This JSeparator includes the menu and whenever you
click menu some items will appear here. So, in the JSeparator some other things also can
be added, we will discuss about the tab and other menus also can be added like and if
you see then menu item will disclaim it is there. So, this is basically the usage of the
JSeparator in your program and this program you can understand yourself and is very
simple that you will be able to follow it how it is worked there.

1002
(Refer Slide Time: 01:43)

And they progress bar usually we are familiar to whenever you are some downloading or
saving some file or copying some from one source to another, usually a progress bar will
show that how much percentage of things that we have done.

So, the progress bar is a dynamic component and this is a look of a clear progress bar.
Now in your java program also you can have a progress bar.

(Refer Slide Time: 02:03)

And then you can show it.

1003
(Refer Slide Time: 02:07)

So, there are 4 constructors to, do it and then it has some methods by which different
information about the progress bar can be extracted.

(Refer Slide Time: 02:11)

And this is a simple example by which you can show we have given the two outputs like
in a middle way or in the progress bar is working, and when the finish job is there. So,
this is a simple example that you can try and you can see how it will work in your
program.

1004
And then JTree this is very interesting one a swing component. A JTree actually we are
also familiar to these things whenever we browse a directory and then that. So, it
basically shows what are the subdirectories under a directory what are the files under the
subdirectories like.

(Refer Slide Time: 02:51)

So, the entire tree will look like this, it can be maintained using a component class only
from which the information can be obtained from the drive.

(Refer Slide Time: 03:01)

So, it has 3 constructors.

1005
(Refer Slide Time: 03:05)

And it is a simple example which basically shows how JTree can be shown can be used
as we see here, we declare is this is basically the one we can say the style is the one root
under this root there is a two nodes it is nodes under this again nodes there are subnodes
actually.

Now, you see how we can create it, is basically style it is basically the default mutable
mu t node this is the file it is there in class which is declared therein swing package; we
have to use it and then we can create style and then we can create other what is called the
menu t node like say color and font.

Now, here you see style.addcolor, that means we add color as a part of the style and then
add font as a part of the style like style under style color and under style font. Then we
can add some other mu note under this color. So, it is basically we define it and under
this color dot at a rate, this means we go into the color rate. So, this way trees of any
branches after the other branches can be created. So, this is the simple example which
basically tells you how the JJavaTree can be crated whenever it is required in your
program.

So, this is the idea about JTree and the next is JColorChooser this is also very interesting
probably you know whenever you use any word application like MS word and whenever
you have to decide the font of a color of a font, then you have to choose it and then color
can be chosen from a color pen.

1006
(Refer Slide Time: 04:49)

So, here is a color pen look like and you can choose any one color and then that color
can be settled there. Instead of writing color dot blue color dot green like any other color
can be added here

(Refer Slide Time: 05:09)

So, by default it will have this is the color chosen which say 200 colors like you can add
more colors into it also there are pro facilities those things can be done by this
constructor.

1007
(Refer Slide Time: 05:13)

And there is a method by which the color chooser items can which color it has been
chosen the value of that color can be used there.

(Refer Slide Time: 05:19)

So, again this is a simple pa program for the practice you can practice this program you
can see how the color can be chosen, here is basically one button is added and using this
button the action handler is there. If you click it the color chooser option will pop-up and
then from there you can select some color and the color will be selected and using that
color if you write something if you draw something, that will be with that color and then

1008
color can be reset. And here is also see whatever the recent color that you have used that
also will be displayed to you. It is a very similar to it is in the context of saying micro
(Refer Time: 05:57) or this kind of things it is there the same concept it can. So, using
this color chooser you can develop our very sophisticated and smart program in this
program.

(Refer Slide Time: 06:09)

And then tabbed pane is basically essential one component, which is also new not there
in the AWT and within these things it basically if you create a frame, in this frame a lot
of other tabs are there. If you know excel and you know probably at the bottom, there are
lot of tabs that will be there that tabs corresponding the page 1 page 2 or more probably
it is called the seat 1 seat 2 seat 3 like the one. So, these are the tab and you can rename
this tab. So, this name is seat 1 this is seat 2 or say photo album 1 album 2 album 3 or
whatever it is there.

So, it basically helps to develop a program develop a windows program which to


organize the different menu items on the frame itself and it can be placed again the
constructor is there, the tab can be placed either in the top or usually the bottom. So,
usually the by default the top tabbed pane is there and then otherwise you can customize
into according to your.

1009
(Refer Slide Time: 07:05)

So, here is basically JTabbedPane and then JTabbedPane in tab placement in it is


basically is the placement the 0 on these are the 2 things are there, otherwise in the left
side also items also 0 1 2 3 these are the different value that can be mentioned and this
basically table layout policy; that means, the tabbed pane if it is there if you want to add
more items into it, and then what is the layout manager that you can follow.

(Refer Slide Time: 07:29)

And it has a simple example for your practice again, you can see how the tabbed pane
will appear into a frame which is included in a container.

1010
(Refer Slide Time: 07:43)

And then JSlider is another one example which also knows which is not there is AWT,
and as you see this is a basically is a usual look of a slider using the mouse you can just
select a slider and then slider can be dragged to show that this is a position that you want
to have. So, this way the different values can be entered into the system and if you press
at the position the slider has released, it will basically get the same value and it returns to
the system.

(Refer Slide Time: 08:13)

It has a few constructors and then methods.

1011
(Refer Slide Time: 08:17)

And this is the one simple program for your practice, you can run it and you can see this
how it will work and then you can click using a mouse you can drag and move the slider
into any positions and release it like that.

And then JSpinner is also similar to the slider, but here actually the numerical value is a
conti at the continuous rage or some discrete and both can be defined can be utilized
here.

(Refer Slide Time: 08:39)

1012
Here is basically it is like look like whenever you have to select font size usually you
know in the Microsoft word or other word documents processor, there is basically this
kind of spinner is there. If you click it then it will change it if you click if you keep on
clicking there is a value automatically will increase and then it will release it then that
value will be selected and then if you press it then that value is selected like this.

(Refer Slide Time: 09:05)

So, this is a leisure look of a JSpinner and it has the two constructors and two methods.

(Refer Slide Time: 09:09)

1013
And this is the one simple example by which a JSpinner with some default values can be
planned and you can change the different values, there we can see the JSpinner whenever
it displays you with initial value phi and it has range 0 to 10. So, we can decide what is
the range. So, for example, 0 to 100 also we can decide it and this is basically the step;
that means, how much incrementation 0 1 like this 1 if we say 0.5; that means, the in the
rate of the increment that can be specified here. So, this is the different way the JSpinner
can be controlled you can run this program with different settings and then you can get
how the JSpinner will look like this here.

(Refer Slide Time: 09:51)

And JFileChooser is basically whenever you have to develop a system program like and
then JFileChooser is really more preferable. Here basically whatever the files are there in
the current directory it will select it and then it will display and then it will allow
generating many events by selecting a particular file and then saving it or copying it or
opening it whatever it is there. So, this basically look like the component according to
JFileChooser in java swing.

1014
(Refer Slide Time: 10:21)

It has four constructors.

(Refer Slide Time: 10:25)

And this is a simple program that you can check of your own, these are the different
folder that you have included here in this folder whatever the files it is there it basically
will be displayed there. So, you can try it and then you can have fun regarding running
and you see how it is there. If you specify the different directory according to the
directory whatever the files it is there, that files will be displayed automatically.

1015
(Refer Slide Time: 10:49)

And then JToggleButton it is also a button, but the difference that it has only toggling
either on-off or open closed or male-female this kind of things are there. So, the binary
pattern is there.

(Refer Slide Time: 11:03)

1016
(Refer Slide Time: 11:05)

It has two constructors so, many constructors and then methods.

(Refer Slide Time: 11:07)

And it is an example as we see we have created one button and then it has two fields on
and off and how this, if you click it here, automatically on, will be toggled to off and
whenever it is off it is clicked it or toggle to on. So, toggling is occurs whenever there is
an event occurs and then it can bis that button value will automatically say it accordingly
and then that value will be used for some other requirement that is there in your program.

1017
(Refer Slide Time: 11:39)

And then JToolBar it is very similar to the menu item itself it looks it has the two
constructors.

(Refer Slide Time: 11:45)

And then so, many methods are there.

(Refer Slide Time: 11:47)

1018
(Refer Slide Time: 11:49)

This is an example as we see the file edit option 1 like in under this option 1 so, many
other things are there. So, it is called the toolbar like it is just similar to the menu bar, but
it is special in the MS toolbar and we can use it. So, as it is used to develop some tools
that are the it is the name is a toolbar.

1019
(Refer Slide Time: 12:07)

And JViewport is just like a text area look like, but it is ja or it is also very similar to the
panel also has a special area that can be viewed in a separate way like.

(Refer Slide Time: 12:23)

And it has the two classes two nested class in it and then it has the two different values
and then constructor.

1020
(Refer Slide Time: 12:29)

(Refer Slide Time: 12:31)

Only one constructor and there are so, many methods.

1021
(Refer Slide Time: 12:33)

And it is an example which basically displays the viewport and then the background
everything can be chosen there and the different setting style the different theme also can
be included and those things you can use the different constructor to do that.

So, you can try with the same thing here I have used the default constructor, but my
advice is that you can try with the different constructor that I have already mentioned and
then on this program. It is applicable to all examples that I have instead there I have used
only one constructor, but for your practice for your learning you should try all these
things with the different constructors. And the different method also you can call once
this object is created you can see what is the method returns and then you can try to print
this method on the windows or you can try to print the method using (Refer Time: 13:23)
into the same frame like this one.

So, you can understand that what they are doing for you actually, and then this is just a
starting point. You have to ultimately you have to use to develop your program that you
can decide one project and then in for that project you can think that what you want to
have and according to try to realize it, and that is all basically this is the way of learning
this kind of concept it is there.

1022
(Refer Slide Time: 13:49)

So, this is the JViewpoint and then I will come to the container class there as you see this
is the component. There are so, many components we have covered in this module as
well in the last module and then. So, for the container is concerned there are 3 things are
there frame panel dialog box and 1 container is also applet. So, applet also can be added
here and although we have not used any example for that, but it is basically if you create
one program which extends an applet, and whatever the component you want to add can
be added into the applet also which we have already given enough illustration discussion
in the while we are discussing about AWT. So, an applet is very same we just ignore it
here in this discussion

Anyway. So, for the container is concerned as we see container includes window, it can
input panel and also frame dialog and it can also include an applet. So, these are the full
what is called the I mean concept. So, for the container in the java swing is concerned
there, and all those things are there in AWT itself. So, it is an addition with some better
what is called the look and feeling.

1023
(Refer Slide Time: 14:57)

Now, let us see what is the JPanel it is there and as we see a panel can include within
another panel and so, on so, on. So, it can be nested that is why it is called the nested
facility which was not there in AWT of course.

(Refer Slide Time: 15:09)

And it has the constructor like panel and then it has one pa argument w buffer; that
means, all the contents can be stored and the layout manager means which layout
manager if you want to add many more items into the panel itself, then which it the
layout manager that you have to follow. Layout manager concept is the same as the

1024
layout manager that we have discussed in java.awt; that means, flow layout water layout
grid layout char layout all those things are applicable here also.

That is why they are they do not have any explicit or special bearing in java swing that is
why it is not included here. And this is an example about how the panel can be there as
we see them here entirely this is basically a frame this is the entire frame, in this frame
the panel is there.

(Refer Slide Time: 15:47)

And in this panel, two buttons are added here. So, this is the example and the; for this
output the program will look like as it is shown here. So, you can run this program and
you can see the output, and you can change many parameters in a program that we have
used there and then you can see it. For example, the background of the panel can be
changed and then button instead of the button you can add some other components into it
whatever it is there.

You can do a lot of experiments, and starting this program you can start changing many
things and they learn it. So, this is the idea actually that I want to mention.

1025
(Refer Slide Time: 16:35)

And so, this is the panel and then like frame we have already familiar to frame concept
there is an AWT is the same concept it is here also. It is also nested class means the
frame is defined we inside the component class that is why it is called the nested class.

(Refer Slide Time: 16:49)

It has some fields like exit on close root pane checking to enable.

1026
(Refer Slide Time: 16:55)

These are the fields and it has the four constructors for the different way the frame can be
initialized actually; all constructors as per initializing the object whenever you create it.

So, there is a default constructor and then some graphics can be added it basically this
graphics is for style, a frame can be with different style shading color background all
these things are there. The frame can be added using some title also and both title and
then configure and also it is there frame can be without any title like this one.

(Refer Slide Time: 17:23)

1027
So, these are the constructor that can be used there while you are having the program and
there are so, many methods using these methods the information about the panel can be
extracted which can be utilized for controlling your program.

(Refer Slide Time: 17:33)

And this is a simple example as we see it is a frame and this frame includes on simple
button and then it will basically use it. And then this pa this program is as we see here a
level is also used in this frame. So, level, button, a button is level as button and then the
frame is created as a. So, frame it is their title is JFrame by example.

So, this is the one thing that we have used in a simple container, but the same thing again
if you can repeat it, here just only changed it what change you should do it? For example,
you want to include these things into an applet; that means, we want to add frame in their
applet, only simple change you should do public class JFrame ex extends applet and then
the main method should not be there. Instead of the main method you can write some
unique method here you can and then code include all these codes that is all it will
basically create a frame and then frame include some other elements like.

So, it is a simple that you have already experienced while we are discussing about AWT,
how a component can be added into an applet how a component can be added into a
frame like.

1028
(Refer Slide Time: 18:51)

So, this is the idea about the frame and then the calculator let us see one idea about. We
have already given one illustration about how a calculator will look like if we use AWT.
Now that time also we have explained we have mentioned that the calculator does not
pretty look good, and a lot of other stylings that you have to do from the programmer end
only so, that the calculator can look very good and more elegant is there.

However, java swing has a lot of simplicity; so that a calculator can be easily drawn
according to the nice view of each without much headache about the programmer here.
And as you see here this is a very good looking calculator and this is a calculator that we
can develop using swing components easily. So, I will give you the step by step whatever
the method that we can follow to develop such a calculator.

So, what are the method that is required and then designing a calculator is basically is a
first-time practice actually. If you can design a calculator successfully, then you can earn
a lot of confidence about how the swing can be utilized to develop an application for
your requirement that we can suit to your requirements.

Now, first the method that we should mention is that. So, we have to add with the
component which is the component that needs to be used that say suppose we have to
create this as a frame or is a panel, then you have to add this component and then add
other components those will be included in this one. So, here actually as we see wa; so
all buttons are there. So, we can see 16 buttons, as well as one, equals button total

1029
altogether 17 buttons are there and in addition to 17 buttons as we see 1 text field area is
there. So, as we see these are the 17 buttons right and this is basically the frame area and
in this frame area there is another text field also there.

So, the enter is the frame and in this frame, there is one text field area and these are the
button and this 1 there. And buttons are now included in this component; obviously, we
can follow certain layout managers maybe say grid layout manager. So, we can create a
grid layout like this one then accordingly we can decide it. And if you use the flow
layout manager also we can do that whatever the way you can do no issues. So, you can
adjust it.

So, these are the 17 buttons you can customize to place it say suppose equals button you
can say this one. So, right-aligned or it is there, we have used the center-aligned for this
1 like. So, the anyways so, these are the buttons and then text field and then the
background these are the few things that you have to consider. So, for this calculator
design is concerned. You can change the color as an instead of blue maybe say silent
audio low whatever it is there anyway.

So, first we have to add the components and then all the components that will include
into the container, we have to define then and then adjust. And then finally, this will give
a look like which is basically just a structure, but we have to add the event now how the
event can be added? We have already discussed about we have to register the action
listener which action listener that you want to use here.

Here, the user, is the mouse being the action listener can be added there, add action
listener or specify the event to be controlled. And then background color whatever it is
there you can choose it size of the that calculator, also you can decide using set size
function and then setText; setText is basically set the text to the level to s; that means,
whatever the levels are there you can set the text like and then getText is basically
returned to the text that we have leveled it here. So, here basically 1 2 3 all these things
are text that we have set to each ba each button like and then it will basically return the
values. So, whether the value will be here in the text field or the value will be here all
those things can be here.

Now, in addition to this as we see these are the few other it is not the text actually, they
are basically for some operation and those operation means if we click it basically ca

1030
action is that whatever the results it is there and then what are the subsequent things will
be entered into this it will appear and then the addition of the two apparent will takes
place. So, this is the idea actually it is there.

Now, So, the idea is that we have to first design the layout and then place all the
components in it and then finally, define the event handling mechanism. So, these are the
steps major steps are involved here.

Now, let us see the stepwise everything one by one for each discussion here.

(Refer Slide Time: 23:45)

Now, this is the first step in this step what we do is that, as we see here let us go slowly
so, that you can understand about it. So, we are creating a calculator extends JFrame and
implement ActionListener because we want to include event there.

Now, So, first we create a JFrame and this is a filter frame and then text field that is
given as a l and a 0 s 1 and s 2 are the 3 strings that we have considered for the 2
apparent and one result actually. So, a calculator is the ba constructor initially they are
basically null stream and so initially, calculator basically has the null value like and then
we have to go to the mainframe main method. The main method creates a frame f using
swing calculator. So, it will be basically title here or it will be displayed here. So, in
calculator look like

So, with these things, it will basically create like this one.

1031
(Refer Slide Time: 24:47)

Now if we go put the next step; our step 2 and then in step 2 as we see we just use one
UIManger it is defined in the a java swing itself SetLookAndFeel.
UIManger.getSystemLookAndFeelClassName. So, is basically automatically defined
whichever the look that you can have. So, it is basically that this is a default look that we
have used it here and if suppose it is not able to decide this UIManger, then it will just
simply throw an error like this one.

Any way we can this one and get the system look and feel a class name is basically
giving you what are the UIManager that you are ee including. It is just same as the layout
manager concept it is a here in the java swing expression it is called the user interface
manager UIManger like.

Anyway then we create a calculator object c is a type we have already designed the
constructor there with initial value s 0 equals to s 1 equals to s 2 equals to non-string like
and then we create a text field they then text field is there and set editable; that means,
text field can be editable we can try something here also this is why it makes editable and
this is a false means no editable is possible. So, we cannot type anything here

And then we create so, many buttons b 0 to b nine for the numeric button and b 8 to b m
for addition subtraction and division multiplication for equal and b equal b equal lay b
equal other 2 also we have created it anyway. And then we add all these buttons or we

1032
create a button v 0 with some level as it is shown here. So, we are just we are continuing
the step 2 again, because there are few more items to be added there and so.

(Refer Slide Time: 26:39)

So, we are adding all these aa items all buttons are there na 0 to 9 buttons all these
basically some addition subtraction multiplication all these buttons are there with label
all these things are there and 10 b another button is created with dot. So, point is there
and b equal another button also will be added.

Now, JPanel p equals to the new panel we create 1 panel that is a panel is basically we
want to include this is basically rather we can say instead of the frame it is a panel
actually. So, in this panel, we want to add all these things there. Now we are defining the
action listener method here. So, bn bd bs ba for this class component actually here, in
this case, calculate the component. So, we are adding some methods that that if we press
bn then what of action that it will produce. So, these are the things it is declared here and
then. So, these are the action listener for all components those we have included here we
have added it there.

1033
(Refer Slide Time: 27:41)

And then finally, we add all the buttons and labels and text fields into the panel. So, this
is the statement for that. So, this completes the addition of all the elements into the
button side by side and then this one; what is my suggestion is that, you just do 1 step
and then run it check it that how it is going on. So, usually if you do everything together
and then you may not find that how it is working. So, first create the button and then you
complete it and then run it and see the output then add buttons then run it see how it is
coming to add text field run it see and these things. So, one by one if you do it you will
be able to have the good feeling that how it is working actually for you.

(Refer Slide Time: 28:33)

1034
And then next step is basically once all components are added into the button and we
have to define the action performed for each what is called the component. So, here is a
routine for action performed that you have to write it. Now here if s dot character 0; that
means, the first character is 0 or it is less than 9 or it is this one. So, this basically go on
appending here. So, if you type something here in this one. So, it will go on appending
here. So, 45.6. So, it will 45.6 will be display here like that.

So, this is basically the first thing that we are doing and then. So, this is basically the
continuation.

(Refer Slide Time: 29:19)

Next is here we are clearing if the different things are an app for example, if this equals
right this thing is there then is basically sum and then if this is c the clear. So, c button is
there if we then it is basically what will happen and then. So, these are the different
actions if something is happened for plus or minus or division then it is basically what it
will do all these things. So, whenever you face it with basically read one string another
read string. So, that those string and attach there and then result will be obtained. So, this
is the procedure by which the different actions can listen and for these actions, the
consequence can be added there and operation will be there.

1035
(Refer Slide Time: 30:11)

And finally, as we see here finally, the result will be stored there and the result will be
like this.

(Refer Slide Time: 30:17)

So, set text is a level that means text field area it can show it here. Now so, idea how a
calculator can be designed I have given an idea about it. So, two things are there first you
have to plan the entire layout and then according to the layout, we have to decide that
what are the different components are to be included and then you include those

1036
components and then you have to add the action handling mechanism that is all. So, this
way you can we will be able to do it.

So, this program as I have given for your practice I should advise you to run this
program, and then you will see how it is working and then part by part program
execution is better suggested so, that you can understand this concept clearly.

Anyway so, we have learned about AWT and Swing and these are the things very much
essential for window programming, other than the simple pro programming that we have
learned regarding multi-threading input-output handling and then in capsulation, all those
things are there, but this will add more color to your programming arena actually. And
here obviously, you can have the answer that whether both sw string and AWT can be
punched together or not; obviously, it is possible and then as you see if you compare
AWT and string then they are comparable in terms of many other parameters, but 1
parameters is that swing gives you much more elements than the AWT.

It is much much more actually. Now I just slip it as an exercise that how many classes
that you can use. So, for the AWT is concerned and how many swings it is there. Now
you can count it and you can just learn it that swing is mo much more elaborative more
voluminous. However, easier than the AWT to use it and it gives you more what is called
the smart-looking program development.

So, thank you for your attending this module.

1037
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 45
Demonstration –XVI

So, I welcome you to this Demonstration session. This demonstration is based on the
topic on event handling demo event handling mechanism in Java, which we have
covered in the last module under it AWT programming part 3.

(Refer Slide Time: 00:35)

Now, we know exactly what is an event handling concept it is there and in our theoretical
class also we have discussed about few examples like Scribble 1, the Scribble 2 and then
the MouseListener example and also we have demo you have explained how the
keyboard events can be handled and then finally, we have given an idea about the
calculator.

So, in this demonstration we will again repeat the same thing, but in detail manner so,
that you can understand how the event handling activities are carried out.

1038
(Refer Slide Time: 01:13)

So, let us have the first demonstration this is regarding the design of a scribble applet. As
you know scribble applet basically gives user draw something on the applet or I mean on
the component container itself either on the frame or it is on the applet. Now this scribble
applet scribble example that we are going to discuss is basically applied version.

So, first we want to extend this program as an applet class and then we add the event list
event and we have to register the event handler routine namely, in this example basically
related to the mouse event handling. So, we have to add or you have to register two
listener namely MouseListener and MouseMotionListener. And then we have to define
implement the event handling method. So, in this case the method which are very
importance are the mouse based method and then MouseDragged method.

Now, these two methods are defining the interface MouseListener and the mouse
MotionListener interface. So, you have to implement it here. Now we will implement
there are some other methods also those are there in these interfaces namely
mouseClicked mouseMoved mousePressed mouseExited and then mouseReleased oh
sorry mousePressed is already you have implemented. So, mouseClick mouseMove
mouseEnter mouseExited mouseReleased all these things. So, those interfaces can be
also implemented we will just give an idea how the impli such a in interface method can
be implemented.

1039
Now, let us see the program here as you have displayed here, and this program as we see
this is the init method this init method is very important in case of applet the init method
is coming to the picture in case of other AWT based programming they are new there is
no init method, but in the class where we are implementing in that class itself we can
add. So, we just add I this is a part of the registration as you know the first step of inner
handling.

So, we just add MouseListener and then add MouseMotionListener this is the syntax that
you have to follow here this means is basically for the current threat and here we just
define the mousePressed e that that is the even handling mechanism here. So,
mousePressed and is the mouse if e means event as you have already mentioned that,
whenever an event occur related to the mouse event or whatever it is there the
automatically the AWT will generate an event object.

So, in this case if a user pressed a mouse button then automatically the event e will be
generated. So, if this is the event then from this event we can extract many information
for example, for this event dot getX it basically tell what is the x coordinates of the
mouseClick position similarly e dot get y this y coordinates of the mouseClick position.
So, these two positions we easily store because we have to draw the scribble; that means,
whenever user draw by dragging the mouse, it will be displayed on the area of the applet.

Now, so, this is the mouse press it is very simple in this mouse press even we have to just
record what is the current location where the mouse has been paste and then another
method that we are we have implemented here mouseDragged. That means, if we press it
and then just move the mouse then it is basically called the mouseDragEvent and in this
event what we are doing is basically we draw a straight line from the last position to the
current position and incrementally if all the positions are like this drawn then a state a
line according to the point or tracking of the mouse will be displayed on the screen.

So, this is the two method that we have implemented here and the other methods namely
MouseClicked mouse mouseMoved mouseEntered mouseExited and then
mouseReleased can also be defined. In this case we have not defined anything explicitly
they are implicit things are there; that means, if any event occur related to these activities
there will be no action taken actually because as you have not done anything here or

1040
even if it is done also, no event can be caught and as a result no action will be initiated
ok. So, this is the example the scribble one.

Now, let us see the output and then we will come back to the example again; we will do
certain modifications so, that you can understand impact of that modification. I am just a
little bit increasing the size of the applet so, that we can view little yeah.

(Refer Slide Time: 06:27)

So, this is basically the scribble applet and at the moment we do not have any event, now
I am just going to drag the mouse and as we drag it as you see line will be drawn like and
drag not initially any order you can draw here whatever it is there yeah. So, you can see
using the scribble applet, we are able to I mean by means of mouseDrag event handling
we are able to draw any things there any curvy line also we can draw and we can take it
whatever it is there that is all.

So, this is the idea about the scribble 1 version 1 we can say, now I am coming back to
the problem again and here is the one event say suppose mouse clicked.

1041
(Refer Slide Time: 07:19)

And as there is no action it has been implemented. So, it is not doing anything in the
same applied also if we click nothing will takes place because there is no event handling
routine is there. Now I am just adding in this mouse event handling routine a sa simple
quote like showStatus as you know showStatus method will basically pin something
whatever it is happened here.

Now, in the mouseClick option I just use the. showStatus method and then we just
message mouseClicked. So, what will happen is, if we just click it and automatically in
the status of the plate viewer it will basically display that mouse has been clicked.

1042
(Refer Slide Time: 07:59)

Now, here you can note it here ok. So, they are actually MouseClicked it is there.
Because you have clicked it and then if we drag it you can see no action will be there and
then clicked ok. So, initially as you see there is no action. So, just it appeared started and
then whenever it is clicked is there then ok. So, it is basically no mouseClick event is
there now if we clicked it, then we can see around it is showing the mouse has been
clicked like. So, this is idea about.

And then mouseMoved is different from the mouse that in the sense that, if we clicked
and then just simply move without dragging that is a mouse moved actually and then
mouse exited also just opposite to the click; that means, is just releasing these are the
things are there. So, if we write some code here and accordingly that code whenever that
event will occur, it can be generated and then we can show it. So, it is left as an exercise
you can write some code and then for every event that it may takes place in this context
you can see the corresponding output.

So, you can use a g dot sting method to display corresponding to each event handling
mechanism event handling routine whatever you have mentioned here. Now this is the
scribble one which basically extends and applet the scribble applet the another example
also same scribble applet, but using the lower version of the JDK toolkit where actually
the different methods were there those are defined here namely action method that
mouseDrag method mouseDown method namely. So, those methods are deprecated now.

1043
(Refer Slide Time: 09:41)

Now, we have a new method as you have discussed here. Now this is basically based on
the old one just for a simple favor of how the event handling routine can be written in a
program and that can be handled by java system runtime manager.

So, in this example as we see the little bit is advanced example we can say, it has other
than the scribbling only it also has the two more options namely cleaning; that means, it
will basically clear whatever the portion that you have scribbled so, far and then another
option is that choice in the color. So, we ca if we see that applet first then you can see
exactly how the applet will look like and then you can understand the code that has
basically has planned to implement these kind of applets.

1044
(Refer Slide Time: 10:29)

So, let us have a quick view of this applet here yeah. As you see here this is an applet
window; in this applet window you see two buttons here is the one clear and another is
the button is called the color ok. Now the currently color is the called as black; now if we
draw something just a scribbling we see something it is there exactly it is black; now if
we change the color. So, you just is a is a choice item you see and in the choice box we
can select some color say red and it is showing that red is there.

Now, if we select the fine another color right you can see the different color now if we
see the clear button, then what the things that you have drawn it will basically repaint.
So, repaint everything with the previous background. So, its clean it. Now this is our
applet now let us see how we have designed this applet what are the means methods that
we have used it here.

1045
(Refer Slide Time: 11:33)

And is this program as we see we have declared two components namely button, clear
button and then color choices as a choice button the choice component these two buttons
these two components have been declared. And in the init method as we see we have just
decide the background of these applet is as white, and then we create the clear button
with a level clear and then clear button the foreground and background has been decided
as a black and the light gray as you can see the background the button appears with a
font as the la font as the black and then background of the button as the light gray and
then we add this button into the applet screen.

So, the add method is called for that. And similarly the color choices we have included
several color like black, red, yellow and green and then color choice items has been
created and they have been added into the add item like. So, these are choice list is
created and finally, we decide we set the foreground of this color choice as black and
then background is a light color.

So, you can see the both button and then choice component looks very similar in the
sense of color settings and others, and then we deci we add 1 level as a color to indicate
this choice is basically to relate to the color only. So, a level has been added side by side
this 1 and we add all these things into the applet.

Now,. So, this is. So, far the applet design is concerned as a.

1046
(Refer Slide Time: 13:17)

Now,. So, if we do it do not include any even handling mechanism the applet will appear
it is like this there. Now we have to implement the listener method here, now here we
first implement the mouseDown method is same as the previously described mouse the
mouse pa paste method that is discussed in the scribble 1 and the mouseDrag is also very
similar to the mouseDrag method that we have discussed in the scribble 2. So, we do not
want to discuss it explicitly and next another is that action event that we have to write it
is basically handling the whatever any event occurs.

So, event is basically any object of type event if it is created and object art is basically
tell about which is the event actually we have called it there. Now if event or targets that
mean if we click say button so, that is a event of target is clear button then it basically
clean the repaint the entire what is called the applet area. So, that is why set color field
rate by that default color is been set.

Now if event or target is color choice. So, this is basically the action event is related to
the choice selection actually. So, if the event dot target is equals to color choice and then
it will basically what it will do, depending on arts basically if it is black then it will set
color black and otherwise whatever the different color will be choice according the color
will be set and it will return this action to the caller actually.

So, this is the way by which the 3 actions related to the mouse handling the mouseDown
and in mouseDrag and then another 2 actions related to the clicking on the button or

1047
clicking on the choice. So, action handling return has been designed and you have
already shown obtain the output that it will show the output this one.

So, my advice again is that you can try this program with your own settings and then run
of your own and then change whatever you want to do and let us see what is the effect of
the change that you can get it. So, change in the sense that if you change in the method it
will basically reflect it automatically ok. So, this is the scribble tool.

(Refer Slide Time: 15:37)

And then our next example is MouseListener it is very simple example it is very simple
rather very trivial example we should say. So, there are different mouse re mouse event
actually likes a mouseClick mouseEnter mouseExited mousePress release some fa
features or you have already familiar we have already experienced in scribble 1 applet.

Here again we have to do; it we will just do what exactly the thing is that if some event
occur we use the so, status method to show this. Here actually we do not instead of this 1
a level will be there and for this level that text will be changed according to the event
that it occurs. So, the accordingly the code that is here as you know it is basically the
AWT program without any applet.

So, it is extensive frame. So, whatever the things it will be components and other things
it basically will be will be include in the frame itself and as it include mouseListener. So,
MouseListener method or interface are to be here and then we first do the registration by

1048
add MouseListener this and then we decide the level 1 the component, we display this
component and then finally, we write the event handling method namely MouseClicked
here simply setting the text for the level whenever the text as the basically related to the
particular event like loop.

So, this is the 1 example very simple example as you can understand it I hope and now
here is the output you can see. Let us resize the window so, that we can see it yeah. So,
now, here as you see here. So, if we clicked then you can see the level will be
mousePressed like and if we add if we mouseReleased also you can see the
mouseReleased be there and so, mouse play pressed mouseReleased MouseClicked all
these message are coming because I am here controlling I am pressing clicking deleting
all these kind of things are doing as a result you can see that display is also changing. So,
this is an example related to the mouse event handling.

Now, I think it is time to discuss about key hand KeyEvent handling one example and
this is a very simple example here the.

(Refer Slide Time: 17:57)

So, whenever there is a KeyEvent occur, all the KeyEvent can be categorized into either
keyPressed keyReleased or keyTyped. So, there are three events. So, if we can devi de
define these 3 events handling routine in our program. So, it is enough and all the other
things that we have to add the; we have to do registration the listener object. So, in this
case we have to addKeyListener; addKeyListener is the listener here in this case the

1049
listener will be watchful to see if any event occurs at any instant and then also one thing
you have to use it to call the request focus; that means, the AWT should instruct the
runtime manager to request focus for the keyboard in ta if any.

So, this is the thing and in this case the definition of is the method keyPressed
keyReleased and then Key tip a simple method. So, status method has been called for it
and then it will basically display the status bar like. So, these are also an another applet
program so that status is accessible to us as by means of extending it. So, it is a very
simple. So, status method we are calling it here and as you see here ok. So, initially as
you see so, status applet started. So, there is no event occurred.

Now, I am just going to k keep list as a keep list as you see the Key Up or Key Down
key release all those things are coming here ok. So, it is there and if we write something
yeah Key Up Key Down at an actually whenever the KeyEvent occurs there are 2
methodologies Key Up and key din because you easily key press and then Key Down at
is like this. So, Key Up Key Down automatically side by side actually and then
keyTyped also if you see if we type some character that character will be displayed on
the front area.

Here for example, we are typing like NPTEL sort of thing as it is coming here on this
applet screen. So, you ca hope that although is a very simple example trivial example,
but only for the sake of illustration and then demonstration I hope it is understandable.

(Refer Slide Time: 20:17)

1050
Now, we will discuss about another see there are three different type of keys that is
possible.

(Refer Slide Time: 20:21)

And if we types any function key or some control alter shift and everything
corresponding to these there will be no character should be displayed because they do
not have any character assigned for that.

On the other hand a to z and some numeric characters they have been assigned. So, if we
type it they are correspondingly key type and then for that key type the event will be
occurred; that means, we will be able to read from the event that it happens and then
from this event what is a character that it has been typed can be obtained.

Similarly, what are the function keys or the control or other keys has been obtained that
can be also understood from the event itself that it happens there. Now for this event
class has defined many variables many constants actually. So, we can read all those
values and then according we can understand that, which keys has been pressed by the
user. So, this example illustrate the fact that there are different type of key can be pressed
and according to these the different output can be obtained through extracting the event
that it has caught by the program.

So, this example as we see KeyEvent dot VK underscore a form; that means, if the
function 1 key is pressed; that means, event is related to this one then it will just give a

1051
print that function 1 is there and like this functional function to function see page up
page down page up all the keys those are not having ASCIII code returnable. On the
other hand if we type some other characters key, then you will type it and then it will
display this one accordingly our key typed event methods needs to be modified.

Here we have done it keyReleased. So, status actually Key Up and then keyType it
basically typed whatever the character that we have typed gate key character from the
event that it had happened corresponding to this type key, we can get it and just to go on
appending and that message can be displayed on the area there applied area and it
basically that steam that message steam can be displayed by means of paint method it is
there.

So, these are example now have the demo so, that you can see how this program works
here yeah.

(Refer Slide Time: 22:41)

So, as you see here. So, these are applet has started right now, no event initiated right
now I am going to type a font. So, if we press [FL] 1 as you see this one similarly F 2
and then F 3 and so, on. So, you can see now I am typing a capital A, as you see typing
capital A it will sense it and then it also displayed there and whatever the type character
is there. So, 0 1 2 3 also we can see it is also going to sense it.

1052
So, it is basically the event is that we are pressing some keys whatever is a function or
whatever the character or numeric key whatever it is here. So, these are event that is the
source is a key and then event handling (Refer Time: 23:20) hence read it and then they
can take the action, the here action is basically printing the same text on the applet screen
here.

(Refer Slide Time: 23:31)

So, this is related the KeyEvent and here let us have little bit complex examples.

(Refer Slide Time: 23:37)

1053
Here actually we want to give that example relate to how the button can be manipulated
button can be handled. But this program in addition to button there are few more items
are there first let us have the look of this applet, then I can come back to this program so,
that you can understand exactly what are the concepts are here it is followed. Yeah as
you see here little bit much more components are involved what are the components?

First of all the frame it is and frame contains one panel which is colored as a yellow, and
you see in the frame also we include some ta text area the what is called the control in
action and then button this is basically the level we can say and so, this display the level,
level is included in the frame and fine and in addition to these there are three buttons as
you have seen that button and then another is submit and then cancel.

So, that is also if we click as you see that are ok. So, output will be displayed by means
of another level and that button clicked. And similarly if we cancel then we can see
another the cancel button click. So, you can understand so, how the events are handled.
Here we are clicking a particular button corresponding to this button a particular display
message appears on the frame itself.

And this is the program we have implemented in this applet here as we see we declare as
you see here we declared the frame, level panel whatever the things it is there and they
have been initiated and size and everything has been precede. For example, it is for the
frame and it is for the level and it is for the panel and everything that we have discussed
and then as you have already have an idea about how to configure a panel, how to
configure a feel a frame and whatever the every things are there their shape layout
pattern and everything all these things are there.

1054
(Refer Slide Time: 25:41)

So, if you go through with your own time you will be able to follow it clearly. I will
better come to the event that we have increases there. So, here we have declared one
method of our own called the showEventDemo; and in this method we just assign the
add setActionCommand setActionCommand and command setActionCommand set
action listener and then action listener for the different buttons and different buttons
mainly.

So, here for example, button and then submit button and cancel button for all these
buttons we defined the different methods that it can handle actually and this basically the
registration tasks and then control panel just add different buttons on each. So, button
submit button and cancel button and finally, the frame is now set as visible

And then button click listener is basically the method which we have planned you listen
to the button click this is the main class in this case actually and in this method as see if
you see we have different actionPerform this is the main method that needs to be defined
by us and then so, that according to that what will be the text will be there. So, if we
press this one button click, then it is a status level dot set text will change at that thisone
that is this button is click like this. So, this is a program it is basically event handling.

1055
(Refer Slide Time: 27:07)

So, again you if you run the program of your own, then only you will be able to
understand much more things in details. So, this may be only 10 percent of your
learning, but you have to run it of your own and then see exactly how the things are
coming. If you tend something and then you have to see exactly whether the change that
you have done according to your own wish or not.

So, this is the idea about this one and this example as we see here ok. So, now,. So,
another example that we are going to discuss about, it is another simple example this
example relate to the text field in addition to button. So, here are basically two text field
area, it we can say it is a simple calculator the calculator we will have only add and
subtract methods are the two buttons add and subtract and that two text field as we see on
these two text field for taking an input.

So, it is also even can be added into that text field area, now we will see that how the
even can be added in the text field area and then the third text field is basically so, the
result. So, he probably types say 10 in the first text field and then f15 in the second text
field and then if we try plus and you can see the result will be 25.

If which check in minus as we see the result will be changed to this one. So, this way the
it is a simple calculator look like, but this can be extended to have right your I mean
much more complex calculator actually.

1056
Now, here you see what we have done first you have to create the 3 text field that we
have done here t f 1, t f 2 and t f 3 and usual the routine that we have already learned
about it how to create a text field, how to size of the text field can be case it or is that
everything that we have done here. So, just first few lines is basically related to how we
can create 3 text field and then we have decided that two button, how the two button can
be defined.

So, here we have declared the two button b 1 and b 2 namely b 1 is for plus and b 2 is for
minus, and then we have to add the action listener as a registration. So, b 1 dot add action
listener b 2 dot add action listener. So, if any action have if anything happened to this
button. So, this action listener will listen to that and accordingly the routine that we have
to develop is basically in the next method actionPerform.

(Refer Slide Time: 29:31)

In the actionPerform as you see we read s 1 and s 2 the two string from the two text field
and then there needs to be converted integer,we have done it as a by means of integer dot
par seeing method. And then we have to take about event if the event is e related to the
clicking a button. So, e dot gate source and if it is a b 1 so, it basically at the result and
otherwise we just add subtract from a to b a minus b like and finally, we display the
result converting into the string and then we display the result on to that text full third
text field. So, this is idea about it.

1057
(Refer Slide Time: 30:21)

Now, I just want to add it say suppose I want to add one more button, and you will see
how the things can work for you. So, one more button lame namely say for
multiplication I just add one more button here. Yes I am adding one more button that is
all. So, multiplication and then in the action performed routine I have to change it,
because we have plus button.

So, if the plus button is there. So, another e field part we can add another else part. So,
else if e dot gateSource is equals to equals to b 3 then action that will be performed is c
equals to a star b. And then if just compile this and then you see how the change in the
applet will be and like this ok.

So, now we can see the applet here yeah. So, applet has been changed as you can see if
any value you can add in the two text field plus minus and then star as you see the result
is coming.

1058
(Refer Slide Time: 31:15)

So, this is the way that we can add components at the same time for each component we
can register the listener objects and then according to for each component, we can decide
what are the event handling routine that needs to be associated in each component and
that is all so, far event handling is concerned.

(Refer Slide Time: 31:33)

Now, I will quickly come to the swing and then we have right idea about the swing
actually, and this is the calculator that we can use using the swing. Here the swing

1059
calculator we have discussed in our theoretical class. So, it is basically the same thing we
have done it, now if we run it then you can see how the swing calculator look like yeah.

So, here is the swing calculator is a typical look here as you see here. Now in the swing
calculator as you see 0 to 9 10 keys are there 10 buttons rather they are labeled as 0 1 2 2
9 only. So, basically all these buttons are to allow user to type 0 to 9 any now integers
and then the user using this button can type any numbers for example, 2 5 like this.

And then there are some operation button like plus minus then multiplication then
subtraction and some buttons like clear c and finally, there is another button equals. So,
if we write 2 5 and then plus then 3 3 and then equals then you can understand what the
result it will show. And then if we again click key c then it is basically clean it is there
anyway. So, this is the part of this applet calculator as we see here.

So, here basically idea about designing this calculate, I just leave it with the program you
can have it and then you can check the program of your own according to your own
convenient time then you can understand much more about it. I just want to see the
methodology or the steps that you should follow. In the first step whether it is an applet
or frame you decide accordingly the things will be there in this case we have used a
frame. So, this is not an applet and then we have to decide the frame and then you have
to I mean create one panel usually it is customary to include all the components inside
the panel so, that it can be more better configurable. So, you have to clear the panel also.

And this panel includes so, many keys are there, 0 1 2 all these things button actually
there. So, here actually 17th buttons as we see, 16 including operations and on the last
one is equal. So, those buttons have been declared and then finally, how the action
listener is to be registered here in this case the action listener is basically mouse key as
you see. So, mouse clicking actually; we are we are entering the number not from the
keyboard rather we are entering number from the keys on the calculator. So, the
mouseClick is required here. So, method that we have to add it basically the mouse key
MouseListener to be add MouseListener is the method that needs to be added here.

And then once it is there for every keyboard we have to add the action listener and then
action listener method is defined accordingly. So, that it will basically send that what is
the type that the user has ta I mean keyed rather, and then accordingly it will do the
results whether depending on plus button or minus button or multiplication button or

1060
division button is the operation will be carried out. So, this is the right code; code for
action handling as if you can see later on. You will see that a little bit optimized code it
is used here, but you can write the course according to your own understanding and write
it there.

(Refer Slide Time: 35:05)

So, I do not want to say that you have to follow these code.

(Refer Slide Time: 35:09)

You may understand these code very easily or you can find it little bit difficult to
understand. But anyway, but you can think you can see that how you have to handle the

1061
key that is your own idea should be. And then accordingly you can rewrite this code re
rerefine these codes and then you can use it.

(Refer Slide Time: 35:29)

So, this is about the event handling this is the start and very beginning of the even
handling me mechanisms as I said and more on the things depends on and you can learn
much about if you develop many more programs many more tasks that you have to do it
and you can follow it. So, that is all for today.

Thank you very much.

1062
Programming In Java
Prof. Debasis Samanta
Department Of Computer Science and Engineering
Indian Institute Technology Kharagpur

Lecture – 46
Demonstration – XVII

Now, let us have the demo on Java Swing facilities.

(Refer Slide Time: 00:21)

Now, java swing facility will be covered in 2 Demonstration modules this the first one.

1063
(Refer Slide Time: 00:26)

In this demonstration modules, we are going to cover how to create a j Frame, which
means frame in java swings rather and then panel. And then Swing buttons actually
different components are a swing and then here whenever you have to include this
component.

There are a few things needs to be remembered, either using java constructor we can add
some component or using a frame class or using the Action Listener method it is there
and also we will see that which makes little bit different from a w button to the JButton
that how a button can include an image, that means button with image actually. And then
we will discussed about the simple calculator using addition and subtraction which we
have discussed in our TextField, even handling on demonstration there, the same things
will be but using java’s swing only and simple program to find the number of words and
characters using TextArea.

So, these are another advantage that we can have from the java swing this is how I swing
is more preferable because it has a lot of built-in programs automatically it is there. So,
automotive or account and then character count also can be facilitated from the GUI and
then other GUI component like TextField PasswordField and then Login PasswordField
or everything will be covered and then CheckBox RadioButton Jspinner and then Toggle
button all these things that ever we will try to accommodate the demonstration of all
these programs.

1064
(Refer Slide Time: 01:59)

So, let us have for the first demonstration on the j frame, which means how a frame can
be included in a container using the java swing and for these things as you know we have
to import javax.swing.star, this is necessary if we want to include the swing component
here and then other things are to be included like import java.awt.star and all these things
are there those are related to this one.

Anyway, so we have included those are the things are there they are javax.swing.star it
will include all the packages that are there. And by means of that all classes those are
defined there will be accessible to this program and this program is very simple as you
see we create one frame the name of the frame object that we have created is simply
frame and the level is JFrame example. And then also we declare one panel and then
layout we have sit into the floor layout you have already learned about in the context of
awt and then level has been initialized with the level button edge.

But a level has been initialized as JFrame by example that is all and then button one
object is on a component is created here and all those things are added into this panel
first and then panel has been added into the frame that is the policy it is basically that.
So, panel includes the different Jswing components and the final panel is included in the
frame objects and then so we have to just yeah.

So, if we see the output of this applet then you can find it the output that you can get it
here as you see here a little bit will be regarding screen then ok, so JFrame by example

1065
and then button it is there. So this is a simple example that a frame can include the
different Jswing components how it is they are including here panel level and button
everything has included in this one.

(Refer Slide Time: 03:59)

Now, the next example is basically the panel related, so how a panel can be created and
the panel can be added we have already done the same example in the previous case also
it is explicitly only paneled there. So, let us have the output of this program and here you
can see the background of the different buttons can be changed here how the different
colors also that is also possible here. And then a background of the frame is gray or
white you can say and then whatever the panel is gray and all this thing you have done
the setting it is here.

1066
(Refer Slide Time: 04:34)

Now, our next example is basically Swing example, so how a swing button can be
created and it can be added into a frame is very simple one, as you see here we first
create a frame the frame is titled as not I tell is that in the frame it is here in this case.

Then we create JButton the button is leveled as click and then we add this button b into
the frame f and then finally we define the configuration of the frames regarding size
layout and then visibility those are the standard for a configuration protocol that you
have to do it. So, this is very simple an example for illustration which includes a one
frame a frame contents one button the level edge click yeah that is fine it is very simple
on example.

1067
(Refer Slide Time: 05:28)

Now there are many methodologies by which a frame can be included.

(Refer Slide Time: 05:34)

So, there are three ways that a frame can be and then the different methods can be
included and finally, the whole GUI can be created. So, it is basically one idea about the
creating GUI components inside the constructor method itself and here you can see the
simple example here we give the name of the class that we are going to develop for a
GUI, program the name of the class is simple and in this case and in the simple class as
you see it has the frame declaration. And then the constructor simple and we inside this

1068
constructor we define whatever the procedure needs to be followed in order to create the
GUI. As you have done here create a JButton and that button is added into the frame and
then frame has been resized and whatever it is there and finally in the main method we
can just create the one instance of this class by calling the constructor automatically.

So, that concern only one constructor is they are simple. So this way actually what is the
advantage of this thing is that code sharing is possible if you do the class in the different
packages and then we can include it. And then from this class we can just create the
object and then that object creation itself basically include the different parts of the GUI
is to be included in the bigger one. So, it is basically the idea about the bottom-up
approach, so the bottom level is all the class declaration for each GUI component and
then the top level is the bigger content that it can be designed ok.

(Refer Slide Time: 07:15)

So, this is the one idea about it our next example is basically the same thing, but here we
can create an instance and then for that instance we can create the objects they are here
and then we can say that there is no need to create the instance of the same class
explicitly. This is the one example where we can see without any creating the f object,
however we will be able to add some component into it. So, this example basically
illustrates this fact actually mostly it is very similar to the previous example. Now say let
us see what is the difference here in so far the coding is concerned.

1069
Now here we defined the class simple to which extends JFrame that is the only
difference point here earlier is just simple to class, but you have to extend it. That means,
it is basically this subclass of JFrame actually sample 2 in this case subclass of JFrame
and then we create a frame object and then we define the constructor simple 2 and then
we create the button b and then add Button.

Now here you see we add button and explicitly we do not have to mention implicitly that
if this add button goes to this frame itself, because the frame is the subclass object it is
there. So, this button will be floated on the frame itself which is the main which is
included in the main method main class is there and finally, the main method is basically
created of instance of this class itself by means of calling the constructor.

So, it is basically same as this one you may find a second the last one example is more
preferable that is all this looks pretty simple it looks a little bit abstract, but it is also
some programmer prefer this kind of coding it is there and another example is there
button with ActionListener. So, even handling the most important part is there, so how
we can add the ActionListener to each button like so for an instance for example.

(Refer Slide Time: 09:11)

And in this example we see we create a frame fast and in this frame we add 1 Button
name the name of the button that we have given as B and B has been set and configured
properly and added into the frame and then we have to add the Listener method for that
add ActionListener. New ActionListener is the method right and then it will basically it

1070
will print whatever the action that depends to is that means if we click the button
automatically this event will be executed event code will be even united code will be
executed and it will display the text welcome to java point like this one and then finally it
will display the results. So, this is the one example that we have shown the Button.

(Refer Slide Time: 10:03)

Now, here the next example Button with Image. So, there is one good point here so for
the java swing button is concerned that we can add some button image on the button. So,
this is the code there only you have to just simply instead of setting the level that we
have done in there icon of the image type we have to add it there. So, that we did it here
we have created JButton B and then we say then we create one image icon J.

1071
(Refer Slide Time: 10:28)

So, (Refer Time: 10:28) while we define the JButton B as a button that time we just
create an instance of ImageIcon into it, the ImageIcon basically include the specific
location of the image for from where it should get the image file. So, that this image can
be included is a bottom as you see the output for this programs you can see is basically
include one image that is here and yeah so this is the basically Button with Image. So,
similarly some person phase or some other object flower or all these things or some other
video click video symbols and everything can be included in this button like this. Now
our next example related to the text field in JavaSwing.

(Refer Slide Time: 11:18)

1072
So, how the text field can be added and after adding the TextField how the different
activities can be handle real to this TextField.

(Refer Slide Time: 11:25)

So, again it is very similar to the simple calculator that we have already discussed while
we are discussing about even handling routine managing and they are basically here we
will include same thing, but here we just use only the JavaButton and java text fill
method it is there.

It is basically the same thing earlier it was without any swing pack swing package here
only the thing that we have used in the swing package the output and display and
everything very similar to the previous on an example of course ok. You can go through
the code and then you can understand it is basically very similar to the previous code it is
there and you can find a little bit different the Button looks like little bit different than
the Button that is created that was created using awt bar components like this one.

1073
(Refer Slide Time: 12:25)

Now, our next example to discuss the other few essential components which is not use a
explicitly with a particular specific to the java swing namely password field in addition
to TextField for the login purpose as you know whenever user has to log in to some sites
or server, they need basically display an applet or window were it includes login and
then password.

So, login as a appears as a TextField whereas password has appeared as a PasswordField,


so PasswordField can be treated by using java swing here as you see. So, login you can
type anything something know even added here, so you can just login as you know you
can write a bus is for example and the password is my password.

Now, if we click it and whatever the password that we have your program can sense it
and accordingly it will pin this one, so password is this one whatever it is there. Now so
these are the things that we can action can be generated and then even can be generated
and for these event actions can whichever action that you can plan you can add into the
interface, so this is about the PasswordField it is there.

1074
(Refer Slide Time: 13:40)

Our next example is basically CheckBox CheckBox using java swing the similar concept
only the thing is that JCheckBox JCheckBox and all this thing need to be included here.
So, it is basically we create the CheckBox 2 checkbox as the JCheckBox 1 and
CheckBox 2 and any CheckBox we add that that is all only we just create the 2
CheckBox and out of which 1 CheckBox as marked and the other is non marked. So, it is
basically true and other is there so 2 checkboxes are leveled as C++ and java like.

(Refer Slide Time: 14:18)

1075
As you see the 2 checkbox here and C++ and java and if we click C++ you will see the
checkbox selection will go from Java to C++ like, so automatically it will be added this
one. Now radio button is another example very similar to the CheckBox as you have
shown it, but CheckBox has the rectangular view of Checking Box. So, it has here it is
called the CheckBox, on the other hand, RadioButton is basically the Button looks like a
Radio, that means it is the circular type that is the only difference between RadioButton
and the CheckBox otherwise the process method and everything is very similar to the
CheckBox itself.

So, checkbox and radio button are the same programs in fact only changing the
component type from checkbox to JRadioButton like and this is the code and as you can
see this is the things are there and if we click that click will be highlighted here, using the
mouse click event needs to be added here in order to sense the event and corresponding
that event you can write our own flow code, so that the event handle general code can be
written by the programmer.

(Refer Slide Time: 15:36)

So, this is the one example of RadioButton example our next example is basically
JSpinner, as you know that JSpinner is basically giving the choice of course but a little
bit in a numeric form usually. So, here the numeric form and the range and everything
can be specified as you see here and if we it is just not exactly the scroll bar it is
basically incremental or decremental of the spinner value actually. So this in this

1076
example as we see in this example as you see we create a Spinner JSpinner with the
initial value 5, so by default we can change this 0 and then later let us make it 0 and then
it has the range of values that it can vary so 0 to 10 and 0 to 10 like and increment is 1.
So, if we can give that 0.5 increments that you can understand 0 5 and 0.5 and everything
is there so incrementing 0.5 fine.

(Refer Slide Time: 16:41)

So, we can learn it yeah so as you learn it as you can see initially 0 little bit bigger in
screen, so that we can see it a little bit clearly yeah fine little bit little yeah. Now as you
see here now if we the upper click we can use it so it will increase as you see that we are
clicking and automatically the spinner values is ranging from current value to 1
increment each time and then again decreasing at any after 10 if you right fine right. So,
there will be no increment similarly if we decrement it will go than this one.

Now, so this is the idea about here incremental value can be any value here we have 1, so
if I can to 0.25 so the range of values as precision will be automatically changed and then
it will do work for you. So, it is only for the numeric range of course no other range can
be allowed for it in floating-point and all these things not allowed there, so this is the
JSpinner and our next example is ToggleButton.

1077
(Refer Slide Time: 17:43)

Yeah so ToggleButton basically says button look like, but here actually the button value
can be toggled from only 2 values either ON-OFF or whatever it is there.

(Refer Slide Time: 17:57)

Now, in this example that we see here so little bit bigger in size yeah, so nowhere the
button is default is ON now if we click this ON then automatically change to OFF. So
obviously, the routine needs to be written for that will just come to the code here we can
see what is the code that is there in case of the JButton? So, here we have created one
example the name of the class that we have is basically an extension of JFrame. So, a

1078
constructor of JFrame needs to be created first so public static void main string is the
main method and then we can create the ToggleButton example as a constructor here to
invoked this one.

And then the ToggleButton example constructor is now reset by set title, that means is a
frame thus title of the frame is the ToggleButton with item Listener actually because, this
Button can be is not that action event action listener it is item Listener and then we just
defined SetLayout as a FlowLayout you can change any other FlowLayout or if you
define the set layout null whatever it is they are. So, default layout planning will be there
and set JToggleButton SetAction and then set size set visible true and set default closed
operation these are the usual method for the ToggleButton that you have to add it exit or
close so it is there.

Now here you just come to the set the ToggleButton method which you have used their
how these basically toggling will be there. So, it is ON because it is ON and OFF
between and then add button and then set action is basically add item is not is to be set
here. So, that you can listen to the event if anything happens to that and then we decide
to define the items state change event is there that is the event regarding the item event as
I set already and then if selected then it basically set text OFF.

If you don't select anything it will remain the same thing as that now if I change it so on
instead on True and then off is false actually we can change any value there right and
then here True on instead of ON we can just write True.

1079
(Refer Slide Time: 20:20)

Now we have changed it so you can toggle between True and False like ok.

(Refer Slide Time: 20:37)

As you see here yes now so Button is here we can see this is one, if we click it then you
will see that change will be True to False. So, click the button yeah as you see it is there
and all the other things are applicable here. Now we have understood few components
there few more components are also there that will cover in our next demo class. The
next demo class will include few more concepts about JavaSwing components.

Thank you very much.

1080
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 47
Demonstration – XVIII

(Refer Slide Time: 00:27)

So, this is a continuation of our demonstration related to the Java swing package in Java.
These are second part of the demonstration. In this demonstration, we are going to cover
few more components like ComboBox, then JOptionPane, then JColourChooser, Jtree,
JTabbedPane and so many other things are there.

1081
(Refer Slide Time: 00:43)

So, let us have the demo first. And this is the ComboBox. ComboBox is very similar to
the CheckBox group actually, that we have discuss their in awt. And here how a
ComboBox can be defined can be created this examples will illustrate us.

So, here ok, so first we create a Frame, because a Frame should be there in order to
contain a ComboBox. So, Frame is created. And this class is the program itself
ComboBox example, inside this constructor is a constructor base implementation. Then
we create a Frame, the Frame name object name of the Frame is f. And the Frame will
appear with Frame title call the ComboBox example.

And then, we define an array of strings like India, Australia, USA, England and
everything. So, basically our ComboBox will include these are the items in to it into in it.
And then we create a ComboBox passing this List of strings as an item in it. So, this is
the one way that we can do. Otherwise, separately also add item, we can use it, and then
add in to the ComboBox also can be done there.

Anyways, so if then finally we can create the settings for this ComboBox regarding its
location, where it should be floated, and then the size that mean width and height and
everything. And finally, we add this ComboBox into the Frame. And then the layout size
and the visibility of the Frame box has been set according to our requirement.

And finally, we call this object instance by means of its contractor only ComboBox

1082
example contractor. So, this is the way that the ComboBox can be created here. Here we
have executed this program, and we can see that this ComboBox is now already appear.
The first item which is in the item List actually will be displayed here. And then if we
click in the scroll bar there side right ok, then all the items those are there will be added
here, and accordingly List here.

Now, here actually so the size of the ComboBox as per this example is concerned is the
pipe. So, you do not have to discuss it. You can easily compare the ComboBox that we
have discussed, while you are using awt. They are also one way. The same mechanism
also, it can be followed here, but as it is a we have used a different example, so that it can
give the different way, the different favors that a ComboBox can be designed, and can be
used in your window program. So, this is the ComboBox.

(Refer Slide Time: 03:17)

And another thing is that a table, how we can create a table using you know the table. A
table is basically collection of some rows, the rows contents the data, and there are set of
columns, those columns are basically call the attributes. So, we are going to define on
table which has three attributes. The three attributes are id the three attributes are id,
name, and then salary. As you see there string column is a array, which includes the
column heading for id, name, and salary right. So, these are the way that we can do it.

Now, here the table is a two dimensional array actually, so that array can be read from
the either from the output stream or here which has we have store this table in the form

1083
of a 2D arrays actually. For this illustration, however in different way also, it can be read
from the other source, the way it can be there.

Anyway, so this table contents three rows as we see here. The first row include 101 has
the id, the name is Amit, and salary is this one. Similarly, 102 and then 101, and all these
things are there. So, this basically completes structure of the table, including the data into
the table. And then finally, we have to create the jt. And then jt is basically the object
that we have created of type JTable.

And then the argument that we have declared data, data is basically which includes the
total records that should be there all the rows basically, and then column is basically
column header actually. And then finally, set bounds that mean horse will be the size of
the table that it should be, and then JScrollPane actually we have to include a scrollpane
there, so that it basically scrolling is possible for the table. And then, we add all these
scroll pane as well as the table into this Frame, and it completes the creation of Frame.

Now, let see how the output of this Frame will look like. As you see here yeah, so these
basically size of the table, the table will look like, and it contains the columns as well as
all rows. All rows correspond the all data that we have already populated into this
example. So, there is again we can go adding few more table entries I mean rows and
everything is just go on adding. Adding actually no problem, it is basically there is no
limit of the size that you can restricted to the table that one.

And once this table is there, it can be processed by the different methods we have already
discussed in the JTable. All these method can be used to access the different elements
inside the table, how many rows are there, what is the number of elements, all these
things are there. Even the searching also can be taken with the main different methods
that is declare there. Now, this is the table example is very simple. So, for programming
is concerned, absolutely that is not the big as you see here.

1084
(Refer Slide Time: 06:17)

Now, our next example related the j List, it is very similar to the List that we have
already discussed in awt. So, as you see the List is basically List of items that it can be.
The same way we can put into the first array, and then array can be first as an argument,
when you have to initialize say (Refer Time: 06:36) subject actually List object. So, here
is an another way. So, you can add item independently one by one, and then it can be
populated into the List only. So, this is the second version, second way of storing the
different items into a List.

As we see here we first create a Frame, because Frame should include this List. And then
we have created the List also here. Here List is created like default List model that we
have created one idea about that ok, this is a string of List actually l1. Then l1 dot add
element, it includes that we adding one item into this List. So, namely item 1, item 2,
item 3, and item 4, we have added four different item into the List.

And then finally, we create the object of this List, the name of this is called List only.
And then we pass this lll to this object as an argument that means, it will include all the
items that we have added into it. And finally, these are the usual statements like set
bounds, then set then f dot add List, adding the List into the Frame, and size setting,
layout setting, and then visibility setting that is all. And then finally, we call create an
object of this type of the program as an window, and then we create it one. So, this is the
one example of List, it is there.

1085
Now, we can select by means of placing a as we have highlighted. If we place the mouse,
there on highlighting will be there. And here is that only one mouse can be there, mouse
can be also over, and then many multiple List items also can be selected like this one.
And that selection can be any where there, as it is known as a control button, and in
addition to control the mouse. Base the focus of the previous selection will remain same,
and the next also focus can be changed, both the focus can be merged, and then bigger
focus can be made. All this kind of things that can be done here. Now, so this is the
example of List.

(Refer Slide Time: 08:43)

Now, next example that is we have plan to illustrate, the concept of OptionPane. And
OptionPane is basically just look like a Frame, let us have a quick look of the
OptionPane windows that it can be ok. The optionpane is basically the fixed size, it
cannot be resized or cannot be changed here only a cross button can be used to close it or
button can be press to select it like this one.

And as we see here OptionPane is created with a message like hello, welcome to IIT
Kharagpur like. So, this is the idea of the OptionPane. As you know OptionPane usually
sometimes appears in any our program, whenever you see today using mouse or
everything regarding either progress of some development downloading of a file or if
any error occur is basically error message or it is basically called the dialogue message to
that.

1086
Anyway, so this is an example how such an OptionPane can be created. For this things,
we have to use the class call the OptionPane JOptionPane, and then for this thing an
object can be created. And using the show message dialogue, and which dialogue you
want to add into this that you can include it. And then finally, the another argument that
in which Frame, and finally this object will be created, and it can be added into the final
program. So, this is the program code very simple few lines of course are there, and that
kind code is enough to display any OptionPane like.

(Refer Slide Time: 10:19)

Now, our next example is to create MenuBar. And so menu items into the MenuBar. As
you know menu is basically create a List of items in to it, and then MenuBar is also
basically showing the bar, where the menus are will be (Refer Time: 10:31). And if a
particular menu is selected, then this menu can be chosen here. So, a typical look of a
MenuBar and menu items as we see in this applet, only one menu here.

So, now we let us see the code, as you see the code here. So, JMenu, and submenus are
two menus are there. If we select the menu, then menu will be selected, and then
submenu will be there. And JMenuItem, there are items i 1 to i 5 the items have been
identified there. And then menu example in this example as we see we create a MenuBar
objects and mb and then menu new JMenu, menu is created.

And then submenu also another object is created like JMenu is again the JMenu object
itself, but having the different level submenu. And then we add the item one i 1, i 2, i 3

1087
into this menu item is basically calling the constructed there. So, we create and then
finally we add these menu items into this menu itself. So, this completes the creation of a
menu, which includes submenu items 1, 2, 3, 4 like. And then that is also this basically
creates the menu item, whose output already we have experienced, it will look like this.

And then if I ask you to add one more menu, the same procedure that you can repeat
copy paste and then just simply change the values, and the menu item bars and
everything. So, another menu if it is there, it will appear here. So, many menus can be
added, and then they can be placed into the sidebar or MenuBar actually. So, this is
basically the MenuBar. And then for this MenuBar includes many other menus also. As
you seen in any other windows application like word or power point a many menus like
this, and as we see here also. The many menus are can be included in the MenuBar, and
then the menu item can be added in each menu. And then each menu item from a
particular menu can be selected by clicking all these things. So, this is also another
example of MenuBar like. So, this is the one example, so that is all.

And next our illustration let us have the popup menu. As a name popup menu, it is also
similar to the menu item only. But, is a popup menu, it shows that ok, let us have the
quick output of this that how it looks like a popup menu first ok. As we see the popup
menu, it is basically fine.

And whenever we click it, so pop up menu will appear. And popup menu will appear
with some items in it, so this is the idea of the popup menu. So, it will not be there until
you just click it, so that is why it is called the popup, whenever some events clicking is
occur. So, pop up menu will appear there. So, this is something different than in the
example, whatever you have considered about awt is a specific to this thing only.

And here we can see, we create a Frame first. So, Frame will include this popup menu,
and the name is final J popup menu, final this is the popup menu actually yes, we create
this one. And then this is the name of this pop up menu is edit actually. For this edit
menu, there are item that we have added here cut, copy, and paste like.

And then finally, we just add all these item JMenu item into this pop up menu like cut,
copy, paste as an object that we have created adding them into the pop up menu item.
And finally, we just register the mouse Listener, because if we click mouse, then only
this one. So, even needs to be registered here in this case, and this register basically

1088
defined popup menu dot show method it is there, and then e basically take the event that
it may occur, so then. And finally, this popup menu item is added into the Frame. And
this completes adding one popup menu into your application program. So, this is the one
example that is basically.

(Refer Slide Time: 14:54)

Our next example that we are going to discuss about similar to popup menu, but it is
called the check box menu item in the menu. So, it is a menu item, but with checkbox, so
that is the difference and ok. First see exactly how it look likes actually with a single on
checkbox menu item in this example, as we see here yeah.

So, here if you see at a menu item is displayed in the MenuBar, and if this menu item
includes and as a popup look like if you click it, then that menu item will appear. And
then it has two values like open, and then value two ok. So, it is the two items it is there,
and option one, what is this?

Student: Open and value two.

Open and value two. And value two is with the checkbox, where the open is ok. So,
value two is the checkbox. So, this is the idea about that checkbox can be added into
menu item.

1089
(Refer Slide Time: 15:49)

So, you can select, and add it like this.

(Refer Slide Time: 15:50)

Now, this quote can be little bit ok, we can go through and understand here. So, here that
event needs to be handled, because it is relate to the event ah associated with this one.
So, without event, it will not give that kind of flavor actually. And as we see the program
includes again Frame, and then Frame includes some default closed operation method,
those are defined therein Frame class itself. So, for this Frame class, we called it. And
that is the thing that is necessary.

1090
And this basically set as the exit on close means, if we just to I mean remove our mouse
click, and there it will basically close automatically, so that is why you have to do it.
Otherwise, once you open it, then it will remain, so that is why we have to set a exit on
close. And then we create the JMenuBar that we have already discussed that how the
MenuBar can be created in the MenuBar class. So, JMenuBar class, it is there.

And we create the JMenu objects, so there is a JMenu objects the name of this is file, and
then the set Mnemonic key event VK that means, if the event is occur related to the
function actually, it will takes place. So, this is the one definition, we have use it here.
And then menu item, we have added like open, and then another menu item that we have
appeared there is basically ok. So, yes so menu item that we have created here as the
open one, menu item one which basically with one argument as the key event virtual key
any number. And then we add this menu item, and then JCheckBox menu item, case
menu item, new checkbox menu item like this, and fine, so these are the few many.

And now here is basically the action l in routine as we see here, the different action that
can be handle here abstract button. We can create an abstract button type here a button is
an abstract button, abstract button is created with an event as the get source. And then
button get model, and if it is selected is true, then it will be displayed there.

And then there are few levels, we have used this string, and they are also icon image, we
can created here. And then value 1 and value 2 depending on the selected true or false. It
will be selected, and then it will add this button into the period, and then finally it will
just complete this one now fine. So, now we can have the demo again fine. So, this is the
one example that is related to the item the checkbox menu items in menu.

1091
(Refer Slide Time: 18:55)

Now, let us have the next one illustration regarding the progress bar ok. So, as you know
the progress bar, we will show the progress of happening of some event. So,
automatically is a dynamically, we will change it. And we can have a look about it, as we
see we have displayed the progress bar. And the progress bar with certain speed of
progress, we have already defined in our program that will be explain shortly and it is
there. So, it basically shows the (Refer Time: 19:35) it will stop it, wherever the compute
is there, and then close it.

Now, let us come to the program which basically can be used here in this particular to
give this kind of output demo. And we first create one object of class JProgressBar, here
is the jb. And integer i equals to 0 to num equals to 0 is basically initialize the two
numbers. And then we create an constructor of this example, so progress bar example.

Now, jb as a new JProgressBar has the range from 0 to 2000 is basically the range of
values you can that presided, but it is actually the progress will be computed in the
percentage calculation. So, no issue is there. Then size of the J bar JProgressBar is
basically had decided with the location as well as the width and height. And then set
value is basically 0, the program bar will start from the zero location actually, then j b set
string painted. So, it is basically true, because it will highlights the progress right. And
then finally, we add j b that mean the progress bar, we added into the Frame here is the
constructor of the same. So, it is added in the Frame, set side set layout ok.

1092
Now, here in order to have the progress dynamically changing, we have to define one
more function here that is call iterate. And this function as we see just loop, and loop will
continue till it completes from 0 to two 2000 there, j b set value is i. And then progress is
basically, how much speed that here basically i plus 20, so 20 at (Refer Time: 21:16).

If we change it, then progress bar will right improve it faster like ok. So, whether slow
movement or fast movement that it can be obtained like that way. And this basically the
way that way progress bar can be designed. And then finally, it will include into the
main, and the main an object can be created of this types and it basically will execute.
So, this is the way that a progress bar can be design, and it can be used.

(Refer Slide Time: 22:01)

Now, the next one example is very important in the sense that a tree structure can be
designed using Java swing. And use a tree structure mostly you are familiar with to the
different, whenever you open a directory using command pond or some I mean using the
command that is there in a computer. So, if you see the directory structure, so j t is
basically showing a directory structure that is possible.

In this example, as we see that is a very simple structure, again it can be expanded also
depending on if some other nodes are there in this tree structure. For example, here the
style is the root in the directory structure here, the style has the two what is called the
nodes namely colour and pond.

1093
So, if we select colour, if some elements are there, then it will automatically expanded
into that right, and then red, blue, black right. And if the red content some other, then if
you click it can, but in this case it is not there, so it is like this. So, it is a tree look like, so
it has the main. And from the main the sub main, and then from sub main is items like
this one. So, there is no limit of the hierarchy from which we can go from top to bottom
actually, so as we can see there.

Now, we will see exactly how such a menu, and then submenu or directly or sub directly
can be added into the component. So, this example shows, first we have to create a
Frame, f is the Frame in this case. And then we just discuss the program as the tree
example as a constructor, we will invoke this object as a constructor that is why.

And here the different items into the tree can be declare by default mu table, tree node,
and then style. So, this is the first one style. So, we have label as style, so that is there.
We create some other like colour pond also, because they are also table node t node
actually. So, we have created here three t nodes; style, colour, and pond. And then we
add colour and ponds to the style nodes, this is basically sub node of the style node, so
that is why we add this one.

And the next we create few more nodes relate to the different colours like red, blue,
black, and green, and finally we add this nodes into the node colour. So, this is basically
sub node or children of the node colour actually, so that will appear as the children of the
node colour. So, this completes the formation of different nodes.

And finally, we just create the J tree I mean tree, and passing the root node into it. So,
here we see we create the JT has the tree, and root node is style here. So, passing the
style. And then finally, we add this tree into the Frame, and whatever the other sizing of
Frame, visibility, and resize everything is done. So, thus includes the basically how to
create a Frame of our own, and as the output is shown, it basically will display the tree
look like this. So, this is the example of tree, and many more items can be added, you
can have the many other things are there.

1094
(Refer Slide Time: 25:27)

Our next example is the colour chooser. As you know you can set the colour either using
from the choice, as we have already experienced one such example in some other
demonstration session. But, here the colour choice, the Java swing gives you to have the
general tree of the different colours, and from there we can select a colour of our own
choice. And then that colour can be set as a background or as a pond colour or whatever
it is there, and this is an example can tell you.

Now, let us see the example here. So, this is the one Frame, and the Frame include a
button colour. If we click this button, the colour choice will come automatically here. So,
this colour choice is come, and then this colour choice has the different what is called the
options MenuBar in the menu as I see RGB, HAS, and HSB all these things are there.
So, these are the different way the colour can be chosen, and then it can be setting, and
can be set automatically it is there.

So, everything is basically light weight like that means, they you do not have to bother
about their direct implementation, it is there. You just can add it, then your in your
program you can access all the facilities, it is there. So, as we see the different colour
modes that mean RGB pattern, it can be shown. And accordingly, for them the different
colour can be set also.

So, this is the way now here is the different way the colour can be chosen actually, it has
give you the four different way the colour can be chosen. And also by clicking a colour

1095
point there, we can add the set the colour as we see the changing the colour, we can
change the colour point and everything. So, whenever you choose the colour, it will
decide there which colour that we have chosen, and what are the previous colour that is
the history. All the history colour also can be shown you in the recent pane actually. And
then all the colours has been chosen, and then this things are there.

Now, so many things those are there in details, but can be done with a minimum number
of coding possible. And here is the code that basically can deal with the colour chooser
component in Java swing. As we see the code, it basically the name of the class that we
are going to implement is colour chooser example extend J Frame, and as we have to
input some events. So, action Listener to be implements. So, it is basically inherits the
action Listener.

And then we create the button J button b that basically for the initially the colour that that
needs to be created there, as we have started with the JButton colour actually, so it is
there. So, we create the button, and the label as colour. And then add action Listener this
one, c add button, so we add this button into this component. And then get content pane
actually, so content pane is basically where this colour will content actually.

And then we defined the performance, so the event handling routine here action
performed action event e. So, colour in initial colour is basically chosen as red, these are
default colour. Otherwise, colour can be set as the J colour chooser, then show dialogue
this select a colour as basically is a dialogue that will be there, and with initial colour
actually. And then set background colour as a colour that means, whatever the colour
that you will choose, it will be set the layout with that colour that is all.

And then finally in the main example, we create an object of this colour chooser. And
then colour chooser will be placed into this component, and then it will be resize and
Frame displace. So, this is the way that is there, it is not so big what is called the steps or
basic complex procedures are there very simple, only you have to add the colour chooser
example there. And it can be added into your system.

1096
(Refer Slide Time: 29:11)

Now, our next example is basically TabbedPane. So, TabbedPane is basically let us have
the view of a TabbedPane window. TabbedPane as you see is a tabbed, so there many
tabs are there, as we see here in this example. A TabbedPane is appears with three menu
main, visit, and help. So, likewise the different menus can be added into there, and this
example explain the idea about it here.

So, we first create text area of size say 200, 200 here, so this means that this is the text
area of size 200. And this text area will include as a final actually, so this basically we
add this text area in into a panel. And there are two other panel p 2 and p 3 that we have
added there. So, other than the original pane will p 1, p 2, and p 3. So, p 2, p 3 are there
basically panel related to the different menus are there on this. So, p 1 is for main, p 2 is
for visit, and p 3 is for help look like.

And how we can add this into the TabbedPane is basically, if as we have created the
tabbed pane object tp, just we are going on adding all these menus there tp add, tp add
main, tp add say visit, tp add help p 1, p 2, p 3 look like. And then finally, we have to
add this tp that pane into the Frame, and it is completes the creating a tabbed pane the
way it will see the output as we have seen. So, this is the way the tabbed pane can be
added, and the tabbed pane also can include some other elements or it can include some
event generation, so that if we click this TabbedPane, some things will appear like.

1097
(Refer Slide Time: 31:06)

So, our next example is JSlider. We have already familiar is the JSlider, some glimpse of
JSlider have been used in our colour chooser example. It is basically similar, but it is an
independently one JSlider, how slider will look like as we see here is an output, let me
bigger yeah. So, here we can see example of a slider.

And then there is a slide button is there, if we click, and then drag, then the slider will
move across the vertical line some horizontal, orientation also possible for the slider, but
usually it appears is vertical one. And so this is the slider as we see slider if we moved it,
and and a tiny position, the slider is placed a value can be written there. So, there are the
way that the slider value can also be read.

Now, here is an simple example that it can includes a slider. So, we give the name of the
slider as JSlider as slider. And then is basically slider horizontal, so that is horizontal
movement. If you write the JSlider or vertical that means, the vertical slider will be there.
Now, the next three items are very important. So, first is shows that 0 and 50 is the
location is basically, what is the 0 and 50 ok. So, 0 and 50 is basically range, and then 25
is basically the width right in the pixel right ok, so default is there default. Whenever it
appears the default location in the range, that value will be appeared there. So, it is a 25,
it is the default location actually, whenever it is I start the showing it is there yeah.

So, the default location is 25, and then range is basically 0 to 50. So, the minimum is 0,
and the maximum is 50. And then we can add it into either Frame or panel. In this case,

1098
we have added this one panel, so slider has been added into a panel. And then panel,
finally add in to the Frame. And this is the way that slider can be there. So, we have
almost cover all the different important JSwing components, those are there in the
JSwing package, there are many more also. Those things you can write you can practice
of your own and more practices required, so that you can learn it much more in a details
way.

Thank you very much.

1099
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 48
Java Networking

So, now we are in a position to discuss about network related programming in Java. So
basically, the idea of networking is useful to I mean do certain what is called the
programming, so that the communication between two so users can be achieved. So, here
we have to cover how this network related programming can be done, what are the
different supports the those are available in Java networking, we will discuss. Before
going to actual networking related programming, we have to have certain familiarity
related to the network-related terminologies.

(Refer Slide Time: 01:11)

And then we will discuss those things, then these are the things that is required to
understand the next discussion. So, we will quickly cover the basic concepts of
networking and then finally, the Java. Now, you know exactly what is the process of
networking, it is basically is a process of communication between the two computers we
can say and they can communicate by this ok, if they are the connected through net
network actually, communication channel right; they can communicate, they can share
the file, they can talk to each other’s and like this one. So, these are the things it is there.

1100
And the networking is an issue, because as the time passing on the number of users are
more those are connected in the network and it becomes really very complex and
complicated, how these programming issues can be handled. And this is (Refer Time:
01:56) it has been evolved many ideas that how this networking can be done, the many
tools, there many what is called the environments are available, out of which Java gives a
very good one system, which basically allows you to write your own program and using
this program you can communicate ah communicate to any parties actually. So, this is
basically the basic idea about the Java networking.

(Refer Slide Time: 02:23)

Now, I will just quickly recapitulate the different terminology that is relevant to the
networking related issues that are there. And probably you know all those terminology, I
will just quickly touch there, so like LAN-MAN-WAN, WWW, IP address, port number,
URL, then MAC address and sockets, because all those things will be referred into our
Java-based network programming concept is there.

1101
(Refer Slide Time: 02:49)

Now, so for the local area network is concerned. It is basically the network is a
connection of computers of course, but this is called a local network if the network spans
within say maximum 1 to 10 kilometers within the range. So, usually it is basically on a
campus or even a large building, then the network that needs to be carried out is called
the local area network; it is simply called the LAN.

On the other hand, the medium area network a little bit larger than this one, this span is
usually 10 to 40 kilometers. So, if you have to carried out certain communication within
the city say suppose or an innovative metropolitan area, then it is called the medium
metropolitan area network that is why it is called the metropolitan area network or
sometimes medium network also we can say. And is an example is that cable TV
connection and or cable internet connection, all these things are basically an example of
a metropolitan area network.

On the other hand, a wide area network if the network ah what is called connectivity
extends up to a state or even the entire country, then it is called the wide-area network.
And the span is basically 40 kilometers and above. So, usually internet is a good example
of the public worldwide area network, there is maybe a public network, there may be
private network. Private network is limited to among the peer to peer communications
only on the other hand, public means anybody can be connected and then they can share
them use they can use this one.

1102
(Refer Slide Time: 04:29)

Now, WWW as you have heard about it is basically a popularly called the W3 or simply
web is a World Wide Web, is a web means it just like a net actually you can see, who is
basically spread. And the world wide web is basically related to the internet also because
the internet is a part of the worldwide. So, what is the World Wide Web? Actually, it is a
collection of huge what is called the documents, which are spread over the entire what is
called the network or you can more precisely call the internet. So, sometimes worldwide
web is also called a network of networks that means, is there are a lot of networks which
are connected to each other’s is called that worldwide.

And related to World Wide Web, there are many keywords which have been evolved and
fist said, 50 years or so, which we have mentioned like browsers, the search engine, the
content, hypertext documents, the computer, networks and so many things are there. All
those things evolved not in a day of course gradually, and today basically we see exactly
what is the World Wide Web to and today World Wide Web is basically indispensable in
our day to day activities.

1103
(Refer Slide Time: 05:47)

Now, so far the different computer connectivity’s are concerned every computer should
be uniquely identified, there should be some numbers for that and that is what the W3
consortium they proposed one mechanism, it is called the IP address concept. So, it is
basically IP stands for Internet Protocol.

So, IP address usually is a 4 byte address segmented into 8 bytes each, and then the last 8
byte is basically hosting id that means, if one computer is connected to a network and
that network may have its own id, usually that is decided by the first 3 bytes; in the last
byte is for the computer which is connected to this network. So, it is basically as it is an 8
by 2, so each byte value if you express it is basically in the range 0 to 255 as an example
192.168.0 is the basic one network id, and then .1 is basically the host id means id of a
computer. So, this address is not exactly the physical address, logical address.

Logical I say in the sense that whenever one user wants to connect to a network, he or
she should approach to the network administrator, the network administer will assign one
id; whether it is a network service provider or your network administrator in your
organization, whatever it is there.

1104
(Refer Slide Time: 07:19)

So, this is the IP address and in addition to this IP address, there is also on another
identity is required it is called the port number. So, port numbers related to a particular
and application. So, whenever you run one program, whether it is a Gmail program or is
a browser program or whatever it is there. So, it is basically created an application.

So, every application should be uniquely identified, usually it is that identification it by


means of it is called the port number. So, usually, the port number is related to the
machine itself. So, every machine is given a unique port number and together with the IP
address and port number actually called the socket address. So, the socket addresses
nothing but this is an address of an application.

1105
(Refer Slide Time: 08:03)

And then there is also the concept of URL, probably we familiar to an example of URL
like www.google.com. So, this is the one example of URL it is the full form is Uniform
Resource Locator. Now, here it is basically one idea about by which a particular what is
called the document, we can say the hypertext document like or a particular server can be
identified.

Is basically if we have this URL, then we will be able to quickly look at a computer
where it is located. And for this location as you see there are many parts are involved,
one is called the domain name. And the domain name has the 3 components, is basically
connected to which computer for you www this means is connected to the web that
means, internet. And .example is basically the name of the server, where that particular
file or document is located. And .com is the name of the organization and that means, it
is basically .com or is basically say .in that means, it is connected to India or .au for
Australia or .ua for USA these kind of things are there .UK United Kingdom like this
one.

So, the different country has the different what is called the extension of these domain
name. And then private organization .com is basically for all commercial documents
related and like this one, .org the for an educational institution, .edu also other additional
institution like. So, these are the different organized wise the naming is there.

1106
Anyway in addition to this, so this is basically called the location of a particular file and
there is also another is called the protocol. So, which protocol that it should use in order
to access that document, it is specified by that one, for example, HTTP it is basically
protocol. So, it is basically (Refer Time: 10:03) protocol and then followed by the
resource name, resource name is basically www.example.com for example, in this case,
is basically both together includes the URL.

(Refer Slide Time: 10:29)

So, there are different instead of protocol, here we have uses example one protocol
HTTP, near there may be FTTP or FTP or SMTP like this. So, a different protocol is for
dual discuss about the different protocol shortly. And then MAC address is basically is a
another physical address, where the IP address is a logical. So, it is physical address
means whenever you purchase a computer, the manufacturer assigns on unique number
to this computer and these are this is called the MAC address, the full form of this is
Media Access Control address. And this is also unique for every machine whichever it is
manufactured in till time has the unique number.

So, this MAC address is specified by 48 bits number, again each of 8 there is 6 8 bytes
segmentation which is basically usually expressed in a hexadecimal number like, so
usually max at this, for example, I have given the MAC address of this one.

1107
(Refer Slide Time: 11:23)

So, MAC address is also required again to identify uniquely a location of a particular
machine. And then socket as the socket is basically is a is an application program, you
have a software you can say is a port we can say which basically use for the
communication, is basically is an application program which is responsible for
connecting two endpoints.

So, if you want to connect two computers in a network, this means that that connection
can be controlled by means of two programs at the two ends. So, two computer which
should run two programs, they are called the socket programs as you know the socket is
basically connected to a computer. So, every socket should be uniquely identified and
that for this the IP address in combination with the port number both together call the
socket address. For example, as you see the socket address of this machine is 10.14.90.85
and the port number is 27017 like. So, there so including these two things basically
combined the socket address. And therefore, a socket is not a hardware device, it is
basically software.

1108
(Refer Slide Time: 12:29)

And now let us come to the communication protocol, there are many communication
protocols that have been proposed so far people you are using, like say UDP protocol it
is that all connectionless protocol whereas, the TCP is very popular one protocol trans
Transmission Control Protocol is called the connection-oriented protocol.

And there is another protocol, which is connection-oriented as well as connectionless it


is called the TCP-IP. In fact, IP is the one protocol just like a UDP it is called the
connectionless protocol. So, TCP-IP is a combination of both the thing and FTP is a
protocol, which is basically used for transferring the file from one machine to another.

And HTTP is the file to accessing web documents, like say HTML page like and it is the
full form of Hypertext Transfer Protocol and HTTPS is the one it advanced version is
basically Hypertext Transfer Protocol will follow the simple document transmission
whereas, the HTTP follows the secure document transmission as the security is there is
basically security is enforced by means of some encryption and decryption. And SMTP
is also just like an HTTP it is, but it is related to an only application for the mail transfer.
So, if you want to communicate your peers using mail and everything, so usually you
follow SMTP for which you have to follow one mail server. So, mail servers usually
follow SMTP.

Now, here is again connectionless and connection-oriented, the two protocols by name
you can understand that if it is a connection-oriented protocol means before the

1109
communication, there should be the connection between the two computers should be
established, so that is the one idea. There is a mechanism by which the communication or
connection can be established prior to the communication begin. So, there is called the
communication-oriented protocol.

On the other hand, connection-less protocol means, if the two-party want to


communicate themselves, that they do not record any prior and at the prior connection to
be established, they simply start sending their documents. Now, it is just like a sender
sending a letter to his friend how he can send, you just simply write the postal address of
the friend and then drop it to the post box, and then there is a postal service is there. They
will channelize this letter into a particular frame-like. So, it is the procedure is called the
connectionless protocol.

Anyway, so these are the protocol and more interesting fact is that Java supports anyone
protocol whatever we have mentioned, whether it is a UDP or TCP TCP-IP or HTTP
HTTPS absolutely not the issues there.

(Refer Slide Time: 15:13)

And so these are convection-less.

1110
(Refer Slide Time: 15:13)

And connection-oriented protocol, as you have discussed about.

(Refer Slide Time: 15:15)

And then TCP-IP is also one protocol which is basically more reliable as well as fast
usually connectionless protocol is not reliable; however, it is fast whereas, a connection-
oriented protocol is highly reliable, but it is not so fast. On the other hand, TCP-IP is a
combination of both connection-less and connection-oriented protocol which is reliable
as well as very fast.

1111
(Refer Slide Time: 15:41)

Now, the FTP protocol is for the transferring file.

(Refer Slide Time: 15:43)

And HTTP is also transferring the hypertext document. For example, say the document is
an HTML page who is hosted some scraped, PHP, Javascript or even a plate-like this
one. So, this basically how these files the documents can be coming I mean, can be from
one server, can be brought to a browser machine here for maybe see your local machine
and so and so on. So, these are protocol that it follows.

1112
(Refer Slide Time: 16:07)

SMTP is for transferring the file document.

(Refer Slide Time: 16:09)

And there is obviously, some salient points the between HTTP-FTP and SMTP, I have
listed all these points here for the summarization of all these aspects you can take your
own time to go through this and then can understand it.

1113
(Refer Slide Time: 16:25)

Now, I will come to that Java networking which is more important things to understand
at the moment. And for the Java networking, there are many ways actually and all the
things can be categorized into two categories. They basically called the stream class and
then the datagram sockets or stream sockets and datagram sockets, as you know socket
means a program actually. So, the program should be written in the Java language.

So, there are two ways the program can be written, one way is called the concept using
stream sockets and another way is considering your datagram sockets. So actually, these
are the two different programs, if we use the two different classes for communications
among the two parties. Now, so far the stream sockets are concerned, it basically the
related to the connection-oriented service like say TCP.

ah So, according to these sockets it basically first establishes a connection between the
two communicating parties. And then whenever the connection is established, then they
will start streaming the data from one machine to another as a continuous that is why it is
called the string sockets. And here as I already told you, this is a connection-oriented
protocol that means TCP is followed here.

On the other hand, datagram sockets are another way of sending I mean communicating
between the two parties, it is based on the connectionless protocol. Here actually what is
that the entire documents or the content that needs to be channelized, needs to be sent

1114
from one into another is basically divided into small parts, each part is called the packets
or more precisely it is called the datagram.

A datagram is just like a packet consists of maybe say 64 bytes or every 1024 bytes the
network admitters can decide that what should be the size, but the standard size is 64
bytes like. So, is a smaller bytes packets are created. So, entire documents if it is a 1 MB,
it will be fragmented into 64 bytes each, each, each, each. And then it starts sending one
byte at a rate, and then whenever a packet is there or a datagram packet it should include;
who is the sender and who is the receiver all at this everything is there.

Now, it starts sending start dropping this packet into the network. And then the network a
controller is there, which will basically decide that whether if this packet is available to
him when to which direction he should forward this packet, so that ultimately it will
reach to the destination ah points. So, this is the idea about this one and this protocol
popularly called UDP – User Datagram Protocol.

(Refer Slide Time: 19:07)

So, these are the two protocol that is followed here. And again there are obviously, some
comparisons between the TCP versus UDP. The basic ways that TCP is connection yes
or else the UDP connection-oriented, where is the UDP is connection-less. And there are
some other more implicated the differences are there which has been listed here, again I
advise you to just go through all the points and try to understand that is the difference is

1115
there, but at the moment all those difference is not so much important. So, for our
network each programming is concerned.

(Refer Slide Time: 19:41)

Now, I will come to the discussion on what are the different process so that we can
utilize, because you know Java is the object-oriented programming. So, for the
implementation of anything, we have to rely on the different classes. So, I will just
discuss what are the different classes which basically you should learn so that you can
find yourself comfortable with the network-related programming with Java.

Now, here there are few classes related to the connection and then identifying a
connection like. So, we have listed here like URL is a class, URLConnection is also
another class, and then HttpURLConnection is another class, InetAddress is class, we
will go quickly go through the different class, they are compositions and then they are
utilization and everything also illustration. And then so these are the different classes by
which the connections related information’s can be maintained or can be controlled.

And then regarding these connections and then making the communications actually, so
that means sending and receiving and everything, it has been followed by few more
classes, like DatagramSockets, ServerSocket and the Socket. Now, DatagramSocket is
basically the concept that followed is a datagram streaming that means for UDP protocol
like, whereas ServerSocket and Socket is basically for the TCP related protocol that
means, connection-oriented protocol like.

1116
So, ServerSocket is basically whenever we have to make one machine as a server and
then socket is basically for making some machines as a client. So, it is basically for
client-server computing or distributed computing line. Anyway, we will discuss the
different ah concept of all the classes that are basically very much essentials here, relate
to the Java networking program.

Anyway, all these classes definitely are Java is very organized on system, they are
defined in a package. The package, which basically used for this is ava.net.package.
java.net.package is basically is the package means for including all these classes, where
users can get it and then you can use it.

(Refer Slide Time: 21:49)

Now, I will first discuss each one class one by one followed by some illustration, so that
you can understand the concept that what are these classes has these facilities and on
what occasion which class should be used like this. So, the class URL and I know you
have already mentioned what exactly and URL look like. So, URL first point is which
protocol that it follows.

For example, in this example as you see there are two parts in this URL, https is the
protocol that it should follow. And then followed by the what is called the resource
location, this resource location is basically nptel.ac.in/course.php, this means that in this
location, there is a file available means a user, a browser, a party can access on the tile

1117
the name of the file is course.php. So, the course.php can be accessed by means of this
URL and here another thing is that from which machine that this file can be accessed.

So, the middle part that is nptel.ac.in indicates in which server, this file is located. And
then if this file and this server are identified, then they are definitely what type of
protocol transmission should be followed in order to get access to this file into your own
machine. So, here, therefore, the protocol, the server name and sometimes the server
name should be associated with port number also. For example, nptel.ac.in and then
colon and the port number say 5 0 5 0 that also can be specified; if no port number is
mentioned, then by default the port number will be considered as a minus 1, so this is the
default standard and like this one.

And then finally, the last component is the actual document specialist at the document.
Like, say if we say there, test.java. So, this is the file that you can have and then we can
access it. So, it is like this so this way the URL basically imply it, now whenever we can
define a class. So, a URL basically this is an object as you see, so then this is basically an
object and we can say that URL object that means, URL consists of so many
information; what is the protocol, what is the name of the server, what is the file name or
maybe. So, this is the name of the server that we can understand, but in new of this on
the server name can be also uniquely identified by IP address say 155.18.20.31, so that is
also this one, so logically address is there.

So, it is in and there and there may be one machine that proxy we can say, a proxy has
the tank mapping that if this is the name domain name or the server name, then
corresponding this which is the IP address. So, there is a table maintained for every
network there is a proxy machine, which basically includes everything if this is the
domain name then what is the IP address like this one.

So, so this is a very important one concept about regarding the location or a precisely
specifying the machine that is there. So, this basically the URL location and the URL
classes basically has many other constructors as well as method is there.

1118
(Refer Slide Time: 25:27)

Ok.

(Refer Slide Time: 25:37)

So, the methods those are they are in URL by there are few more methods also, but I
have mentioned only those are most important methods are there; getProtocol, getHost
that means, the name of the host and then getPort, getFile, and then openConnection, like
this one. So, I have already mentioned about the URL. So, if it is a URL object is given
to you, and then you can get although the information from there.

1119
(Refer Slide Time: 26:05)

And so this is an example you can understand, this is very separating a simple example.
So, we can create a URL object like this one, sending this information. And then from
this URL class and using this getProtocol method that we have already discussed, we can
have all the information related to this object. So, this is a simple example if you can run
it, you can get an idea. So, instead of any other URL, you can mention any URL of your
own and you can find the execution of this thing you can understand about these one.
And so this is the URL.

(Refer Slide Time: 26:41)

1120
And then the next class is called the URL class, URL connection class. It has the two
methods mainly, the open connection and get input stream and this open connection is
basically to establish a connection from one machine to another machine from the
current socket to the distant socket-like. And then get input stream basically, how the
data can be read from the distant socket or from another socket to this current socket. So,
this is the two methods usually very much useful, there are some other methods also
those are very much essential right, but those are the methods we have we will be
referring here, we have mentioned here only.

(Refer Slide Time: 27:15)

And this is an example that you can check it quickly. And so this is basically URL object
is created, and then we just make a connection and this is the method by which we can
make the connection. So, this name of the connection, connection again is an object
everything in Java theater engine objects. So, URL connection and then once the
connection is there, then we can create a stream and this stream is basically getting input
stream for this URL connection that means, if this is the machine and we can connect
this another machine like right from so this is basically the distance machine.

So, this machine address is this on, it is your own program from where I am running this
one, so this one. And then from there, I get a get input stream means I am reading the
data from this machine. So, this is the idea about each here that and then we can start
reading this data in the stream ah. So, long the end of the file has occurred which means

1121
the entire file will be read from the distance machine and will be stored into the local
machine-like. So, this is a very simple example that explain these concept that how the
URL connection can be utilized to fetch data from the distance machine through the
communication.

(Refer Slide Time: 28:21)

Now, HttpURLConnection is very similar to URL connection only, but only in this case
the protocol, that it should follow HTTP protocol only.

(Refer Slide Time: 28:29)

1122
And here is a rather different methods that are included in the HttpURLConnection, the
huge number of methods are there, but I have mentioned only two methods other
methods you can obtain from the core Java material, tutorial that is there.

(Refer Slide Time: 28:41)

Now, let us come to the example here as you see, so this is the URL connection, URL
objects. And these basically the idea about, how the HttpURLConnection can be
established. And once this connection is established rest of the things is same as the
previous one. So, this is the idea about so only these basically make distinguish or simple
communication or the URL HTTP communication like.

1123
(Refer Slide Time: 29:07)

And InetAddress also similar to the URL address, but it has a different way the internet
address related composition. So, he is basically IP, Port, everything can be there, it can
be understood. And as you have seen these are the different methods is very similar to
the URL like, the different methods are there by which you can access the different
information related to the different connection of a connection with them about the
different connection.

(Refer Slide Time: 29:33)

1124
And here is another example that you can see. So, InetAddress just like a similarly URL,
this is basically the URL we can say I have specified and get by name and InetAddress.
So, IP is basically the I InetAddress in this case, one this InetAddress is there, then we
can have the different method getHostname, getHost localhost and everything of this
method. And then we can obtain the different information, the concept is very similar to
the URL connection and the idea it is like this. And here is an example that you can run
this program.

Now, I will come to the communication. So, using the sockets basically and there are
two types of sockets, rather 3 socket DatagramSockets, server socket and socket only.

(Refer Slide Time: 30:17)

So, DatagramSocket basically follows the UDP protocol and the different methods those
are defined therein DatagramSockets, these are the basically constructor by which a
socket can be created actually that they are different constructor means, I can either we
can mentioned the port number or we can means at the port number as well as either at
this or you cannot mean some anything. So, this socket is basically if you want to
communicate within the same localhost that means, maybe that within the same machine
like one machine can be connected by the two users.

So, it is basically shear single shear machine is sheared form and then there protocol can
be followed, but here if the distance machine from this machine a to another machine b.
And it is also a distance machine, but if you know the InetAddress quickly early. So,

1125
these are the differences I mean constructed those are useful for the DatagramSocket
like.

(Refer Slide Time: 31:13)

And these are the methods getAddress, getPort, and then getData and getLength. getData
is very important in order to get the data I mean ah get fetching the data from the
machine to that machine here.

(Refer Slide Time: 31:27)

And this example is very easy to understand and very simple example I have planned for
you. So, in this example as we see DatagramSockets ds object is created, and here you

1126
have to mention the port that is the port number which we and this machine this example
is basically, in the same machine how it can be shared the documents actually. So, the
idea is there you can run the two programs, socket program so that means, two different
threads are there.

And that two threads is just you can simulate that ok, this is the one party and this is
another party; like so one party is called the receiver, another party is called the sender.
And this is a receiver socket and this is the Sender sockets. The idea is very simple, first,
you have to keep creating a DatagramSocket objects as you have created here. And then
to do this thing, I have mentioned here port number. So, the port number should be the
same as these two machines, these two programs who run in the same machine. So, for
both servers and send receiver and sender it has the same port number.

And then here you just create a DatagramPacket. So, DatagramSockets and
DatagramPackets are basically to see that whatever the message that you want to
communicate, how the entire message can be created into a number of packets, a packets
may be of 64 bytes as I have told you. So, this object we will do these things for you.
The entire buffer if you give it, then this dp will create the packets that needs to be
transmitted from one party to another here.

And then once it is there, then this basically dp.getData can be converting the string and
the same string can be transmitted by this means of the method. So, receive the dp that
means, it basically receives packets that can be a send that has been send by some
machine and it will receive. And then after receiving this packet dp, it will basically
process that means, you can process shown or you can display whatever it is there.

So, this is so further received is concerned. And nowhere is basically sending, as you
know the sending here. So, suppose I want to send only this text, Welcome to an
NPTEL. So, first I have to create a DatagramSocket ds, as you have to send in the same
machine. So, a port number is the basically same thing that you can do, otherwise, you
can do not use anything also. And then this is the message that I want to send it, is very
small message of course in this case, but actually it can be very large file, in that case, I
can mention that this is a file that you have to store, but using say file input stream the
file can be converted in the stream format and that stream can be put into that datagram
like.

1127
And then this is the ip at this from here you have to send it. Now, here is the one thing is
that or it is a default that if the same machine it will already assign one ip address that it
is this one 127.0.0.1, it is the standard default only. So, this is the default ip address if
you have to communicate within the same machine only. And then the DatagramPacket
that will be transmitted about this string. So, it is a string we convert in the
DatagramPacket, and then we send this DatagramPacket to this port and then is basically
send.

So, the DatagramPacket has been ready with these destination addresses and everything
and therefore send. So, this way the sender will send, it will go to the receiver, receiver
will receive, and then it will be processed. So, this is basically the communication
between the two parties, which are basically using the same port we can say. Same port
in the sense that they are the same machine.

(Refer Slide Time: 35:01)

Now, so another is a class ServerSockets, these have the few constructor as we have
mentioned here. Again the port, the InetAddress and then time that needs to be queued
and so many things are the basic information that needs to be provided in order to create
the object.

As I have already mentioned you, the server socket is basically the program that
basically suitable for maintaining one machine as a server that means, this machine may
be connected with many clients, those are either in the same or you may the same system

1128
or maybe in the remote systems whatever it is here. And so idea it is like this, so server
socket is there. And the constructor it is these are the constructor.

(Refer Slide Time: 35:41)

There are many more methods are there, I have mention few methods here.

(Refer Slide Time: 35:49)

I have mentioned a few methods, those are very important here. For example, getting the
information about the port, and connecting that accept I mean accepting a
communication connection, and then how much time that it should way to listen to

1129
others, those are the different information which is basically can be maintained by and
then can be obtained from the from this method for a ServerSocket object-like.

(Refer Slide Time: 36:19)

And then Class Sockets, very similar to this server socket itself only the thing is that
socket can be used to represents a client machine, so that is why and it has the different
constructor as I have mentioned here. And in addition to these constructors, there are
many other methods also involved.

(Refer Slide Time: 36:37)

1130
So, these are the methods very similar to the server sockets. And then I will quickly
conclude this presentation with more few examples, 2 3 examples I will give it. So, a
simple client-server.

(Refer Slide Time: 36:49)

For example, I have already given an idea about the sender and receiver. It is a very
similar tune only, how this program basically explained, how one machine can be made
as a server, another machine can be made as a client. So, the here basically the
ServerSocket to be created and here the socket is created. Once it is created is basically
by means of getInputStream, it will read it; and by means of getOutputStream, then it
will basically send it. So, these are the two concepts by which communication can be
established. So, this is the idea about communication here.

Now, the server as you see in this program we have created a socket as an ss and
ServerSocket ss also. Now, here ss this basically we create ss dot accept means, the
server accepts any response that is basically made by on a request that is made by a client
so that it will accept and then the DataInputStream is a class by which it will read data
from the client actually. So, it is a right s is the socket program in the client and ss is the
socket program in the server in this case and then it will basically send. And finally,
when the message receiving is complete, so it is basically closed. So, this is the idea it is
there.

1131
(Refer Slide Time: 38:11)

And then once it is this is the server program and similarly the client program it looks
like, so this is the client program. And in this client program, we create a socket program
here, so s is the socket objects. And then DataOutputStream, because here client we will
send some data to the server, and this is the message that the client supposes to send it.
And this basically message will be transmitted, I mean will be sent to the net and then it
will go to the sockets and then this one. And here is the port number, this port number
should be the port number of the server to which it wants to communicate actually. And
it should be same is in the case of both server and then socket as you see here, the port
number that we have used here.

1132
(Refer Slide Time: 38:53)

Is basically 6 6 6 also, it is basically in the server. Now, so this is the idea about that ok,
here in this particular example how a client machine can send a document to the server,
and then the server can receive it and process it.

And our next example is basically to give the dialogue that means the client will send
something, the server responds to that; again client will send something, the server will
respond to that this is called the dialogue process. And this is an again simple program to
understand this concept.

(Refer Slide Time: 39:25)

1133
And here is basically the server is basically this is the server, and then server as the
ServerSockets and these basically accept and this is basically input, output mechanism
that is read from the client right through the client like this one. So, for which data input
and DataOutputstream, d in and d out has been created, and then it will be for reading if
the large message needs to be read. So, data to buffer reader should be used, so it is a
buffered reader and from the buffer reader it basically is reading, and whenever there is a
message that from the client that is a stop, then it will close the service, then server will
stop it there.

So, this is the server-side program. Is a very simple program actually as you see, and you
can understand easily just you have to remember the input-output stream, we are once we
have discussed about our IO stream concept like.

(Refer Slide Time: 40:17)

And this is the client-side program. On this client-side the same port number it should
use. So, it is based on socket and the local host means is the local actually in the same
machine. So, in the same machine two programs, we will learn. So, it is quite possible
multiple program can be executed in the same machine, Java allows these things very
heavily, so it will there.

And then data is basically input-output that means, client will send something, client will
receive something from the server. So, this one again the buffer will be there, to read the
network line actually channel, and then this is the communication continue until the

1134
server wants to continue it there. So, this is the idea about the dialogue client-server as
you have so it is a basic dialogue between the two machines. And this is the one example
here, in the last example we have considered that in the same machine, but in this
example if the two distance machines are there.

(Refer Slide Time: 41:09)

So, obviously you should know exactly what is the IP address of the distance machine.
The program is very similar to the previous one, only the difference is that we have to
explicitly mention, the IP address and then these are port number and number of client
that it can support in this case. So, this is the only change in the server program,
otherwise, everything remains same. The client program particularly is the same program
as it is the earlier one.

1135
(Refer Slide Time: 41:35)

So, this is the client program already we have discussed and you can run it, we can
simulate it in the same machine or in at the distance machine also the output that you will
can obtain. And then again the communication, dialogue, chat, and everything whatever
you want to do, you can do that. So, this is basically the remote communication between
the two machines.

(Refer Slide Time: 41:55)

And then a concurrent server is basically one server that can process more than one client
at a time, so it is called the concurrent server. In this case, the threats to be maintained

1136
and if there should be some method should be by which the client handling client can be
handled. So, here again this is an example, so this basically creating the server as a
socket and for this server socket we accept any client that it send the request, and so this
is the same thing as earlier.

(Refer Slide Time: 42:25)

And then the next thing is basically here is the thread that you have to create it. And for
this thread, this is the one simple intermediate procedure about an input-output stream
that needs to be created. And we create a thread here; this is because you have to
establish a thread there. And this basically ah so the thread is basically here, the
implementation of thread method in the last example we created thread actually.

1137
(Refer Slide Time: 42:59)

So, here we see we create a thread here, so a server is a thread. It will run for so long,
and the thread needs to be handled by the ClientHandle by means of input stream and
output stream, those are things to be mentioned there. So, this is basically created thread.
So, in this case, the server is a thread and we start the thread. Once the thread is started,
we have to define the thread.

(Refer Slide Time: 43:23)

And thread define means all the methods you have to define it here. And the run method
is basically is defined as the thread of how the thread needs to be run actually. And here

1138
is the server part next part of the server; that means, we just continuation of this one
while is basically this is an infinite execution, while it is truly like.

So, until you do not at a disconnect the connection, it will continue this one. And then it
will receive the message, send the message, all these things will be carried out in a
synchronized manner actually, so that program is like this, so that concurrently that
means it does this basically constantly attend attending on client request if it is there;
once it is there, it responds immediately for which the thread is basically mean for that.

(Refer Slide Time: 44:11)

And here this is the continuation of this program.

1139
(Refer Slide Time: 44:13)

And the client program, as usual, the similar one, absolutely there is no same where
different. It is basically same, we have to make this as connection as a 5 0 5 6 is the port
number of the server itself, and then input-output stream for the dialogue communication
if you want to maintain. Then it basically than any other protocol says maybe say, here
we are using the ip i InetAddress, basically TCP-IP protocol, but you can mean some the
datagram protocol dp and you can use it.

So, in that case of a message needs to be the first packet it using the datagram packets
and it can be sent here. So, this is the idea about the concurrent servers both in the client-
side and then server-side. And this basically explained the different mechanisms by
which the communication can be done and as in the class of learning right. So, we are
basically learning, how the communication can be written using Java program, so that is
the only focus we have. Now, in our next we will discuss some demonstration of this
program so that you can see exactly how they run and then how they can execute, and
then how they can see the result actually.

So, we will discuss about the demonstration of this program in our next module that we
will give an idea about, how we can implement all these programs and then you can
execute it and you can see the output.

Thank you very much.

1140
Programming in JAVA
Prof. Debasis Samanta
Department of Compute Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 49
Demonstration – XIX

Now, we have quick demonstrations of the different classes that we have discussed in
our last module related to the Java networking and as you have learned about the
different classes are there.

(Refer Slide Time: 00:31)

So, in this Demonstration we will try to emphasize about the different classes and their
utilizations and then how the internet how the URL related information that can be
accessed given the URL and like this one. And then mainly we will discuss about the
client server; that means, how the 2 sockets can be designed and then that 2 sockets can
communicate to each others.

And there may be one server sockets and the client sockets like and they are also the two
way communications also and then there a concurrent communication; that means, ones
client one server can serve the request to many clients which are connected to that server.
So, those things we will try to give an I mean demonstration in this session. So, that let
us have the first program and this program is related to the URL class utilizations as we
have said that every URL can be created as an object. So, this is called the URL objects.

1141
(Refer Slide Time: 01:29)

So, for example, https://nptel.ac.in/ some file name is basically is the URL and then
regarding this URL we can make a connection. So, the connection is that whatever the
location we have specified to that the distance machine or local host whatever be that, so,
it will make an connection. But here URL basically in other than connection we can have
the many methods are there by which you can access the information about the url. For
example, which Protocol that it has been used or what is the Name of the server, what is
the ip address of the server, what is the Port Number, what is the File that we are going
to access whatever it is there.

So, all these informations can be accessed here. As you see in this program we create an
url object. So, this is basically url object here and then we just the is the constructor of
the URLClass argument is the URL specification this is the url actually for which you
want to have the information. And then this url is an object and for the subject we can
call the different method like say getProtocol, then getHost, getPort num Port, then
getFile everything. So, here basically file is this one and whatever it is there.

Now if we run this then definitely it will try to find a communication connection from
this machine, this program actually. So, this program to this one server and if there is no
I mean violation in the Protocol then definitely the connection will be successful.
However, https is a secured protocol so, from every program it may not allow the
transmission. Now let us see exactly if we try to run this program whether our https

1142
protocol service can allow you to access to this connection and then finally, fetching the
file it is here. So, I will just run this program here.

So, this program has been successfully compiled. So, no problem so far the compilation
is concerned there. Anyway we are not getting the connection here, so, only we are
getting the information about the crl. As you see the output; as you see the output here
and we see that Protocol that is the https the HostName is basically nptel dot ac in and
the PortNumber in this case is minus 1 and then file that basically which this URL
specify course dot php is everything is a accepted from this method only ok.

So, this is the first example that and in major program actually we will I can have this
URL class if it is then lot of information about these things can be accessed and then
those information can be used for our communication purpose. Our second example is
basically the URL connection; that means, it basically used to make a connection from
the specified url location to the current program. And, this program if you see here again
we create the url object here and then this is the url and then url connection is basically
this create and object which basically a connection object here in this case and open url
dot openConnection(); is basically for opening a correction.

And then once the connection is open, so, this basically stream it basically is a basically
TCP protocol you can stream sockets like is a continuous stream can be stored here and
this is the stream buffer we can use it here. So, that all the steam that can be connected
by means of reading the distance machine the things will be there and here is basically
displaying the content that we have there.

Now, here we have to establish the connection, now you just running the program and let
us see after the execution whether we can get the file from the distance machine yes or
not. Now here is the problem is because we are not able to establish the connection as
this is the https actually, other than https or some other protocol if it can followed. Then
it may be possible to face the file here in the local machine, but here because the protocol
is a restriction, so, that all connections.

1143
(Refer Slide Time: 05:39)

We have sent the request; however, the protocol that implemented in the server end
where is the nptel dot is that the refuse our connection, so, we could not get this one. So,
here you can see connection timed out that mean they it has tried to several times and
send the request, but that server has refused the connection that is why it is there.

So, because of this protocol only we could not could get it there, some other some of the
machines other point if it is connected on it if we do it then maybe the communication is
successful ok. So, this is the example regarding the URLClass and then URLConnection
Class. Now here is an another example HttpURLConnection is basically the connection
which basically follows the http protocol and this example is basically the similar to the
previous one. And as you see that this is the url object we have created specifying the url
location and then this is basically the opening the connection following the
HttpURLConnection.

So, here is the object that we have followed to do that; that means, connection objects.
And then for the entire connection if it is successful we read the entire document by just
here actually we are not adding the entire document rather for this http connection
actually http has the lot of information these are called the header information. So,
HeaderField usually there are 8 fields are there.

So, in this program we attempted to read all the HeaderFields that is there in this
connection objects. So, this program will do these things and if we run it then

1144
HttpURLConnection, then we will be able to find the header information those are there
in this connection right.

Here also because of the https we are not able to get any information regarding these
what is the header fields and others. So, that is why the connection is not successful and
then connection is timed out. Now, next example that we are going to discuss about
communication using user datagram protocol which is the connection lists on service
basically.

(Refer Slide Time: 07:49)

And before going to this InetAddressClass; so, this example related to the
InetAddressClass and ok. So, InetAddress is basically the similar to the concept it is
there InetAddress ip InetAddress guest getByName and this is basically the name of the
ip locations or other is a server where it is located this by this is again a url sort of thing
only by the domain name at that we have followed here. So, actually Inet is basically
corresponding to this server as we have already mentioned there is a particular
IPAddress, logical address.

So, basically with this ip is an object by which we will be able to access the different
information regarding the inet addressing scheme. So, here so, getHostAddress what is
the name of the host? What is the PortNumber? What is the name IPAddress everything
we can be obtained here. For example, in this case we have to we are printing the IP

1145
Address ip. So, IP Address like 8 bit 4 8 for 8 bit content in the ip for concept it will be
displayed here.

Now let us run this program. So, that we will be able to see exactly what is the IP
Address of www dot nptel dot ac dot in from this and then the guest hood address also
yeah.

(Refer Slide Time: 09:11)

As you see here the Host Name is www.nptel.ac.in and then IP Address for this
particular machine is 14 dot 139 dot 160 dot 71. So, this is an example about it
InetAddress related.

So, we have discussed about the URL, URL connection, HttpURLConnection and then
InetAddress they were the concept basically regarding the actual specification of the
distance server out of all even the server or any other machines that we are going to
connect or establish a connection

1146
(Refer Slide Time: 09:43)

Now after having this information now it is our task to see exactly the as we have
mentioned there are 2 protocols connection oriented and connectionless and they are
basically implemented using UDP and then TCP IP; UDP for connection less and then
TCP is for connection oriented these are example that we are going to discuss going to
give you is that connection less protocol following the UDP. And here the basic idea is
that we will prepare the 2 programs, 2 sockets rather using the DatagramSockets and
then DatagramPackets layer.

And then the 2 sockets we will run concurrently in this at the same time in this case in
the two sockets are in the same machine, but from the two different windows this means
that assuming that this is basically they are running in a separate machines actually. So,
in the first example as you see it is basically is the server sockets. So, it this is basically
wait to receive any requests from one client and if it receives on request then it will
basically responds.

Here in this case as we see we create one object called the ds is a DatagramSocket
objects and then you have to give the port number here you are giving that port number
you can give any number here because it is implicit to give any port number. So, we have
given one port number whatever it is there 4 digit, 5 digit whatever and by the by with
our own today we have given 3000 (Refer Time: 11:25) so, no problem, but if this port
number should be used for other communicating programs other sockets also.

1147
Anyway, so, this is the basically buffer where you want to store we made that 1024 size
of the buffer and we create a DatagramPacket here. As you know UDP follow
DatagramPacket concepts that mean it will convert or enter the message into number of
packets of peak size say 64 bytes like and then these basically packet we will create these
things here is the 1024 is the total content the message and then its basically converting
the packets actually.

And then here the this datagram packet is basically send they as a buffer like if we
receive any message from the distance machine or from other sockets it will store into
this packet. So, you receive the packet and then all the packet will be stored here in the
dp and so, this is basically the receive is the method which is defined there in
DatagramPacket concept itself. So, it will basically receive all the packets from the
sockets and then that packet will be display here this is the method by which the entire
packet content can be displayed on the screen.

We can save this packet into our local machine also using file output stream program and
then finally, once the receive is over then we should close it and in this case server is
waiting once it receive a packet it will receive it and then finally, then or sub so, it will
close it. And so, this is the client side program a server side program.

(Refer Slide Time: 12:53)

The client side program in sender whenever sender sends something how sender can
sends it. Now the sender can sends it again DatagramSockets for the sender sides needs

1148
to be created. So, this is the ds object for the sender like and this is the String that
message that the sender wants to send it smalls message ended here and then InetAddress
is created ip because it is InetAddress is required and which machine as is the default
one.

So, in the same machine all the InetAddress will be by default it is 127.0.0.1 and then
DatagramPacket is basically for the message it basically converting the InetAddress, so,
this is the object it is there. And so, this basically DatagramPacket is created taking this
thing as a total information about the string it is here and the datagram packet is created
with the address to whom this DatagramPacket should be send here is the address of the
server we have already mentioned earlier and then datagram packet is ready to be sent.

And then here is the send method will send this DatagramPacket to the server basically
to this port at port at this actually. And then finally, once send is over it will basically
close the connection. So, this is a concept that sender and receiver. Here receiver being a
server we will receive a message from the sender; sender is the client here in this case
now here just I am going to give a demo of this program execution you will be able to
understand how it will work here. Here the first we have to start the receiver program
then you have to start the sender program means receiver should be there first; otherwise
if you start sender program first then sender we will say sending this, but there is nobody
to receive it, so, they are messaging will lost.

So, here as we see receiver, so, receiver receive this message welcome to NPTEL this is
basically the windows which is running the receiver socket and this is the window which
is running the server socket. So, in the server socket we just run the server or Sender
actually and then Sender sends this document message as you know welcome to NPTEL
like and it goes to the receiver, receiver received it and then print it. So, this is the idea
about using DatagramPacket EDP protocol here datagram packet.

1149
(Refer Slide Time: 15:11)

Now, our next example here this is the second version of this protocol here basically
implementation of client server mechanism, but here the idea about is that. So, is a dialog
message within this. So, it is a dialog message; that means, the same UDP protocol that
we have discussed earlier, the difference here is that the communication we will just in a
chatting manner; that means, first server socket program we will always be there to listen
to the client. And, then client we will send some message server we will receive this
message and then server again send some message to the client, client will receive it and
this dialog may continue whatever the things until server or any client send a stop
message for that.

So, this is the program consulate is here and you see this is the implementation of this
one all these import section is mandatory java dot net and other things in input output for
a streaming and everything it is there all those things is obvious. And this program as
you see ds is basically the socket I am now discussing about server side program. So, ds
is the socket for the server and here is basically port number is 123 port number is this
one right.

And then this is what is called the 123 is the port number right, here yeah this is the port
number and this is the size of the maximum buffer that it can handle actually. So, it is a
byte this is a basically temporary buffer we can say is an array of stream basically and

1150
then DatagramPacket DpReceived this is we say we create a DatagramPacket because
we have to use the UDP.

So, datagram packet we have declared a datagram packet name the DpReceive and then
DpReceive object is created that mean receive if we receive some message for receive is
basically the content that needs to be received from a distance machine and the length of
the packets actually and then ds dot receive is basically we have to receive if it receives
any packet there.

So, this is basically the method which is basically in a constant watching and then
whenever its receive a packet it will basically get this one. Once this packet is received
and then you can send the prompt message that client and what are the message that is
received is basically printed there; if data received to ok. So, if there is an message they
by; that means, it will say that this is our tongue I mean communication is I mean over
and then it will close the message.

So, this is the server side program, similarly there is a ok. So, let us go to the yeah fine.
So, this is the client side program similar to this.

(Refer Slide Time: 18:13)

In this case as you see here I want another socket client socket is created and this client
socket is basically read the continuous steaming from the keyboard like we whatever it is
type it from the keyboard it will read it this is the Scanner class is created here. The

1151
Scanner class is basically reading some input from the keyboard standard input and here
is the socket that we have created datagram sockets and then this is the ip address of this
thing. And this is the temporary buffer where the before sending this message you will
needs to be stored here and this is the basically portion of the communication.

So, this is the communication here and is basically. So, is the reading wants input from
the keyboard. So, this is the Scanner only and then its store in the buffer and then it
basically convert in the packet. So, this is the DpSend is the packet where the buffer the
packet will be created buffer will content all the message that the client wants to send it
to server.

(Refer Slide Time: 19:19)

And then finally, ds send the socket we will send the packet to the server and then it will
basically continue until this message by is there. So, if it types by then both server will
understand that client is no more interested to send any message and then the server also
will close its connection as well as this client also will close its connection.

So, it is basically the idea about these are server and client side program, this is the client
side program. Now here we are just see again two windows we have to first start the
server window fast. So, the server is ready to listen any request from the client and then
we will start the client server client program and another window will be there. So, two
windows actually we can write one here, and one here.

1152
(Refer Slide Time: 20:21)

Now, so, this is basically the client side program. So, this window is basically client
window and this is the server window, now here clients would send some message. So,
hi I just are typing the message hi nptel java program client from client.

Now I am sending this one yeah now the time message that whatever it is there we are
typing hi nptel yeah I am from client ok. Now you see we have typed hi nptel I am from
client then ok, server should send some right then it can send some more message like
nptel test write something testing server ok. So, it is there fine yeah. So, whatever the
message that we are typing we are sending it now if we type by then ok.

So, here in the client send by and exiting this is the one right way by which the server a
client can send some message in a continuous steaming manner it is not the dialogue
right ok. So, it is not the dialogue of course, the dialogue program will come there. So,
the both way the communication can be shown their using some TCP protocol we have
planned it anyway.

So, this is basically the message that, so, the machine can be done here. Now, let us
come to the second example our next example is basically to explain the TCPIP protocol
using again server sockets and then socket that we have discussed.

1153
(Refer Slide Time: 22:39)

So, server socket is for the server side programming and the socket classes for the client
side programming. Now as you see here this one ok. So, here as you create a ss is
basically the server side sockets and this is basically we have given on port number to
the socket program as 6666. So, it is given by us and this port number should be used by
the client if this client wants to communicate to the server again. And this basically is the
socket object is created; that means, a socket basically s one socket object is created only
if the server socket accepts the connection that if it is reaches to him.

So, here basically ss.accept is basically the request that can be attended by the server and
accepted. So, on socket object is created regarding to that one. So, this is basically server
socket is now ready and then socket also from the client is also accepted by the server it
is also ready. Once everything is ready yeah, so, once everything is ready then we have
to read the message that will be send by that will be send by client. So, it is basically we
have to create a data input stream dis and you see s means if we receive something from
the ss not get input stream.

So, get interesting method is basically one method it is there in the socket class itself
and this method we will read all the content that is there from the socket program sites
actually and then this will basically read as a string has we have given this one. So, it
will store as a string whatever the input stream that we can read converting the string
actually and then finally, this string will be printed on the screen and then the server

1154
socket will be we will closed. So, server socket if we run this program it will wait to
receive on request and it will accept the request and then you read the content from that
socket and then finally, print it.

(Refer Slide Time: 24:51)

So, this is about the server program in this case and as you have seen that we have use
the server socket and the socket. So, it basically follows the connection oriented protocol
namely TCP protocol and here is the client side program. So, for the client side program
is concerned here as you see we create a server a Socket for the client. So, this is and the
port number is the same as the previous one and then this is the output stream that you
have created because you have to send something.

So, gateOutputStream method is basically we will create a stream with the string that is
there. So, here d out right UTP Hello Server this is the string actually the message will be
converted into output form and then output stream will be maintained. So, that the steam
will propagate I will send to the server and finally, it will close. So, server is closed that
is all this is a message here is basically very similar to the UDP protocol where server
sends a message to the client and then client printed it.

Whether it is a continuous manner or is it just only one chat whatever it is there. So, in
this case also it is write one chat is their server and client both are ready in to windows
and then client send some message the message is here Hello Server and the message is
received by the server and then printed it that is all.

1155
(Refer Slide Time: 26:21)

Now, the next example is basically dialogue, this is more interesting program on and
here the dialogue between the 2 sockets; one is ServerSocket another is a client socket
and then client will send some message server will received server will print it then it
will sent to the client, client will print it then it will send another message, the
communication may continue until both the party may want for this. So, there will be
some stopping criteria say stop from stop message from both sides then both party will
understand that chat is over.

So, here is the example very similar to the previous one only absolute there is no
difference as you see here this is the ServerSocket the port number of the server program
and this is basically accept to the sockets right so; that means, if it accepts then a socket
object will be a established a connection from the server to that a Sockets one.

And then this is basically Input; that means, reading stream from the distance machine I
mean from the other Sockets and then Outputting; that means, if the server wants to send
something then it basically outputting. And here is basically flow that it will display the
content and this content will continue until there is a stopping criteria reach there is a
stop; that means, if it miss receive a message stop then this will basically close and then
this is the server side one.

1156
(Refer Slide Time: 27:41)

Similarly, there is a client side program as you see here the client side program these are
the socket that we have created the post port number this one and this is basically in the
same machine. So, we have to tell that this is the localhost. If we say explicitly specify
the ip address or some host name then; obviously, it will go to that distance that is the
only difference. So, in this case the localhost means in the same machine, but from the 2
windows that is how you have used it and then rest of the things is very similar to there
we have to define the data input stream; that means, the reading from the server side any
message and then output is basically sending some message to the server using TCP
protocol.

And here is that basically if the client received any message then how they will print it
how they process it. So, this is the continuous manner means both the party will continue
their dialogue till there is a stop from both sides or from anyone sides like. So, this is the
example now we can give an example. So, that we can see we will type some message
from the client it will go to the server, server we will receive it server we will send some
message.

1157
(Refer Slide Time: 28:47)

It will come to the client, client will again receive it and then client will type something
like this. So, now, here from the server side ok. So, server and client both are now ready
now here from the; so, we are just sending from the client side hello server, hi server
end. So, here you see client says hi server, now either from the client or server we can
write something now in the client hi how are you; how are you I am sending this
message now is go to I am fine ok. So, its come to this I am fine and then if we come
here in the client or server then buy or stop.

So, now we will see this will go there. So, client server say stop and then yeah. So,
anyway so, this top basically message received from either server or client or from both
basically close the communication it is there. So, this is the idea about the dialogue
message. Now so, and then remote communication is basically the same thing only the
thing is that in so, localhost we have to mention the ip address explicitly.

1158
(Refer Slide Time: 30:05)

Now, I will quickly come to the concurrent what is called the server let us go to the
concurrent server. And, here is basically here as the distance meeting is not possible here
to give a demo we will give basically in the same machine I am giving I detail program
you can have it from my sites you can get the program and you can run it I do not want
to discuss about the detail program I will only give the demo of this execution.

So, here the idea is that one server program is there I can say the concurrent server it is
basically thread implementation of the server which is be difficult which I have
discussed in our theory class. And then here we can plan what are 2 clients that more
than two clients also can be possible 2 clients for this 2 windows actually we have to do
it. So, there are 2 windows that we have mention here. So, they are total altogether three
windows one windows for the server and another windows for another two windows is
for the client here now as you see here ok.

So, as you see here. So, this is basically the server window and this is the client 1
window and this is the client 2 window. Now so, all programs are running so, server is
concurrent here in that because if the message comes for any one client it will response
to that one. So now, I am typing something from the date about yeah, so, client is now
communicating in ok.

So, here basically so, client basically give the date, so, date has been printed then it
basically ask that what do you want then whatever it is there right time I can say right

1159
time. Now here basically the idea is that client 2 basically asking the time now all these
response is coming from the server itself right. So, server is replying that it asks the date,
this is ask the time and they are receiving this one and this is a message actually it is that
ok.

So, here what I can say is that client is basically responding to any request from any
clients and then is basically the input is input to the server is basically the request from
the client regarding any information and then it receives and then printed that is all. So,
this way we can see that these are concurrent program is there and details of the program
that you can have it from the program exact details from the slide discussion as well as
from my sites itself. We can download it and then you can run and you can try to
understand how it works and you should its practice it then you can understand much
more about it ok.

Thank you very much.

1160
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 50
JDBC – I

Now, we shall start learning about JDBC. The full form of the JDBC is Java Database
Connectivity and these concepts will be covered in 6 sessions including today. So, first,
we will learn about actually so, far the JDBC is concerned there are three things to be
learned. First of all the database management system and then how the database
management system can be connected. And, this itself is called the JDBC driver and then
finally, the java application which basically will help a programmer to connect a
database from the application as an endpoint.

So, three things are there so, for the database management system is concerned there are
many tools many packages are known. In this course, we will cover one system which
basically helps a programmer to maintain a database is called the MySQL. So, we will
discuss the MySQL and the MySQL is a database management system and then we will
discuss about how these MySQL can be installed. If you are new to this MySQL then all
this information is highly essential for your learning. So, I do not know exactly whether
you are familiar with SQL or MySQL or rather relational database management system
anyone.

Anyway so, considering that you do not have any background knowledge about the
database management system handling. So, I will take a quick tour of the SQL based
database management system which is a very popular one is MySQL. So, in this session,
we will try to learn about how the MySQL can be installed. And then finally, we will see
exactly using this MySQL if once installs in your machine successfully then how we can
manage the database management system related to a task. Namely, how we can create a
database management database, how we can create a table under a database and then
how you can accomplish different operations to the database.

1161
(Refer Slide Time: 02:40)

Now so, first what exactly the MySQL it is. So, it is a very popular software usually you
know for the database management system handling one language has been provided. It
is very popular and a standard language it is called the Structured Query Language. We
usually call this language as a fourth-generation language, if we set C, C++, Java they
are the third generation language. The language of course, but the thing is that it follows
a certain syntax that is why it is sometimes it is called the language, but truly SQL is not
a language like Java, C, C++.

Anyway, SQL programming whatever it is there we can do it in English like syntax


actually. And it is basically a de facto standard nowadays; every database management
system engineer prefers the SQL based system. And, SQL base system is basically
followed there are many types of database management systems as relational database
management system, object-oriented database management systems; SQL is in fact, a
relational database management system. Now, regarding the relational database
management system, we will discuss a few things about it, a few salient points about
this.

Now, the SQL is basically is very simple and it is easy to use and that is why it is fourth-
generation language; actually that the difference between 3 GL and 4 GL. Third
generation and fourth generation languages are that third-generation language is
basically how to do concept; that means if you want to solve a certain problem how this

1162
problem can be solved. Then we have to write a details about it, but whereas, as the
fourth generation language, it is what to do. Just you tell that what you want to have then
automatically the SQL processor will take care about your what aspects and then solve
the problem. You do not have to write so, many details about the programming. So, that
is why SQL is basically a lightweight concept.

(Refer Slide Time: 04:39)

Now, using this SQL we can do many things, that we will be going to discuss and
another thing is that whatever the syntax that you can write that is basically in English of
course. And you know in English, there are two types of characters: lower case and
upper case. SQL does not distinguish whether you have typed in lower case and upper
case; that means it is case insensitive.

1163
(Refer Slide Time: 05:02)

Now, SQL has many advantageous and there are many tools that basically leverage the
concept of SQL. And, as I know the SQL is structured query language that is what we
have learned in the last slides. The MySQL is a specific application that is a tool which
basically developed by Monty Widenius and it is basically My, My is his daughter's
name. So, that is why MySQL he gave the name about his fond daughter. So, MySQL so,
it is not that MySQL means it is mine SQL is not like that and then it is basically the
SQL can be installed in your stand-alone machine like PC, laptop whatever it is here.

And, then once you installed it then you can maintain your database very easily. And as
you know it provides the structured query language and structure query language become
a de facto standard. This means that you can test it, you can use it, you can solve any
problems and then once you have done it using MySQL then finally, you can deploy to
any other systems which basically have an interface about the SQL. So, that is is the
beauty of these things. So, MySQL is initially developed, distributed and supported by
Oracle corporation. As you know Oracle is a joint player in the field of database
management system. Now, I will first quickly tell about how MySQL can be installed in
your machine.

1164
(Refer Slide Time: 06:37)

Now, there are many ways the install can the MySQL can be accessed from different
sources; I will discuss about the installation of MySQL in Windows environment.
However, the basic steps and procedures are very similar to any other environment like
macOS or Linux.

(Refer Slide Time: 06:55)

Now, you can download a very go-to resource of the SQL is basically contains many
things, if you want to have an Apache server or if you want to develop something in
PHP. PHP is one another sort of programming language for web programming it is called

1165
the Hypertext Pre-processor. And, the MySQL they are basically bundled together and
there are many sources for which the for example, here XAMPP, WAMP Server
etcetera. So, all those things you can download from that link which I have given for
XAMPP for Windows, I have given the links similarly for WAMP for windows also the
second link you can follow.

So, these are the well-known link and definitely, this is the free source actually; you do
not have to pay anything, you can download it is freely open source.

(Refer Slide Time: 07:47)

Now, I am telling you how the other source that you can follow to download your
MySQL software. So, if there is a link as I have given here, dev mysql.com downloads.
So, from this link you can go and in this link, you can find MySQL community server.
So, you just click this link then it will face to you, it will align to you in the MySQL
community server. You open this link and then finally, you can find there are many what
is called the software available for freely downloadable. And, out of which we have to
select without installation and is an archive version.

And, then directly also you can follow the link on which you can download the software.
I have mentioned here for the software and for the 64 bits machine, if we have the 64-bit
machine then it easier. And, the latest version I have mentioned here as MySQL 8.0 0.13
this is the current version. So, you can download it and if it is changing the version you
can again download the newer version and you can re-install it whatever it is there. So,

1166
this is the kind version that you can and this will be download as a zip file.

(Refer Slide Time: 08:58)

So, you have to unzip this file. So, what is the idea about is that where you want to install
that you have to decide. So, if you suppose you want to install in C drive and under the
name of MySQL. So, then you should extract the file; I mean, the zip file that you have
downloaded to extract all the files it is there; I mean unzip the files actually into the C
drive. And, then you should rename the folder otherwise if you directly start installing
then it will take the same name actually here MySQL version and then Window 32 for
example, instead of Windows MySQL 8.0.13 then Window 64. So, you can just rename
this file to MySQL rename this folder to MySQL. Then MySQL can be however,
MySQL can be installed anywhere, but the basic steps are same.

1167
(Refer Slide Time: 09:50)

So, now you have to place the folder on another drive to make backups and reinstalls
easier; actually, as you know MySQL maintains a database repository. So, data
repository for which you have to create one directory separately for you; by default, it
should be the directory in the same as the MySQL is installed. So, better is that the
directory can be maintained in some other drive for example, in D drive. So, the default
name is data that you have to do you should not change it. For example, here I have sent
is that D colon D data is the directory drive where we want to maintain all the data
repository under MySQL server.

And so, we can copy all the contents which are there once after in the folder that is the
MySQL you can move to that D data. So, there are some that system file is there, you
just move all the system file into the newly created directory, that you have create that
we have just now done in the D drive and then you have two folders. So, you should
remove one folder. So, C then MySQL data that folder should be removed. So, it should
have only one existence.

1168
(Refer Slide Time: 11:11)

So, this will complete the installation of the MySQL and then there is a little bit
configuration it needs to be done; for this configuration, there is a file, it is called my ini
file. So, it is an initiation file that you can find the MySQL folder. So, you just using any
editor let us say WordPad or Notepad you just type this contents. In this my ini file and
then it will basically complete the my ini file. So, just typing this file and save this file
into the MySQL directly it is there.

(Refer Slide Time: 11:56)

So, this is basically the configuration there are few more configuration also you have to

1169
consider ok. So, there are few more configuration is required, here I have mentioned
exactly what are the configure and you should consider. The thing is that, if you want to;
I mean, MySQL server is now ready to run actually. And, then you can run this by first
time if you want to run it, then you should try this command actually C colon MySQL
bin mysql.exe. So, this is basically to run the MySQL server first time. And, for this
thing you just go to the Start, Run command and then following the command also you
can do it for the initialization.

And then here the password you they will ask it so, you can give some password for
example, here this is the password that you can set and then root is the password like. So,
you can give the root password or guess password whatever it is there and then you can
also change the password at a later stage. So, that option is there I will tell you exactly
how the password can be changed at a later stage. So, these are the things that you should
do, first of all, ini file and then you have to run the SQL server first time and then change
the password there.

(Refer Slide Time: 13:12)

So, these are the ones you do these things then your next step is basically to set the
classpath. So, that you can run this program from any other directory like.

1170
(Refer Slide Time: 13:21)

So, here is basically how the how you can do this. So, this is basically calling you to
have to create a Windows service. In order to do the Window service from the command
prompt, you have to go again. And, then in the command prompt, you have to write this
command cd MySQL Bin and then MySQL install. And, that also can be done in this
way control panel you have to go in this environment. And, then there is an
administrative tool we have to select it and then services and double click you can under
the service you see MySQL is already available. So, you have to double click and under
the double click is the startup type it is basically select the automatic.

So, this will basically ensure that you can run this MySQL server as soon as you boot the
system; that means, you just on the system automatically MySQL is ready to serve you.
Then you have to go to the command from MySQL and then you can use it whatever the
way you want to use it. So, these are the different procedures that are very much
necessary so far the setting up of the MySQL service is concerned. Now, I will discuss
about how the MySQL statements can be, there are what are the SQL statements exactly.
So, that you can execute from the MySQL server.

1171
(Refer Slide Time: 14:46)

Now, there are different statement and the first statement that you can do is basically
show a statement. I can say it is the show command, it basically you can type in either
small letter or capital letter it is not an issue. And then show database; that means if this
is the full command actually; it will basically tell you what is the database which is
available under the MySQL at the moment. So, is basically this is the command, I am
just telling you what are the different command that you should learn as the first time ok.
So, this is a first command that you can think about it and then the next command that
you can think about the create database.

So, how you can create a database as you see here, the create database is the command
and then you have to give the name of your database. For example, I have given the
name of the databases test, that means every database should be uniquely identified by a
name; unique name. And, that name is essential and every user should know about what
exactly the database. This implies that MySQL server can maintain many databases in
the same server or in the same machine. So, that is why the different and under a
database there are a lot of tables that will be there. So, that is what you have to first
create a database and the mean is this.

Now, suppose already there is a database which has the same name then definitely it will
report an error. So, that you that database creation is not successful, please try with some
different name. So, this is an idea about the second command which basically how we

1172
can create the database of your own and then finally, you have to initialize the test. So,
for these things, the command is use command. So, use and then give the name of the
database that means, this database is, therefore, now active for your work. So, these are
the three commands that are very beginning. So, if you want to create a database of your
own which is new and then you can just do it and then finally, activate it by using the use
command.

(Refer Slide Time: 16:58)

And then there are many other commands which are basically useful. So, you have so far
created a database which is a name and under this database, we want to maintain tables.
So, first I will tell you how a table can be created. Now, as you know a table basically
looks like this, a table has its own name. So, there should be a name and there will be
some columns, these are columns are call attributes. So, this is the attributes and then
each row will contain a record. So, each row will contain a record. Now so, attributes
and then table name are the first thing that you should ensure that whenever you have to
create a table.

And, this command basically creates a table is a command that basically tell you exactly
what is the way you can create a table of your own. So, the column is that you have to
first give the table name. So, this is the command create table and this is the table name
that you have to specify. So, my table name may be saying NPTEL data like this and
whatever it is there and then all the column name, say suppose this is the one column

1173
name. So, maybe say roll number roll and this is another column say a name and this is
another column say marks and this is the another column say grade and this is our total
whatever it is there so, these are the column name. As you see here I am in the process of
creating one table and the name of the table, in this case, is JavaCourse and I created four
columns here Roll, Name, Marks and Grades.

So Roll, Name, Marks, and Grade so, five columns are not there. And then we have to
specify for each attributes what is its type. As you see here for the Roll column that mean
attributes type is Integer and I mention that this is the primary key, if you know one key
should be unique all values then this is the primary key. So, this column will contents all
records having the unique values unit columns. So, all values are unique like so, this is
called the primary key and then the Name is basically is a character is a Varchar is a
syntax for that. So, that SQL can understand about it and 30 is basically maximum string.

That means, you can store a name of a maximum 30 characters in this column so, name.
And then, Marks is again Integer and it is not null; that means, if you enter any null then
you will not be able to null it. And the primary key is also not null; that means, no record
you can enter for which this element has the null value, null value means no value ok.
So, integer Mark’s is also should be a not you have discussed it here and Grade is also a
string of two characters. So, this way we define one table and this is the command, if
issue this command to SQL server then SQL server will create a table under the active
database which is the test in this case. So, this completes how the database can be
created.

1174
(Refer Slide Time: 20:05)

And then, if you want to know exactly the database that you have created what is its
description. So, the description can be obtained by the command is called a DESC, it is
basically the short form SQL sometimes allowed to give you short-form describe; short
form of describing statement. Now, if you type this command describe followed by the
table name, in this case, the table name is JavaCourse then you will be able to see exactly
which is the structure of the table. So, this is the command here desc then database table
name is JavaCourse and then it basically gives the structure.

So, as you see here so, it basically what are the fields and then type it is there. So, in this
case, the fields also call the attributes there are four and then the type is int. So, basically
11 digits can be there, Marks also integer 11 digits can be there and the Name is string 30
and varchar is 2 30 and here you see null or not null. So, this means no null value is there
with no null value; however, this can have null value also.

And then finally, you see whether there is any is a primary key or not. As we have
mentioned this is a primary key, this is the primary key and other is nothing is
determined non-primary key and then default is basically null. So, initially whenever you
create the table that time there is no default value, you can also while you are creating
some default value say 0 0 0 all this thing can be included there also.

So, this is the structure of the database that just now we have created and after creating
the data table as we have seen it, you can see the structure of the database. And, using

1175
this also what are the different type of fields also can be created, we will discuss shortly
about this different type of file that can be possible using SQL.

(Refer Slide Time: 21:56)

And the next is that your table; your database is ready, under these database a table is
ready, but at this moment the table is empty. Now, it is your task to enter the data into
the table. Now, the data into the table can be inserted by another command in SQL it is
called the INSERT, INSERT INTO. Then this is basically table name, for example,
JavaCourse and then what are the values that you want to enter in each rows. So, here
Value1, Value2., ., Value n provided that there is n number of fields are there. So, this is
the command INSERT INTO is basically default in setting record into a table.

Now, if the table in contents already some record, then insert the command will insert
into the appending mode. So, whatever the records are there it will be there and then it
will start appending the record at the end of the existing records. So, this the statement as
we have seen here with this ok, we have issued four insert common one by one. First
insert into JavaCourse values 01 Debasish 75 A, as you see here it is basically like; insert
into JavaCourse values 02 Nilanjan 85 EX. So, it is the second record and this way this is
the third record and this is the fourth record that we have inserted.

So, we have seen exactly four insert command as have been issued to insert four records
successfully one after another. If you again type another click insert command so, the
next record will come here and so on. So, this is the simple way the insert command can

1176
be issued to the SQL system and your SQL will insert one by one.

(Refer Slide Time: 23:47)

And here is the UPDATE command, if you want to change some values in a particular
record that can be done using the UPDATE command. So, here the command syntax is
UPDATE then table name and then SET. So, these are the command syntax and then
table name in for example, in this case, JavaCourse and then which column that you have
to change it. So, column name Value1 Value2; that means, these are the new value that
you have to changed it. And, then this is the condition for which record that you want to
tell. If you where star then for all it will be there if we instead of the star actually the
short form that was star means all or where all otherwise you column name equals to
Value1.

That means, it will change those columns whose column name is Name1 is Value1. This
is basically condition; that means, if you want to update particular records then which
record should be updated that has to be mentioned here. Now, here is an example if you
see there is a two update command we have done it here; update this is the table name set
Name Debasish that means we want to update this table at the Name field by Debasis
where Name is Debasish. That means, this is the condition, this means that earlier table
that we have created, if you see this entry was d e b a s i s h and then by means of this
update command we will be able to change this one. So, this table basically is shown
after the update I mean first command is executed.

1177
Now, let us see the second command another command update again, the same table
name set Marks 85 Grade Ex where Name equals to Debasis. So, after this one if this
Debasis earlier it was 65 a, now it becomes 85 Ex. As you see here update command will
basically help you to change the values in a records, satisfying a certain condition that
we have there.

(Refer Slide Time: 25:44)

And so, this is the update and then finally, SELECT is very popular one command; if
you want to read some records from the existing table in a database then the select
command is there. So, a select command basically stands because syntax is SELECT
FROM WHERE. So, this is the command syntax that you have to remember, SELECT
then you can select all columns, then select star FROM the which table we have to read,
we have to mention. And, if you want to select some records which satisfy certain
particular condition then you can mention this one. So, this is basically the way by the
select command can be executed.

Now, let us have some command execution on the existing database that we have just
now created namely the JavaCourse. And, there is a select star from JavaCourse, this
means that we want to select all the fields from the table JavaCourse and there is no
condition that means, it will basically select all. So, no condition needs to be satisfied. If
you exit this command then you will be able to see this kind of database is there. Now if
you want to run the next command, next command says suppose select name roll from

1178
JavaCourse So, this is the command that we have select name roll that means only two
fields from the table. So, this basically will be the output once you execute this
command.

You can see this output on your console, in your console the display screen all these
tables will look like in this table form. And then next commands, let see another
command on the same database like a select star; select star means all field from
JavaCourse where marks are greater than 80. That means, it will select all the fields the
marks are greater than 80; that means, in this table as you know this is the initial table
only these two records qualify for this statement. So, it will basically display this output
and next another column; you see another command that is the select star from as we see
the command again select star from JavaCourse where name like this one. So, a name
like means it is basically whatever the other things are there, only there should be at least
two-three characters like j e e.

Now, this is the condition it is there, where name like is another syntax for, there are
many other selects common is syntax and compositions are there. I am giving you the
basic concept at this stage only, you can follow any SQL book. So, that you can learn
many other command formation from that under the select there are many other
command formation actually. And, then nested select although select within select so,
many other things are there that I just want to skip at the moment. Now, if you execute
this command then it may not satisfy any record that may not satisfy this condition. In
that case, it will display the blank table, as you see here no values, in any records which
have the name having any three characters say j double e. So, it will return a null table,
blank table in this case.

Now, our next command that we are going to is this select star from JavaCourse order by
marks. Now, we can understand what is the meaning; meaning is very simple in English.
So, you can understand if I do not say anything also you will be able to order by means it
will display the table, but according to by default is according to the ascending order.
Otherwise order by marks you can write descending also it can be there, by default it is
an ascending order. As we see this basically select the entire, I mean display the entire
table and when the marks are basically in the ascending order of the marks is there. So,
this is the few commands that you can think about how the table can be created anyway.

1179
(Refer Slide Time: 29:58)

So, these are the few command that we have discussed about. So, for the select is
concerned and next we will discuss about another very important command DELETE.
So, using this command, if you want to delete any record that you could that. So, this is
the command syntax is DELETE FROM, WHERE. So, delete means it is the table name
that you have to specify and you can delete entire records, if it satisfies certain
conditions. So, we have two conditions like, all the conditions as you like say name
equals to say d e b a s i s whatever it is they're like this one so, it will delete that record.

Now, let us see one example so, that you can understand how the delete command can be
executed for the database, that we have created namely JavaCourse under the test table;
JavaCourse under the database test. Now, this the one example that deletes from
JavaCourse where a mark is less than 66; you can understand it will delete all the records
which have to satisfy this condition. As you see there are few records as the marks 65
those have been deleted like this one. So, after the successful execution of this command,
it will give output like this. And, you note one thing one is deleted; that means, it is
physically removed ever no logical deletion takes place.

So, delete command is very dangerous in that sense that you should issue this command,
once you delete it then you will not be able to recover it later on ok. So, this is the delete
commands and then there is another command also delete from JavaCourse then you can
understand this means it will delete all the records from your table.

1180
(Refer Slide Time: 31:34)

Now, DROP TABLE is another command which basically to delete the entire table. So,
drop table is also another very dangerous command of course, and as you need syntax is
a very simple drop table, this is the command and then you have to give the table name
which you want to delete it. so here. Now, as we see the example a drop table
JavaCourse this mean that whatever the records it is there, it will be deleted forever.
And, then if you again select start from the database it will say that database or table
does not exist; this kind of commands it is there if you want to select it there.

(Refer Slide Time: 32:16)

1181
So, we have to just learned about the setting up of MySQL and also we have learned
about a few important and 1frequently occurred SQL statements. I hope you have
understood, but this is just at the beginning stage; if you run with many other database
creations, many other tables you can create. And, then for each table, you can run just
you can just come into the playing mode like. So, play with this one right, but you have
to install the MySQL first, MySQL installation is not a big job.

In our demonstration 1, we will give a thorough step of how the MySQL can be installed
in your machine, At that time if you have your own laptop you can write attain this
session using your laptop and you can follow it. So, everything is very simple, but before
that you can install all the software from the net and then start our procedures seeing our
demonstration. So, MySQL should be installed beforehand you know so, that you can
practice it about it. In our next session, we will discuss about JDBC driver regarding and
then we will discuss about it and then; obviously, MySQL is a structured language.

So, unstructured data cannot be maintained by this one and then how to take a backup of
MySQL data ok. Those things you can find if you give this search into the net, the net
will give you a lot of solutions for keeping backup data. Now, in your backup data as you
see say suppose you have to install a MySQL with a newer version, but you do not want
to lose your data. So, that is why your data should be stored in a separate drive that we
have done here D. So, D drive can be copied anywhere and then if you install again
newer version and you're in setting, if you mention that your data is that right so, that
data can be accessible always.

So, absolutely no problem, if there is a problem or the MySQL server is corrupted or


there is a breakdown in your machine you will not lose any data there; provided that you
have keep you kept the backup all the times you have there. So, database security is not
an issue so far the MySQL is concerned there. And, many systems actually usually
follow several back-ups of the same system, those are the different issue that is for the
more reliable database management if you want to have it. So, thank you we will come
to the next session where, we will discuss about JDBC driver.

Thank you very much.

1182
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 51
JDBC - II

As we have already stated there, there are three things, so far the JDBC related java
programming is concerned, the first thing is that the server which basically includes the
database; that is the MySQL server we have covered, and the next thing is basically
JDBC driver. So, this basically driver is a connector, connector between your program,
your program written in java application to the database which is mentioned. So, there is
a connector.

Now we are going to discuss about JDBC as a connector, so that it will connect a java
programmer to the database. Now in the last examples what we have discussed about is a
direct, there is no connection from the same host machine, where you have installed the
MySQL, from there from the same console you have executed, but now we will basically
see how from the java application in, as an end point we can communicate to the MySQL
server remotely. So, this concept is called the java database connectivity.

(Refer Slide Time: 01:21)

Now let us see exactly concept first. So, as I told you java database connectivity insures
you to have the connection from your program. This is your java application, you can

1183
write whatever the program it is there using any API you can use it here. So, it basically
is a program actually that you. Now your database can be stored here maybe Oracle or
MySQL or some other system database is there, it is there. Now here is the java database
connectivity JDBC driver, it basically connect your application to this database. So, this
connection is a basically, is a connector line. Now for this connection you can in you
can, ok fine. So, for the JDBC connections related API these concern, all those things are
available in a package in java and this is a bundle package like API, so java dot sql.
Anyway how to do this connection and everything to through JDBC and everything. So,
basically JDBC related all the commands is basically, I mean implementation is available
in java.sql. We will discuss about java.sql package later on.

Now, we will discuss about only the JDBC connectivity and regarding the JDBC driver.
Now the driver that you can install from the driver is a java.sql.Driver is a one package it
is there. So, using this package, basically there are two classes DriverManager and
Driver, three classes rather DriverManager, Driver and then this is the connection. So,
these are the three things that you can have from this java.sql.Package actually. So, these
three classes are already defined there, we will discuss about all these classes later on.
Anyhow in order to use the JDBC from your program definitely java.sql should be
imported in this application and then you have to create the object of these driver
manager, driver and then connection. So, this will basically help you from your program
side how the JDBC can be connected. Once the JDBC is connected with your application
then JDBC will take care about the execution of any SQL statement that you used from
your program there, and it will send this statement go to the server, server will execute
and then result will be returned to the JDBC. JDBC interns return the result to your
program, and then from the program you can have the result and process it and then you
can get everything.

So, here basically directly if you can do it, but here through JDBC you can this one. And
one important thing is that, this is basically is an object oriented concept, object oriented,
paradigms it is there. Wherever this database which you usually use relational database.
So, it is a relational concept, so paradigm is different. There may be some object oriented
database also there, but usually a SQL follow the relational database, and JDBC is a
unique one system we can say, who is basically match between the object oriented

1184
concept to the relational concept. So, this is a very unique one features that the JDBC
profile has and very useful also for any java programmers.

(Refer Slide Time: 04:39)

Anyway, so this is basically the about the JDBC database connectivity, and as you know
JDBC it supports the SQL related query execution. So, JDBC in fact, is a SQL level API
which is very popular for handling RDBMS; that means, Relational Database
Management System.

Now, there are some what is called the driver also available, who is basically allowed to
handle with some other type of database management system also, but initially and till
time right the SQL related RDBMS is very popular there. And there are many vendor
those basically help you to maintain your database, as you have mentioned here for
example, OracleDB from the oracle. MySQL is basically from the oracle itself, but it is a
smaller version one, and OracleDB is very for the business purpose, for big business in
the organization if they want to use it for this one and MySQL is for the small enterprises
for organization.

Other than this one, one more popular is called the Sybase and there is also a MSSQL
Microsoft from and that is also available these are the basically database, but in our, in
this session, in this discussion we have used a MySQL. Basically syntax and everything
are the same, you do not bother about whether it is OracleDB or MySQL or Sybase or
MSSQL absolutely they are very transparent. You do not have to think about anything

1185
which database management system has been maintained, but JDBC will be able to
contact or interact any database vendor; OracleDB, MySQL, Sybase or whatever it is
there, but here; obviously, for different vendor database, the JDBC driver is also
different.

So, usually every vendor for example OracleDB create a JDBC driver for you if you
want to use it. Similarly MySQL also create another JDBC driver for compatible to
MySQL. So, you have to install that JDBC driver for which you want to have a
connection. So, I will tell you exactly how the MySQL related JDBC driver can be
installed in our machine.

(Refer Slide Time: 06:45)

Now relational database, as we already know that it is basically a relation database


means is a table, a table contains a number of fields and also it contains a number of
records, and that is why it is called the table. So, relational database means called tabular
database, but it is called the relation, because the processing of the different entities or
the records or the entire tables or many tables based on some mathematical formulation.
This mathematical formulation is called relational algebra, as the entire database can be
processed using the mathematics mathematical syntax, called the mathematical
operations, relational algebra this is why this is called the relational database
management system, and that is why RDBMS.

1186
(Refer Slide Time: 07:38)

Now, so for the database driver is concerned which I was just talking about. So, if run
your SQL statement from your application, as it will be run remotely to a server through
JDBC driver and for different JDBC driver the different program is there. So, the
different database management system; the different program is there as we see here.

So, this is basically java application any one application from anyone program right, so
JDBC driver. Now as I say JDBC driver you have to install if you want to connect oracle
for oracle compatible this one. So, from the oracle source only you can get it, install it.
Similarly Sybase also you can get it, install it, MySQL you can get it, install it. And then
this basically, so it will connect the database server and this is a Java application Java,
JDBC will connect one application to the database management system through JDBC,
that concept is basically, it is there, that is characteristic that you have to follow. I think it
is easy to understand.

Now in our discussion whatever we will follow we will refer to the JDBC driver related
to MySQL database server only. And the approach in fact, very similar to any other
database oracle or Sybase or MySQL absolute no difficulties, only you have to install
that appropriate driver in your system. The JDBC driver for different database is
different as I told you but you have to just install this one.

1187
(Refer Slide Time: 09:07)

Now JDBC is popular, because it can be executed anywhere from any system. So,
platform dependence independence is a very good issues, that mean as you know java
application is a platform independent, so absolutely you can run this program from any
system as you wish, and then it is a basically object relational mapping. I told you, so
java application is object oriented, whereas, database is relation oriented. So, there is a
good mapping for the JDBC and is a unique concept it is there. And network
independence, in which network you belongs, absolutely you do not have to bother about
it, JDBC driver itself will take care about all network related these things.

So, the network programming that we have learnt about, this is for the core related to
some other network protocol implementation. Whereas the database connectivity also the
through network only, because your remote server can be maintained in some distance
location, but JDBC will connect from your application to database server and both to and
fro connection. That means, if you; if the database server return some results, the results
will be collected by the JDBC driver and it will return to your application and vice versa.
So, this is the database independency is a very important. And database independency is
because, as I told you it is also applicable for relational database, but there are some
systems for which a, JDBC driver is also available which basically allow you to connect
it, for object oriented database or some other database management system.

1188
(Refer Slide Time: 10:37)

Now, they, as you have told you, so in order to use the JDBC, definitely you should
know SQL, because you have to fire the SQL related query statement through JDBC
driver. Now, I will just discuss quickly, that there are different type of JDBC driver. And
in this slide as you see, there are four different type of JDBC drivers are there.

(Refer Slide Time: 10:57)

So, the first type on driver is called the JDBC-ODBC bridge driver. So, it is basically
object oriented database corporation, is basically the idea about this JDBC driver is that,
so they can use any third party API; that means, not the java API. So, if these driver you

1189
access the third party API then it is called the type 1 JDBC driver, and usually no
network connection they support. So, if you install JDBC driver in your host machine,
and in same machine the third API is also installed, then you can use the database from
there.

So, it is not the, remote connection is not possible. And next is the type 2 JDBC driver
there are some Native-API, so you can develop your own API or already existing C, or C
plus plus libraries; if we use it then this driver can be the type 2 JDBC driver, so that
kind of driver is also available in the market. However, the same type 1 driver like this
also connect to the server in the same host, no network connection is possible.

On the other hand type 3 JDBC driver, it can consider any one type 1 or type 2; however,
connected through net. So, this is basically network connection is there. So, this driver
will connect the network, connect to the remote one host, that host can include the
JDBC. That kind of concept is there, so this is the type 3. And finally, type 4 JDBC
driver is a basically independent, it can be independently connect to the network and then
you can use it. So, this is basically is a good for remote server maintenance and other
issues are there.

So, whatever it is there, we will basically follow the type 4 JDBC driver in our
discussion. And as you see the type 1 is a bridge driver, it basically bridge from this java
API to other API like. Whereas API driver, the type 2 driver is a partially java driver and
then type three and type four is fully developed by java system only. So, they are the
hybrid actually you can say, these are the two hybrid JDBC driver actually. In some
situation if you want to have cross platform application then you can follow it.

1190
(Refer Slide Time: 13:24)

So, these are the driver that is there, and then Now, how the JDBC-ODBC work it is,
basically this is explained here, these are database as I told you, everything should be
installed in the same machine that is the client machine and if it is your job application
you can just in the same machine, host it and then the same machine also host the
database management system. So, this way it basically works there, but if this data; this
type of driver has certain pros and cons.

(Refer Slide Time: 13:51)

1191
Advantages is that it is easy to use and can be easily connected to any database, that is a
good advantage; however, its performance has an issue, because it, the performance
degraded because JDBC method call is converted into ODBC function call. So, is that
query execution is not so fast, and then the ODBC driver needs to be installed in the
same client machine. That means, both JDBC and ODBC needs to be installed

(Refer Slide Time: 14:18)

And then next is type 2 native-API; that means, as I told you, you can connect to your
own API or some already existing API that those are there in C, C++ like. So, here is a
same thing just like type 2, in the client machine you have to install all these. So, JDBC
API should be installed and then that the database also needs to be installed, but only it
will connect other than other database, it will connect to the native or C, C ++API is
there and this is your application. So, these are different facilities of service that it can
give to you.

1192
(Refer Slide Time: 14:55)

And our next example, and then it has some; obviously, advantage and disadvantage. It is
also again performance issue also it has, because it needs to be converted from your API
to other native API like, the native driver needs to be installed on each client machine as
the same issues it is there. The vendor library needs to be installed in the client machine
also, because JDBC driver also to be installed and native API is those you have to use it,
also needs to be installed in your same machine. So, these are the things are there in this
particular example

(Refer Slide Time: 15:32)

1193
And type 3 is basically network protocol. As you know type 3 database can be connected
through net, whether is a type 1 or type 2 it also can be connected, but usually it is type 1
independently, and here is the idea it is. So, basically these are the server site that can be
in a remote location, connected through the network. And then network protocol driver,
they are basically you will connect it, that needs to be installed in your machine of
course. And this basically the JDBC driver, JDBC driver we will follow what type of
network protocol that needs to be there. Actually JDBC driver itself include this protocol
bundle with this one.

So, you do not have to explicitly considered both the things will be there. Only in your
machine you have to install this JDBC driver. And then finally your application, java
application using your JDK and whatever it is there you install it. So, you can run your
java program and then get a connection through JDBC, JDBC will send the connection to
the database server, get the result, result will be return.

So, this is basically the type three. Type three is the most one sophisticated things it is
there; however, there is another type 4 database is also there, but now let us see what is
the issue, goodness good point and bad point.

(Refer Slide Time: 16:44)

So, for this type 3 is there. Here the no client side libraries required, because JDBC
driver is installed in your own machines only, only the JDBC driver and then your java
needs to be installed there. And disadvantage is the network support is required, because

1194
without network and communication you cannot connect to that, and it required for
database specific coding to be done in the middle tier. So, the database coaching means it
will already database JDBC will take care, but some coding effort is required time to
time. And final is a as it is related to network, so network protocol needs to be
compatible to your system.

(Refer Slide Time: 17:23)

Now, type 4 actually is an process to eliminate all those things is there, it is more
sophisticated than type 3 here.

So, here again database is in a remote location and thin driver it is basically called, which
basically take care about the network and then connectivity issues, between your JDBC
java application duo and it will do this thing. So, it is more sophisticated and as it is,
again few issues are there like say type 3 database issues are there

1195
(Refer Slide Time: 17:53)

Thin driver is required, as you know basically, and better performance than all the
drivers that you have considered is very fast, and no software is required at the client side
or server side as well as. And here the drivers basically, different drivers from the
different vendors are be installed. I think this is not also big issue we can do it. So, we
will consider the type 4 JDBC driver in our in our discussion. Anyway, so we have
learned about JDBC and JDBC characteristics,

(Refer Slide Time: 18:25)

1196
Architecture maybe two tier architecture, all the type 1, type 2, all these things are the
two tier architecture.

(Refer Slide Time: 18:34)

And then three tier architecture is also similarly type 3, type 4, JDBC driver are the three
tier architecture.

(Refer Slide Time: 18:44)

Now, let us see what exactly inside the JDBC is there. Now, so there are few steps
actually if you want to invoke the JDBC in your application. So, first you have to load a
JDBC driver that can be done from your program itself by making some classes which

1197
basically provides you to how to load a driver to your application, and then you have to
create a connection. There is again class facilities are there, and once it is connection is
there you have to connect to the data source, which database you want to connect it and
then you execute SQL statement, that way you have already explained during our
MySQL studies and then the result that you will receive you have to process the result
according to your own requirement. So, these are the five step procedure that we have to
follow and we will learn exactly all this five procedures, how it can be executed carried
out in our, from the java application

(Refer Slide Time: 19:32)

Now, so far the JDBC driver is concerned, we have to install this driver. This is the one
link I have given it for you, so you can go to this link and directly installed it, and this is
the most current version it is available. There is also other link is also available, from
here also you can download this, this JDBC driver that is in your case, that the type four
JDBC driver actually we have mentioned you. Once this installation, that that installation
is very stress for, you just download this one and double click it will automatically
installed in your machine. We have to then finally, set the CLASSPATH and all those
settings are minimum requirement that is required and then CLASSPATH setting.

1198
(Refer Slide Time: 20:10)

If you know a little bit system level administrative job in windows, you can do it
otherwise in our next demonstration, we will give you the details about how the
CLASSPATH can be set and then connecting to database I will come to there, how the
connector connection can be done.

(Refer Slide Time: 20:25)

Now, I told you that all the things can be possible from your application itself, so you
should follow some API. So, the API that is responsible for doing this thing is java.sql
API, that is a package. So, you have to import java.sql dot star; that means, this package

1199
contents the different classes as we have mentioned here; DriverManager, Driver,
Connection, Statement, ResultSet and SQLException. So, all these classes are enough, or
only few these are the sixdifferent class, libraries are there in your java.sql API.

So, learning all these class is basically sufficient to use it. So, we will try to learn all
these classes in our next, in this current session as well as in your next session, so that
how we can utilize this one. DriverManager is responsible for maintaining the driver and
driver is basically, the controlling the things, and then here basically the driver manager
statement, and DriverMmanager results its and then SQLException are the classes,
whereas Driver, Connection and Statement are the interface; that mean class facilities are
there and we have to use the interface to redefine your requirement actually, we will
discuss all these things.

(Refer Slide Time: 21:32)

Now so far the loading the JDBC driver is concerned from your program, you have to
issue this statement. So, from your java program if you execute this one, and here is
basically your type 4 driver, where it is basically it mention. So, you have to give this
one. And then these basically, your program will connect connect to the JDBC driver
automatically and then it will basically establish a connection, it is very simple. On the
other hand, if you want to connect the Oracle, this is the driver that loading procedure,
and if it is for the MySQL, this is a loading procedure. For the different what is called the
database management system, the different loading procedures are there. So, that

1200
information also we can have it from the vendor itself, so they will tell you that how to
load your JDBC driver to connect to that particular database is there.

(Refer Slide Time: 22:28)

And then final the Connection object is there. So, you have to create a connection object
as I told you, connection is a class, is an interface, which is already there in java.sql
package. And then use the DriverManager, this is the class one and there is a method
getConnection. Now, here is an few syntax that I have told you, so you have to create a
connection object. This is the connection object conn; initially it is null and then this is
basically userName “guest” and then password “guest”. Suppose, that the username and
password always, it should be specified. In our earlier discussion about MySQL, we have
given the username as root and password as root also. Otherwise, you can say it
whenever you install the system, that time you can give the username and password and
password can be changed also, anyway. So, suppose username and password are the two
objects; two string is “guest” and “guest” like you have just have it and then this is
basically url one string that basically in which machine your, I mean server is there. Here
is basically, if you see, your SQL server if is installed in this IP address then you have to
mention it, and then in which directory that you have to mention it and this is the name
of the database that you have to do it. For example, “test” is the database, it is installed in
this remote server whose IP address is there and this is basically the directive, where it is
stored there. So, this url actually the, for any connection, as you know in Java
networking we have told you, url is basically a specific location of a particular server

1201
where it is there. and once this url is already known then you have to create the
connection, the connection object is created here and then it can be instantiated by
calling this method, DriverManager. getConnection as I told you and passing these are
the three arguments url, userName, password.

So, this is the idea about how you can connect to your application to the remote server
using this statement. Now, here, so the idea it is, so, Java MySQL database is basically
name of the driver, where it is loaded and this basically, database server where the
location and finally, this is the name of the database, those three things are very
important. Now, again if you want to install your server in locally that is also possible.
Means, your JDBC driver and your application and the server, database server both are
in the same machine. Then here in this case you should write local host, that is all. So,
this will completes the idea about establishing a connection from your application to the
database server.

(Refer Slide Time: 25:13)

Now, so far the statement execution is concerned in JDBC, in java API; java.sql API.
There are one class; statement is there.

Now, this class has the three different predefined classes are there called the Statement,
reparedStatement, and CallableStatement. So, Statement is basically executing one
statement at a time. PreparedStatement is set of statement can be punched together to
these things one, and CallableStatement means; if you want to change the statement

1202
execution, when you are issuing this one. Anyway Statement and PreparedStatement, if
you want to execute one statement or multiple statement at a time.

(Refer Slide Time: 25:53)

Now, here is a simple example that we are going to discuss about, how we can execute
some SQL statement using our JDBC data connectivity already there from our program.
Now, in this program, we have to input these are the statement. So, Statement is an
object, is created. Object is the type of the class statement initially, it is null, so the object
is just defined. And then the connection, with the earlier discussion, if you create a
connection to this one so, connection, this is an object, connection object. And then the
CreateStatement is basically is instance, the statement object. So, this statement and
connection are very important in this case.

Now, once the statement object is created using this one successfully, if there is no error,
then you are free to execute any statement. All the statement you can type in English,
whether lowercase, uppercase, it is not an issue. Then there should be enclosed in double
quote. For example, I want to execute “show tables” or show databases, then I write
show databases or show tables within double quote. And then execute method can be
called for, thus for the statement object, so it will basically, so you and once this is there
in your control, all the database, all the tables which are there will be displayed into the
system. Similarly, another statement “insert into JavaCourse value” this one.

1203
So, as you have already learnt about how all this statement we have executed from the
same concept, but here from the Java application, it will go to the JDBC driver, JDBC
driver will send this statement to the database server, database server will execute it, and
then you can get the result also. So, this basically tell you how the different statement
can be executed from your JDBC, from your java application. There are many other
statement also like wise we can execute it.

(Refer Slide Time: 27:48)

Now there are; obviously, few more useful methods as we have used one execute
method. Like execute method there are some other method also there they are basically
same thing right, whether it return something or not, so executeQuery, executeUpdate,
Execute and getMaxRows. GetMaxiRows means, it will basically tell in a data that how
many method, how this statement if it is executed, how many methods, how many results
have been changed or updated like this one. On the other executeQuery it is basically
creates a data, what is called the return, it basically return a ResultSet actually, the
ResultSet regarding we will discuss in details. Basically if you execute a query it will
return some results. So, those results can be captured by one object call the return; object
of ResultSet class, and then it can be stored there and it basically executeUpdate, means
it is update it and then finally, return Boolean that means, whether true or false like this
one execute also execute a same way, but it is basically the different methods are there,
basically the same thing whatever it is there.

1204
Now, execute can be used without any result set. Whereas, these can be used with result
set or simple the report that report during the execution line. Anyways, so these are the
different statements that is possible for the statement object, and we will use in our demo
as well. In the next session also, we will discuss about, details about the programming, so
that how the results can be processed.

(Refer Slide Time: 29:25)

Now, this is an another example, called the PrepareStatement, as we see here, this
statement is basically we can create a QryString. It is basically statement “INSERT
INTO JavaCourse”. This is the one statement and that value actually, we have not
mentioned it here, but that value can be given it after this query string is prepared we can
push this value by means of prepare statement. So, prepare statement is another type of
statement.

So, basically pstmt, setInt and then 1, 1 means the first value with this value 12 , 2 means
the second value with this one “ABC”, 3 means the 3 value 64, 4 is this one this way. So,
this is basically first is basically argument indicates that, which values and this is
basically what is the value for this to be by which this one.

Now, what you can do is that we can read all this things from the keyboard or some other
means by input output system or whatever it is there, then we can load all this thing into
the statement, and finally, we can execute this one pstmt.executeUpdate; that means, it
will fire this statement finally.

1205
So, this is the idea about; that means, CPU want to prepare one statement and then we
can use the prepare statement object for that. So, this is the prepare statement class.

(Refer Slide Time: 30:42)

And ResultSet is basically as I told you, it will store the results written by the by the
execution of a SQL statement through the java application and so, ResultSet is basically
is a complex on concepts, but it has, it returns you number of rows basically, if you
execute a statement, which can returns a number of rows like, so if the number of rows
are there, you can process or you can scan from one result to another result by means of
next method, it is there. So, next method is there. Any way, we will have, let us have
some examples so that we can understand about ResultSet methods are there.

1206
(Refer Slide Time: 31:20)

So, for the ResultSet class is concerned, these are the different methods, we have
discussed about it. So, better all this method will be understand during the application.

In our next session, we will discuss about different application of this result sets one by
one.

(Refer Slide Time: 31:38)

And there is again another important aspect that you should remember that different data
type. See SQL also provides certain data type, where as java provide some other data
type. So, there are mismatch in fact. So, here we have mentioned about. So, Boolean if it

1207
is the data type that sql language can understand, SQL there are structured query
language can understand. Whereas Boolean is in java, it is like a Boolean class.
similarly, character that is there in SQL, It basically understand String and VARCHAR is
basically string of characters, it is String, DOUBLE is Double, FLOAT is Double,
INTEGER is Integer, REAL is Double, DATE is, this is the class Date, TIME is class
Time, TIMESTAMP that is followed by this one, this one.

So, you have to just matching, whenever the result set that can be obtained, so they can
have this kind of data type from the SQL side. And whenever you receive from your
application side this is the data type, so there is a conversion is possible. So, there is a
method of this conversion. So, these are the method by which the data type from Boolean
from the SQL to the java program Boolean and then these are the method actually get
method, it is called most popularly called the ResultSet get method. So, by this method
you can convert the data easily into your java compatible things are there.

(Refer Slide Time: 32:56)

Now here is an example let us see, how the result set can be processed here. Assuming
that the connection is maintained and then JDBC driver has been loaded and a
connection is established, and now we are executing the statement and then this is
suppose, this is the statement that we have executed. This is the statement suppose, you
have executed, the “SELECT * from JavaCourse”. So, this means as you know, if the

1208
database includes; contains certain record, it will give all the records that is there in the
table. So, all the record will be stored into this rs object.

So, rs object is basically, the entire records, the entire rows basically, contains. Now,
here while rs dot next means this is the result set. We will content, this is a record one,
then record two, record three and so on, so dot n records are there. So, rs dot next
basically, when it is not n, n means end of this records, it will process it. Namestring
equals rs dot getString; that means “Name”, which is basically the first field will get into
these one, “Roll” get into this one, “Marks” get into this one, “Grade” get into this one.

So, get string method is basically, get whatever the type it is there in the string and from
there will be store in the string format. And from this string format if you can convert in
the integer or double or whatever the type that is required there, so that you can get it.
So, this way the one by one each record can be processed and it can be used in your
purpose. So, this is the idea about the results returned by the JDBC connection and then
it can be used there.

(Refer Slide Time: 34:35)

And another important thing is that exception is very much importance, so far the JDBC
is concerned there. So, lot of try catch block can be added there, because in exception
may occurs many times, say suppose you are not able to establish a connection so error
will occur. Suppose, you have connected the establish, but because of the network
disruption sometime the data is not accessible.

1209
So, in order to avoid all those kind of unwanted disruption in the execution, so all those
things can be caught by exception classes. So, the JDBC in the API, JDBC API there is a
lot of SQLException is there and few exception methods it is there SQLException, SQL
State, SQL error all those things can be getMessage, getSQLstate, get SQL error code, so
many things are there so that knowing the, what type of error you can process it. So,
these are the essentially exception handling mechanism needs to be followed in this case
also; those things every statement which you are going to execute or every statement
there in your program, better can be put under the Java exception handling mechanism,
these are the (Refer Time: 35:50).

(Refer Slide Time: 35:51)

So, we have discussed about JDBC driver, connection and then establishing and then
execution of the statement and then once the result is there. In our next session, we will
discuss about more how to execute statement, all the connection, all the five steps that
we have already told you regarding the JDBC application, we will discuss about all this
five statement, how can be executed and then how the different execution can be carried
out. Now, we can store and retrieve image using a JDBC or not. The answer is yes, but
the procedure is bit difficult. Although ODBC is very good for storing what type of data,
but sql is basically good for only storing the other, but that storing is not directly it is
possible, some indirect mechanisms are there. And then prepared statement we have used
it, it purpose is that, if you want to get the data one by one, those data can be collected in

1210
your application and finally, create a statement to be executed then the prepared
statement is there. So, these are the obvious questions, probably you have learned it fine.

So, thank you very much.

1211
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 52
JDBC - III

Now, this is the 3rd session of our JDBC learning and then in this session we are going
to learn about the five-step, that we should follow from the program execution point of
view in order to access the database remotely from the hope your host machine.

(Refer Slide Time: 00:38)

Now, so we will see exactly how all those things can be done, but using some examples
one by one different example that we are going to cover in these slides are like how we
can connect JAVA application to the database server. In this case; obviously, MySQL
only and then how a table can be created and then how the records into such a table can
be inserted. And, then how the results obtained from a table can be processed and then
the record can be updated and then record can be deleted. All these things we have done
in our first session of learning of JDBC when we are just connecting directly from our
console missing to the SQL server. But, here we will do the same thing, but using our
from program, not from the console.

1212
(Refer Slide Time: 01:00)

Now, let us first see exactly how the connection to the remote a SQL server can be done,
as you have already mentioned about this idea about that connection as we see here. So,
basically this is the guest login and password that is a piece of information that is
required and these basically shows the JDBC MySQL database location driver actually
we have to connect it and the test is the name of the database and then that connection
class that can be created by using this method only.

So, this basically return you the connection objects and then connection object basically
can be obtained using URL, username, password which we have set in the last three
statement. And then finally, we can have this statement console from your
System.out.println usual database connection established successfully if it is there. And
all these things should be put under the try-catch block as I have already told you in
order to handle the exception if any occurs during any problem which may occur during
either this time or this time it is there.

1213
(Refer Slide Time: 02:25)

So, this way the connections can be established and then so, this is a method by which a
connection can be done right. And, this is a simple statement that you have to follow
usually in every Java application you have to include this kind of course, in your
program always.

(Refer Slide Time: 02:42)

Now, let us see how a table can be created. First of all;’ the same procedure that the
connection can be done. So, this is the statement that you have to include.

1214
(Refer Slide Time: 02:49)

And this statement follows the different statement like how the; we can execute a
statement here. As we see here in this example so, the statement object is created using
this statement, these two statements are to create a statement object. So, statement conn
createStatement this is basically instantiation and finally, execute the method of the
statement can be used using passing the SQL commands. So, this is basically SQL
command show tables. Now, the result will be written and this result will be caught in
the rs result statement object; rs is basically statemented that we have created here.

And, then we just scan all the results that obtain that that is there in these rs we can say
array of results we can say rs and then rs.next means we scan each element in this rs
array one by one and then we can display on the console. So, if you can pass a while
statement until all the elements are traverse; we will be able to do that. And, then
statement .execute another statement that we are going to execute after knowing that this
table is there, create table JavaCourse Roll Integer primary key, Name Varchar Marks
Integer not null, Grade Varchar. So, these basically tell you that a new character table
can be created and that name of the new table may be saying JavaCourse.

So, this way the new table can be created and then we can get it. So, all the statement
that we can we have executed ones using SQL server directly from the console it can be
existed from the Java program using this statement actually.

1215
(Refer Slide Time: 04:24)

And then the statement can be executed again after the in creation is there, if you want to
see exactly where the table is created again the same statement can be executed show
tables. And, then rs statement getResultSet it will again the return the results is showing
all the table and in this case you will be able to see that new tables which have been
recently added can be shown in there.

(Refer Slide Time: 04:52)

And then these are the parenthesis things under the catch and try and catch blocks should
be there so, that the exception can be handled properly. So, these courses are available

1216
readily will be able I will give you the source of all these courses in our next session
when you will discuss then you can run all those courses and you can understand
thoroughly one by one so, that if you can. So, that will give you a lot of practice to
understand how things are going on.

Now, we will discuss about how a record can be inserted into a table again from the Java
application; you know how the same thing can be done from the console directly to the
MySQL server.

(Refer Slide Time: 05:22)

So, again here you see the Connection type of object conn Statement and rs these are the
three different type of objects of type connection statement and the result sets that are the
things we have defined it. And finally, we create a connection here using the same
method that we have discussed.

1217
(Refer Slide Time: 05:42)

So, the connection is established and then finally, we execute the statement and this a
statement object is created and this a select star from JavaCourse. This is the SQL
statement we fire from this program and then it will result return the results rs. And, then
we can browse the results through this while statement; each record can be printed on our
screen. I mean displaced screen like using this simple System.out.println. Once the
record will be obtained and this is the process by which we can get the values and then
processing these values into the string, actually, it will display all the results.

And, then once the result is the after the execution of the select star from JavaCourse we
have to execute some other statement like statement execute INSERT INTO JavaCourse
with value this one. So; that means, here the five different statements SQL statements we
have fire these are related to the inserting the records into the table. This is the initial
table, it may we usually if it is the initial table it does not have any record after inserting
this one it will give the records are to be inserted into there. And finally, we can get
results sets using this rs statement and then the result can be obtained after the result of
this in secretion is there.

1218
(Refer Slide Time: 07:02)

And then that the result again be processed using the again passing because, it will
process all the results that can be obtained from this one and then the result can be shown
on the display screen. So, this way you can connect you can establish a connection and
then once the connection is established we can fire a lot many skill statements to be
executed. And, then on the successful execution of each statement we can get the result
and then all those result can be processed using these are the few courses that we have
mentioned here.

(Refer Slide Time: 07:31)

1219
And then finally, all those programs should be put into the exception handling trike and
broths mechanism.

(Refer Slide Time: 07:41)

Now, inserting a record with another example; let us see how things can be done. Again
it is the same as the previous one we create the conn and then p statement here basically
we have to prepared statement we have to follow; that means, we can read some values
from the keyboard and then statement can be prepared and then finally, this statement
can be executed. So, these are p statement object is created finally, this is a statement and
then rs the result where it will be stored. So, they are the four objects that we have
defined here and this is the connection mechanism few lines of course, that is obvious it
is there and we can just simply make a connection.

1220
(Refer Slide Time: 08:3)

And then once this connection is there we can execute some statement. So, the statement
is created and then this is the SQL statement is fired from this. So, SELECT star FROM
JavaCourse and these basically first we want to see the result before insertion what is the
data it is there; so, it is the basically it will get all the records those are there at the
moment before executing any insertion. And, now we are going to take the input from
the entries of the table JavaCourse; first we give a prompt Enter Name read the name
from the buffer keyboard. So, keyboard from the keyboard the array name will be
entered and then it will read it and then this will store into this name right.

(Refer Slide Time: 08:55)

1221
So, it is basically name and then grades and then roll number and the marks everything
can be read from the keyboard and then their value can be temporarily held there. And,
then the p statement using this command all these values that we have read from recently
from the keyboard can go to these values. So, this basically this thing we prepared using
INSERT INTO JavaCourse Roll, Marks, number, Grade VALUES is this one; all those
values is question mark. Those value will obtain from the p statement all these get int get
string setIntString.

And then finally, p statement executeUpdate means all the value that we have already
stored and will go to this one and finally, the entire statement will be executed. So, this is
basically the problem the statement that you can do it and then finally, after this insertion
is done we can display the result. So, results after the insertion again we can execute
SELECT star FROM JavaCourse, the result set can be obtained again and then these
results can be scanned one by one for each field Name, Roll, Marks, and Grade one by
one. So, it will basically display all the records including the new record that we have
added into the system and finally, it will try cache block it is as it is there.

(Refer Slide Time: 10:06)

Now, inserting a record into a table that we have discussed how it can be there and now
processing a table either we can do a lot of processing.

1222
(Refer Slide Time: 10:18)

So, basically, the result data set that can be processed here. Now, here again same thing
we first import java.sql.star; all these things would be inputted there and this class
basically is a Java application in this case by which we can process any execution like
and these are the few statements here as we see here. In this example what you want to
do is that say, suppose already a table is there and for each table, all the marks are
already there for say 100 records or whatever it is there.

Now, we want to get the results and then we can get the results from the server and then
being all the results in our application end and then make their average. So, basically this
program will tell how the results can be obtained from the remote server from a table and
then the average of all the marks can be calculated and it can be finally displayed. So, it
is the idea and so, this is the process that we are going to give a simple example here. So,
these are the few statements as usual earlier. So, it basically establishes a connection
from where application to the server.

1223
(Refer Slide Time: 11:30)

And then this is the statement object is created and then we got all the results because we
need to fetch all the results. So, SELECT star FROM JavaCourse it will basically fetch
all the results, those the result will be store in rs results sets and then results that can be
obtained can be processed it is like this as you see here. So, we just give the Name, Roll,
Marks and Grade they are all string and then finally, we can convert all these things into
the numbers form.

So, total marks are integer parseInt MarkString so, it basically read the results are there.
So, total marks will be obtained for each record getting one record at a time and then
getting the results are there and then finally, the total number of records can also be ca co
obtained. So, this is the formula getRow from the result sets is basically says that how
many rows that we have fetched it. So, this basically includes the total number of records
are there. So, it is basically a total number of students and we in this statement after
parsing all the records we can got the total marks and then this is the total number of
records. And finally, the average marks can be obtained by this one and the assign can be
printed on the screen.

So, as you have learned about how the entire results from a database can be fetched into
your Java application and then some processing. It is a just an example that how this
processing can be done. There are a lot many processing also can be done from the SQL
end also; this average calculation is also possible at the SQL site also using some SQL

1224
command. But, this result also can be obtained and you can get it there. Now, here is a
question some processing can be done at the server end, it is possible you can fire those
processing exhibiting the statement from here and then get the result. Or, you can get the
entire result in your n program end application and then compute it and then process it.
So, both way it is there, some things which are not possible from the server end you can
get it and then you can solve it that is also quite possible.

(Refer Slide Time: 13:29)

So, whatever the way the processing it is there and the rest of the trailing part of the
program is basically related to the exception handling. Then updating a table it is
basically how we can update command.

1225
(Refer Slide Time: 13:43)

Update command already you have learned about while we are studying the SQL
statement there. So, first of all, we have to create an establishment and then create few
important objects like conn statement and rs for related to the connection statement and
other result states storing. And, then these are the basic string that we have declared to
be used intermediate way and this is basically the; for five steps which are required for
establishing a connection from your program to the JDBC server.

(Refer Slide Time: 14:07)

1226
And then we can use the statement like this one this basically creates a; I mean is a
define a statement and then this is the execution of the statement like SELECT star
FROM JavaCourse. So, this basically shows that what are the entries are there as usual
earlier we have discussed it. So, this a statement will be executed, the data result will be
stored in the rs object and then this rs object can be passed one by one, scan then finally,
it will display.

And, then here we just give we just execute one more statement is called the update. As
you see statement.execute we are going to execute one more statement update, then
JavaCourse set Marks. Here exactly you see update these are table name and set, the
Marks equals to 85, code equals to Ex where Name equals to this one. So, that means, it
will find a record whose name is this one, if it find this is the condition upon the
condition; satisfying the condition it will basically change this record with these values.
And, then after this update command is successfully executed we can face all the records
and see whether the results are updated or not.

(Refer Slide Time: 15:25)

So, the last few statements is basically executed the select start from and then rs.next we
can again reply we can see that whether the update common has been executed or not. If
that data is satisfied this condition definitely you can do it and then finally, it will have
updation is successful there and again the try-catch block is basically to ensure that the
program is executed in a reliable and more robust way.

1227
And then deleting a record, it is basically how the record can be deleted, the same
procedure will follow. First of all we have to create the statement object and then
connection objects and then result set object and then we have to establish a connection.
And, then using the statement object we have to fire the; a co statement SQL statement,
in this case, deletes a record.

(Refer Slide Time: 16:13)

Now, here is the statement here we create the connection object, statement object, result
set object and then these are the temporary variable that is required.

(Refer Slide Time: 16:27)

1228
And then this is the five steps that are necessary to create a connection and all those
things should be placed in the try cache block. And, here now Result Before Delete; we
just see exactly what is the result it is there and then here basically we are creating we
are executing one statement called the delete from JavaCourse. Now, if we delete from
JavaCourse this means that it will delete the entire, I mean a number of records those are
there in the table. If they delete some records from this one certification condition only
that kind of records will be deleted whose condition is satisfied.

But, this is a very dangerous one delete common like it will delete all the records, but not
the entire table. Table will remain there now, hereafter this deletion is there if we just
simply execute this statement to get the other records if it is there, if you see then get
result. And, then again processing the result as is the same way one by one you will see
as this is not there so, rs.next will return null.

(Refer Slide Time: 17:25)

So, null means it will not execute further this statement and then it will do not give any
print on the screen.

1229
(Refer Slide Time: 17:30)

And so, this is the delete statement as we have seen.

(Refer Slide Time: 17:32)

And then deleting a table and this is another command it is there drop command and
again the Statement, Connection and the ResultSet are created and this is a connection is
established.

1230
(Refer Slide Time: 17:44)

And we execute the show tables; that means, what are the tables are there. So, show table
says you know show table, show databases everything is there you can execute it, under
your own login password, your authorization. If their many databases it is there showing
database will show you all the databases. Now it is there so, results as getResultSet
basically it will return you the result set and System.out.println it will show all the tables
which are there including their table name. So, the Table in the test will be there and then
the table will be displayed; that means, whatever the tables are there.

Now, after these things we execute the drop table JavaCourse; that means, we want to
delete the table permanently whether it contains a record or not. It will remove the table
permanently physically from the server and then show tables after this thing again the
same thing if we repeat and then you will see that all tables are there except the
JavaCourse table is there because JavaCourse table has been deleted. So, this is the way
the different statement that can be executed and then after exiting the different statement
we can process the results.

We have state three sessions, we will discuss about demonstration giving all those things
in details starting from the installation of SQL server, installation of JDBC driver and the
execution of some SQL statement from your application.

So, thank you very much.

1231
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 53
Demonstration – XX

So, here is the session about JDBC, there are there is a series of demonstration will be
followed after the learning, so, for the theoretical concepts.

(Refer Slide Time: 00:31)

So, first we will discussed about regarding the MySQL server installation and after the
steps of installation we will decide exactly how to access the MySQL server. Initially we
will consider about the console based accessing and then later on another session where
we will demonstrate how the same can be done through the JDBC driver. So now, let us
have the demonstration about the MySQL database server installation in your own
machine right.

It may be laptop, it may be PC we will we are going to consider the installation in


Windows system. However, the procedure and the steps basically in variance for any
other systems to be followed. So, as an installation the first step is basically to download
the software as you have told the download the link that we have already given.

1232
(Refer Slide Time: 01:22)

So, this is the link the dev dot mysql dot com oblique downloads oblique. So, this
actually is the link; so, if you just able to access this link then it will open a browser
window where you can find MySQL community downloads.

(Refer Slide Time: 01:58)

So, we have just clicked the link and then we see that MySQL community server is there.
So, we have to open the link and then we will find the installer basically as you have told
Windows installer you have to consider here. So, this is basically archive a ZIP Archive.

1233
(Refer Slide Time: 02:12)

And depending on your machine configuration whether it is a 32 bit or is 64 bits; you


have to decide the correct what is called downloading software for your download. So,
that you have to ensure that otherwise your installation may not be successful operation.
So, assuming that our machine is Windows 64 and we are just going to download the
latest version of the MySQL server which is the MySQL 8.0 and then release 13.0. So,
we are going to install it; so, here actually we have already pre-installed, it is in our
desktop terminal.

(Refer Slide Time: 02:49)

1234
And then so, this is a zip file. So, this zip file you should copy into some directly where
you were you want to install; obviously, zip file is a compressed one you have to unzip
the folder. And then so, it will basically give you all the installable file that is there in
there in the zip file.

(Refer Slide Time: 03:09)

So, here as you see the folder where we have unzipped the all components is mysql 8.0
then 13.0 and then win war. So, this is the software basically we have right to copy this
folder into the exact location where you want to install as we are going to install into our
C drive. So, you just copy this folder into our C drive here and we just rename the drive
as mysql because, you want to install this software as a MySQL.

So, we have done it my SQL ok. So, our zip file contains lot of other executable bin then
data then docs etcetera. So, we can see these are the basically zip unzip these are the total
installable file it is there. So, this is the first step that the download it and then we have to
copy the folder into the proper location.

1235
(Refer Slide Time: 04:10)

And then we have to so, this basically completes the downloading about it and then go
to the command prompt. So, you have to copy the my any file as we have already
mentioned and that my any files should be placed into the MySQL directory. So, my any
file the configuration which is there that configuration and we have already mention in
theory class; we are typing the configuration that is required for the my any file right.

So, this is the syntax that you have to follow verbatim without knowing what exactly the
things are there, only the system can understand about the any file. This is required for
the initialization so far the MySQL server is concerned. So, MySQL id then hash
installation directory then base directory. So, it will be base dir equals these is a base
directory where our zip file is located that is c colon then slash mysql slash within double
quote. And then data directory hash data directory; data directory is equals to within d
colon dash data.

So, this is basically back up file will be stored in this drive we have planned that all the
backup file or data file will be stored in a D drive of this machine. You can make our
some other stores location also no issue.

1236
(Refer Slide Time: 05:37)

Anyway so, the data file is created here in D drive, we have created a folder there.

(Refer Slide Time: 05:41)

And there is in a C diver so, you see in the mysql directory the data file is there, this
folder should be removed. So, we are removing this folder from here.

1237
(Refer Slide Time: 05:50)

Now so, this completes exactly the storing the files there.

(Refer Slide Time: 05:57)

Now, you have to run the program and to run this program you have to go to command
prompt. And in command prompt mysql go to the bin directory and there you type
mysqlid --console console. These are command already you have mentioned there
console data initial is right initialize right ok. So, once we face it so, your system will
take care about this installation of these program.

1238
So, installation is going on and then as you return to the command prompt and you have
return it to this and localhost that basically the this machine is the host machine in this
mysql server is there. So, we have completed the installation here ok. So, it is now
installed, now our next task is basically to change the password.

(Refer Slide Time: 06:57)

So, we can do this thing again from command mode. So, mysql -u root -p. So, basically
user is root and then password it is basically asking the password. So, in this local
machine and then you have to enter the password you can type any password. So, in this
case you are setting the password as the root password right ok. So, this is the localhost
password is basically as it is mentioned. So, this you have to give the password at the
beginning; so, we are copying it and then pasting.

So, you are giving the password; however, we can change the password also for these
things, we can write the command alter. So, we are just changing the user id login for
this as alter user give this root, we are giving the user name as root at the local host. So,
this is the step that you should follow user root and percent localhost. So, this is a
command identified as root. So, this is basically root is the user id in this case enter. So,
there is some syntax error ok.

So, now so this is the correct syntax that you should follow in order to give the proper
name of the user here, you should note it this is very important and then once the user is
there we have to set the password also. So, you should set the password here ok. So, here

1239
you see alter user command. So, this is the user at the rate of localhost identified as this
is basically the password. So, we set for this mysql server at the moment user id as root
and password is also root. So, this is the login and password for this one.

(Refer Slide Time: 09:15)

And now our mysql server is ready, we can type exit command and to exit from this
setting.

(Refer Slide Time: 09:27)

Then we will go for the class per checking or not now. So, we have done it and then we
can change the password, this is the changing the password of.

1240
(Refer Time: 09:35).

So now, we are now our server is ready and now we are going to log into the server. So,
for this login we have type the command in the mysql prompt you have to go mysql -u
root –p is basically ask for the password to be entered. So, the root is the password and it
is case sensitivity. So, in the small letter you type root. So, it is there and then system has
accepted this authorization check is passes. Now, one thing authorization check is
passed; that means, MySQL server is now allow you to execute any statement whichever
you want to run it right ok.

(Refer Slide Time: 10:22)

Now, we are going to first our step is that initially the server is prepared; however, there
is no database there is no table under this database. So, we should see exactly if there is
any database at the moment in the server or not under your categories. So, absolutely is
not there; so, you first create this is the default database is there, but we have to create
our own.

So, now we are going to create one database of our own. So, clear let it be test database
test now so, database test is created. Now, again if we try to create database test it will
give an error because, it will not allow to duplicate the test 1. So, it is there now, if you
can again create database test 1 this is quite possible test 1. So, it is you can delete also if
you want to remove these.

1241
(Refer Slide Time: 11:16)

So, databases if you see it will give you all the databases that is here. So, right now test
and test 1 these 2 databases have been created.

(Refer Slide Time: 11:27)

Now, these 2 data bases under your own jurisdiction and inside these databases you can
put as many table as you wish. Now, we are going to enter some table under the data
base test 1. So, you have to make it active.

So, let us use the command use test. So, this basically make the data base currently
active. So, this is now current active database test. Now, whatever the command that will

1242
be you will be able to enter it now it will go to this test data base actually. Now, let us
first create a table, we want to create one table the name of the table that we want to give
a JavaCourse.

And then this table has four fields as we see Roll, Name, Marks and Grade, they are 4
columns actually. The first fill field Roll has the type Integer we have to give this syntax,
the Name Varchar and then you can type in integer in capital letter or small letter
absolutely no issue. You can do whatever it is there and then the second field is Name it
is basically string of 30 characters, for this the syntax is Varchar. And then within
brackets is 30 indicates the maximum 30 characters can be allowed to enter or; that
means, this is the weight of the column. And then Marks is also the type Integer and then
Grade is also a character, but is of 2 characters only.

And one more thing that you ensure that for the first field Roll we have declared the
primary key. For every database table there should be one field as a primary key, there
may be more than one field also primary key any way no issue. But, if it is a primary key
then it should have all the entries are all null and entries in any rows should be unique.
So, you cannot allow it based system not allowed to duplicate entries in 2 rows for this
value primary key which is defined. And then other is also you see marks integer not null
this indicates that these entry has to be there whenever you insert some record into it no
null values is allowed.

And great is a second and at the moment there is no entry. So, it is basically default is no
value is it is there. So, we have entered it now you can show the table that we have
entered; so, table you see ok. So, this is the case right now we have created one table
called the JavaCourse and this is the describe command short form DESC if we type it, it
will basically display all the structures there which is there.

1243
(Refer Slide Time: 14:04)

So, as we see the 4 fields there type and then null key is primary default is null also and
there is no exactly my field and there is a total structure composition so far the SQL
server is concerned maintained this metadata in its own repository. Now so, the data is
created now at the moment is javacourse table does not have any data.

So, if we add use the command select start this basically the command is to retrieve all
the record that is stored there in this database in this table JavaCourse. At the moment as
it gives that empty set there is no elements there. So, now let us see how the record can
be inserted into the table the JavaCourse again which is under database test. So, there are
commands like insert, insert command can be one at a time or four insert commands can
be also placed in the same command also, now we are typing only one command first ok.

So, at the same time we have typed all commands on by one anyway so, it will execute.
So, first insert into JavaCourse value 0 1 Debasish 75 A. So, 4 records has been inserted
and you know all these record insertion will go into the appending mode. So, one by one
it will be inserted; now if again if you see the show table or select star command and as
you see the four records has been inserted.

Now, I am again issuing one more insert command here insert into data into javacourse
value say 0 7 and then within quote name is Amit and then marks is 95. And then grade
is EX within double quote all the string or varchar should be in the EX. Now, semi colon

1244
should be there termination of the command enter, now it is successful; now, enter the
data right.

(Refer Slide Time: 16:03)

As we see we can enter it here roll number is the unique key, now let us see again insert
command at the primary key should be unique. Now what we are going to be, we have to
starting the insert and then 0 7 again insert value 0 7 Anand a n a n d Anand then 85 fine
no problem. So, whatever it is there; now if we want to do because primary key should
be a unique one, but here as we have given this so, it basically gives that error. So, it
should be different ok.

1245
(Refer Slide Time: 16:40)

Now so, this you have added it and as we see at the moment there are 7 records entered
into the table. The name of the table data database table is javacourse. So, this is the
insertion command is there and also we have learnt about the select command select star.
Now, select star has the different other nesting and then conditional base also. Now, here
we want to execute the select command select name roll from JavaCourse.

So, basically not the entire table, but only 2 columns mainly name and roll number it will
be there; as you see name is there roll is there. So, in order you will specify the field in
that order it will basically get the data as we see the 5 records have been retrieved and
there are 2 fields name and roll number has been there.

1246
(Refer Slide Time: 17:37)

So, again so, select star indicate all fields, but if you specify the name of fields so,
explicitly only those fields will be selected and then so, again from select only the
grades. So, if you see it will not display the name yes, select grade from JavaCourse as
you see here right. So, it will only the particular field will be particular field; that means,
column grade will be selected as you see. So, this one and this is basically the results that
SQL server returns against command that you have given to it.

Now, our next command that we are going to exercise is basically conditional. So, select
star from the JavaCourse with certain condition, here suppose the condition that we are
going to give that marks is greater than 80. So, that mean it will basically retrieve those
records whose marks is greater than 80. So, this is the command that you followed and
note that command should be terminated by a semicolon. As we see out all the records
these are the 2 records only satisfy this condition and therefore, has been retrieved. So,
this is the select with condition, there are many other complex condition also can be
fired.

1247
(Refer Slide Time: 19:03)

Now, let us see another conditions that we are going if this condition does not implies to
any record so, then in that case it will return null. So, here is another select star from
JavaCourse where name here this is the command name like something; that means, we
want to have if any name is there for which any substream JEE is there. So, this is the
command that we are going to write yeah.

So, you see here within single quote there is a “ JEE “ this means there should be any
one name who substring is jee; as it does not have any such name in this current record
entry. So, it should return an null actually. So, its empty set as its says that there is no
record which matches with this condition therefore, it returns empty sets.

1248
(Refer Slide Time: 20:02)

Now, next our commands is basically we can also retrieve the order according to some
ordering may ascending order or descending order based on the numeric field. As we see
we have the two numeric field one is roll number and another is grade marks. So, let us
see to retrieve the value of the field based on the ascending order of the number like. So,
select star from JavaCourse order by marks. So; that means, the marks field will be order
in an ascending order.

Now, the same thing also we can do in descending order; in this case the command little
bit you have to change in order by descending order right; ordered by desc write desc
after the by the desc right desc desc then marks. So, this is right so, we are facing some
syntax error anyway. So, select start from JavaCourse order by marks descending. So,
this is way you can see this display the record in the descending order of the results.

1249
(Refer Slide Time: 21:54)

So, we have learn about the different compositions, there are many more select command
is very complex also because, nested select is also possible here. Anyway that we do not
want to discuss at the moment, let us proceed further. Now, we will exactly how a
particular record we have learnt about how to insert a record, opposite to insertion
operation is basically deletion we will see how a record can be deleted ok. So, have we
have to first discuss update, let us see exactly how a record can be updated here. So, we
will discuss about the update command.

So, update is basically JavaCourse, we have to update the table and then to update it you
have to give some condition that what is the basis of updation in which value needs to be
updated. So, here is the command update JavaCourse set, we have to just change the
value the field name and we have to change the value of this field by Debasis where
Name is equals to Debasish. So, it will find if any entry for the field name is equal to
Debasis it will change Debasish as a different spelling. So, this one enter now it is done.

Now, if you show if we show that it will select star. So, you will see in earlier case select
star from write javacourse as you see the these things been changed. So, like this
anythings for example, you want to change the marks who got 75 or more we want to
make it as a 80 or (Refer Time: 23:38) like. So, here again we are going to change it
update javacourse set marks equals to 80, where marks equals to 70 marks is greater than
75 that is all, marks is less than 75 rather.

1250
So, you can understand what is the meaning so, all the marks will be right. So, it is
changed one change has been done as you see those are the 75 above had been changed
and this update is basically permanent; that means, one you do it so, it is basically
permanent forever. So, this is the one another updation is set marks equals to 85 grade
EX where, name equals to Debasish we want to change this yeah. So, we are just going
to change it that.

(Refer Slide Time: 24:42)

Another update command as you see we are using another update command update
second update right yes. So, as you see here update JavaCourse set Marks equals to 85
Grade is equals to Ex; we are changing the 2 fields where Name is Debasis. Earlier,
Debasis marks is 75 A, now after this updation you will see marks will be 85 grade is
here grade right. As you see this has been updated. Now, fine so now so update is there,
next our statement that we are going to discuss about delete operation.

1251
(Refer Slide Time: 25:27)

So, delete means basically if you want to delete a record, it is again physically deletion;
that means, it will remove forever. Here we are issuing one command delete from
javacourse where marks equals to marks is less than 75 fine. So, you are deleting the
marks there is no entry which satisfy so, no deletion is there. Now, we are giving the
command marks is less than 85 ok. So, here we can see 2 rows has been deleted; after
deletion if we see the table entry we will be able to see that this is the table actually there
which basically is there deletion.

And so, delete if we issue the delete from table the entire table will be deleted delete
from javacourse. So, this means it is permanent 3 rows where the present it is there. So, it
is deleted the set is empty, now we can permanently remove yeah show table; as you see
only on table javacourse is there. Now, the entire table also can be deleted whether it
contains data or not it absolutely does not matter; for these are command is drop table.

1252
(Refer Slide Time: 26:53)

So, here you have the command drop table the name of the table. So, this one basically
completes this one. Now, if we show data then show tables as you see there is no tables
in these database. Now, that database also can be deleted as you have current database
test right it can be deleted no ok. Anyway so, as we see there are few some step SQL
statement.

How they can be executed after the successful instalment of SQL server. Now, we have
done about the SQL our SQL installation is ready. It may be here in the currently local
machine, but the same can be installed in a remote machine also.

1253
(Refer Slide Time: 27:35)

If it is installed in a remote machine so, you have to note the IP address of the same
machine and then using this concept you will be able to connect to this. But, this
connection is through the JDBC driver. So, that will be discussed in our next session.

Thank you.

1254
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 54
Demonstration - XXI

There are three things so far the JDBC is concerned; one is the database management
system which is basically in this learning we have considered MySQL and then another
is that JDBC driver which is basically you will connect to the server and then third
component is basically the Java application.

(Refer Slide Time: 00:31)

So, JDBC is the middle which will basically connect your program means Java
application to server. Now in this session, we will try to learn about the details about the
JDBC driver.

So, first, we should see exactly for this MySQL server, the proper JDBC driver needs to
be installed. So, we will discuss about how the JDBC driver will be responsible for
connecting our Java application to the MySQL server. So, downloading the JDBC driver
and then once the JDBC driver is installed successfully after downloading; obviously, the
installation we will see exactly how this can be installed. And then finally, the through
the JDBC driver and then Java program how we can execute some statement, SQL
statement; and we will execute the SQL statement from our Java application Java

1255
program, and then we will see their results from the console again; that means, through
the again connecting them is MySQL server after executing. This basically gives an idea
about that whatever the comment that we are intended to execute form the application
whether it is successfully executed or not.

In our next session that will be held later on we will see exactly how the results also that
can be obtained purely from the application itself ok. Now let us start about how the
JDBC driver can be installed. The location of the JDBC driver is we have given the link
is there.

(Refer Slide Time: 02:11)

So, https://dev.mysql.com/downloads/connectors/j/. So, this basically is the link from


where you can get the JDBC driver for the MySQL connector.

1256
(Refer Slide Time: 02:29)

So, MySQL connector is there and there is a connector J.

(Refer Slide Time: 02:35)

You just go to the link and finally, you will be able to set the proper program there.

1257
(Refer Slide Time: 02:41)

So, it is basically a platform-independent one version that you have to install it. And so,
this is the version this is a zip file of course, and the version is for current SQL 8.013.

(Refer Slide Time: 02:51)

It just simply starts downloading. So, you basically download now.

1258
(Refer Slide Time: 02:53)

So, download from the net, it is free software. So, there is no issue. So, for downloading,
this software is concerned. Once the JDBC driver is download then you have to extract
the zip file, and it can we download in any directory. So, we will just advise you to
download into on C drive right ok. So, we just unzip this zip file and then we, once you
do the unzip, then you can find so many folders there are a one folders called JDBC
MySQL connector.jar file.

(Refer Slide Time: 03:29)

1259
So, this file you should rename to MySQL for just for simplicity, you can give any name,
but for convenience you can give this one and then finally, you should place the jar file
MySQL.jar file along with any other program which includes in this using JDBC, that
should be done by one command from the command prompt java minus cp MySQL.jar
and then what the all file name fine.

So, you just simply copy this jar file into this one right. So, we have copied it right. So,
we have copied this MySQL jar file and this and then we have to finally, set the
classpath name from the system file itself so that this JDBC driver can be identified from
any location. If you execute it, so, you have to set the classpath also there.

(Refer Slide Time: 04:11)

Anyway, so, our JDBC connection this is this gives you complete competition about the
JDBC connection is there.

1260
(Refer Slide Time: 04:37)

Now, you have to login to the MySQL server because we are quit from we are exited
from this one, the password is root here now ok. So, the JDBC this MySQL connection is
done currently it is there.

(Refer Slide Time: 04:51)

Now, we want to write some Java program by which you can execute some SQL
statements and then after the execution of the statement, we will be able to see the result.
Now see there are few steps; obviously, involved. The first thing is that you have to
create few objects; the first is that connection object we give the name as conn.

1261
We define connection object and then we define ok. So, this is basically setting up the
connection and then username is root, we have to write is username root password is
root, URL is basically you can note it JDBC MySQL this is basically localhost and this is
the number that is there, is a port number is 3306 and the JDBC, the drivers should
connect to a particular database. So, the last field is basically the name of the database.

(Refer Slide Time: 05:49)

As we have know already we have created one database in an earlier session, and the
same database will be used there.

(Refer Slide Time: 05:59)

1262
And then we have to load the JDBC driver by using the statement is basically the
“Class.forName.com.MySQL.cj.jdbc.Driver”.newInstance this is the method and so, this
basically is to load the JDBC driver into your application actually ok. So, this is the right
and then we have to establish the connection created an instance of the collection of
object for which the DriverManager is the class there.

So, DriverManager.getConnection and giving the URL. Whatever the URL you have
given there you just give the argument here URL, userName, password; otherwise you
can in this method also you can type within double quote all the argument this also will
work, but for the convenience, we store it and then pass it as a method arguments.

So, this basically creates the connection objects and then if the connection is successful
from the program, we will get if there is no connection successful it will given an error.
Now let us see whether error or not there. So, for the error handling, we have already
enclose everything under the try-catch block. So, these are customary try-catch block
that we have enclosed it now ok. So, run this program java minus ct yes.

(Refer Slide Time: 07:21)

So, now we have already loaded this one here java minus cp MySQL.jar connect. Now
connection is there. Now we can compile this program. So, the program is successfully
compiled and executed after the execution is there. If we see the database connection
established database connection is now terminated also.

1263
Now, if I suppose there is a mistake for either say some name or some say root password
is changed; so, guest g u e s t, suppose this is a wrong password then if wee again try to
connect it, java minus cp MySQL.jar connect as you see it basically compile it. The
compilation is done and then running this program, as you see cannot connect to
database server this is because of this one. So, an exception is caused access denied for
user root localhost using password yes. So, this basically refuses to get the connection.
So, root is the password that is required for the correct or successful connection at this
moment.

(Refer Slide Time: 08:39)

So, this way you can see how the connection can be made with the JDBC to the MySQL
server through the JDBC there. Now we will discuss about how the simple statement can
be executed. Here the simple statement that we are going to execute is, create a table java
course because there is no table at the moment. So, as there is no table we will not be
able to accomplish any insert, delete, update command.

1264
(Refer Slide Time: 09:07)

So, first, we have to create the table. Now, this is the one program as we see. This
program basically tells how we can create a table. Now here you see this is the
Connection object is created and then the Statement object is created of the class
Statement, ResultSet it basically it will return result set; in this case, we will not consider
all though, but it can give the results. And here is basically userName; root and then
password also root we have stored and then URL is JDBC here; JDBC MySQL localhost
this is basically URL for the our MySQL server in this case.

Then we establish the connection using this command Class.forName.com


MySQL.cj.jdbc.Driver then .newInstance. This is basically the syntax for which the
connection can be made. When the connection is it is successful then we have to create
the connection object through the DriverManager getConnection giving the argument;
URL, userName and password which is basically assigned here. And then so, this
basically completes the connection and here is basically we are creating a statement
object.

So, statement for conn.createStatement object is created and then this statement object is
initialized with one statement the create table; JavaCourse Roll Integer primary key,
Name Varchar 30, Marks Integer not null, Grade Varchar 2. So, it is basically this is the
way the usual way, that a table can be created with four fields namely roll number name
marks and grade like.

1265
And so, now so, this basically completes the firing the execution and then if there is an
error or whatever it is there it will obviously, catch by the try-catch block. So, this
basically is the program which basically creates a connection objects connect to the
server through JDBC driver and finally, execute a statement to create a new table and the
command is that java minus cp MySQL.jar and then create a table this is the name of the
class that we have created here.

So, this is basically the program and then in the server, we are coming to the console to
the server and here show table-use test show table. So, we see the new table java course
has been created under the test database. So, this is the first step or creating the table
here. Now let us execute some other statements from this table. First is that we have to
insert a few records into the table.

(Refer Slide Time: 11:53)

So, we will see exactly the table that you have just now created from our Java application
how the same can be used to insert some data, we will create many records as many we
wish. Here we will consider four records to be inserted with one SQL statement. Now,
this is a program as you see this is a program. You see here first of all these are the. So,
this is the conn is the Connection object, the STMT is the Statement object and then here
is the basically userName and password and URL these are the three parameters that
required to install the DriverManager.

1266
So, we use these object and then finally, through DriverManager we connect it. So, the
conn object is now ready; that means, its connection is established and then we just
create a statement object and then the statement is basically created with execution for
request with four insert records one by one. Here you see this is the first insert then
semicolon, then the second statement.executes second insert and another
statement.execute the third insert and then the fourth insert for this fourth execute
statement.

So, this way we have issued the four a statement and then we call the executive method
for this statement object to execute these are the four statement. This basically the
request will pass through JDBC to the server, and the server will execute it and then
finally, we will see whether a server has done the things correctly according to the
request that is there in the application.

So, here again, we are running the program, this is the name of the classic insert records.
So, right in ok. So, the common is java minus cp MySQL.jar that you have to give it
colon then you have to give the InsertRecord. This is the syntax that you have to follow
if you want to communicate. So, there is no error message that means it has been
executed. So, let us come back to the table here again. So, we can see a select star from
the java course, it is already there. Here also if we write say desc table java course also it
will give the same things as usual because the table has been successfully created with
the structure that we have given it there.

1267
(Refer Slide Time: 14:21)

So, it is successfully created. Now so, the table is created four records has been have
been inserted into it. Now we will see exactly the Update command how this can be
executed from the Java application through JDBC driver to MySQL.

(Refer Slide Time: 14:43)

Again let us look at the code here ok. This code is, as usual, this is the Connection,
Statement objects and these are userName, password and then this is the URL and we
create the Class.forName passing the userName, password and then URL.

1268
And then finally, we create the conn object; that means, connection object in calling the
DriverManager.getConnection method with the URL, userName and password and then
this is the statement object is now ready to fire. Now here the statement you see we use
which command, SQL command to include it here update JavaCourse set. Name equals
to this one where Name equals to this one. So, here is basic and you see in the first table
that we have discussed there is one entry basically the first entry for which the name is
Debasish d e b a s i s h. So, it is basically this command is requested to change this entry
as a d e b a s i s. So, now, we are this program that is now ready and then let us compile
this program and then ok.

So, this program yes. So, update record this is the name of the file yes. Now the record
has been updated and let us come back to the command prompt. So, command prompt
again just see exactly select star from you can see the updation is successful. So, this way
the command relative update can be fired from the Java application and then we will see
exactly delete command, we will just be going to delete one record from the table is java
course here and here.

(Refer Slide Time: 16:37)

So, it is basically this is the program as we see. So, this is the usual the things it is there
in we have already familiar with this thing in the last examples and this is also clear only
I just changed that we have done here. So, we have just create delete from JavaCourse
where marks are less than 66.

1269
So, in the record, there are some marks if it is less than 66 like the which 65 it will be
deleted. Now so, let us. So, this is the only statement that we are going to do it. So, delete
records. So, it is there now as you see there. Now here I am just going to change one
little bit small change here. So, as you have already seen that. So, more than one SQL
statement can be executed. So, those actually this is basically a statement.execute method
is there.

So, I am just changing you just add one more statement.execute instead of delete keep it
delete here, then insert right see roll number 7 Amit marks is not here, next just copy
statement.execute again right. So, these are deleted we are giving going to execute. So,
insert right.

(Refer Slide Time: 18:11)

Insert into the right java course then 0 name roll value yes. So, fine, so, Amit. So, values
it should be valued inserting to java course values v a l u e s values 12 Amit, 85, a this
one right. Now we are inserting one more record now I am just right going to here. So,
we have to save this program we have changed it. Now it will execute two things; delete
as well as insert also. So, yes nowhere you can see right. So, the new entry has been
made here as you see. So, as many as SQL statement can be executed from one program,
as you have seen you have tested it to two; so, it is not necessarily limited to two more
than two statement also can be executed from the same program itself.

1270
So, depending on your requirement whatever the SQL statements are there, that we will
be able to insert it.

(Refer Slide Time: 20:05)

Now here is the another delete statement as you know, we can delete the entire what is
called the all records from the course also or so, if you want to delete all records, so,
what is the command then? Delete all records.

Student: Drop tables (Refer Time: 20:19).

No, the drop table will delete anyway. So, now, there is another delete command; delete
if you give the name of the database right. So, delete from JavaCourse.

1271
(Refer Slide Time: 20:33)

So, this means that it will delete all the records from the JavaCourse. So, it is the
command it is there, we are changing like delete from now delete from JavaCourse as
this is the statement that we have executed from this one. So, it will basically delete all
the records. So, now, the record is empty.

So, there are no records. If you again insert as you see another record will be inserted or
whatever it is there, and if it is select star also it will not return anything because it is it
does not have any record there.

(Refer Slide Time: 21:17)

1272
So, finally, we can delete the entire table also drop table and then. So, this is the program
here drop table here in this program. So, a statement can be executed and then if we
show tables thereafter the drop table program is executed successfully.

So, the drop table will permanently delete the entire table actually and you see there is no
table here. So, the selects and show tables also if you see, so, it does not have any tables
in this way. Now so, what we have learned here is that how we can establish a
connection and then after the connection is successful then we will be able to execute the
SQL statement from Java application.

So, in this demonstration although we have to use the localhost, but the URL as you
know the URL specification that we have discussed during our networking discussion,
the complete specification URL using the protocol and then resource name and
everything if we mention properly including port number etcetera, then it will basically
redirect your aggregation to that particular remote server whether it is connected through
the network or it is the localhost absolutely this is the no issue you can use the same way
actually.

So, in this case, all through remote connection is not possible to establish at the moment
although you could do that, but anyway you have done it, but the procedure is same only
the URL needs to be changed. And you should have the privilege to access your SQL
server using your username and password that also should be ready with you, then only
you will be able to establish any connection and thereby execute any SQL statement.

So, this is for today’s plan and in our next session, we will discuss about how all the
results that basically after executing a particular SQL statement, which will return the
SQL server will be handled by our Java application itself. So, that will be discussed in
our next session.

Thank you very much.

1273
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 55
Demonstration – XXII

I hope you are enjoying our Demonstrations. This is our last demo and this demo is
related to the lessons that we have learn so far the JDBC concept is concerned.

(Refer Slide Time: 00:31)

Now, to in today’s demo we basically going to cover about that not exactly connecting to
the SQL server on console rather program to program only. So, that from the java
application itself how can issue different SQL commands and the commands can be sent
to the server, server will execute the command and then the server will return the results
and all the results will be processed from the application itself. So, everything is
basically included in the application only we will not go out from the application.

Now, so far this thing is concerned, we will see exactly how the different statements can
be executed and then they can be fire to the server. And you know exactly as a process,
their first step that you have to consider is that you have to first create three objects. One
is the Connection objects, the Statement object and then Resultset objects. So, we have
already learnt about how the connection objects can be created and then from your
application how the connection can be established to a server through JDBC driver.

1274
And then we have also learned about in our last session that how the JDBC driver can be
used to have the communication that mean from application to the server some request
can be issued. Today we will discuss, now we are going to discuss about the program;
the statement exhibition of the different SQL statements and then getting the results and
processing the results in the application environment itself.

Now, we are going to discuss about how the execution of a select statement can be done
and after the select statement as you know, it will return a set of records, how all those
records can be processed from the application itself. For example, display on the screen
only. So, far the processing is concerned we will consider simple processing. In the first
example we will consider the data will be faced from the server and the data some
calculation for example, average calculation of all the records will be calculated like this
one. And then we will discuss about how the table can be created and then after the
creation of successful table from the program itself, we will be able to confirm our self
that the table has been created successfully.

And then we will see exactly how the insert command can be executed and after the
completion of the insert command execution we can ensure our self that insert of data is
successfully achieved and then finally, with the repeat for the same other commands like
update, delete, drop table etcetera.

(Refer Slide Time: 03:23)

1275
So, let us proceed for the demonstration. The first program that we are going to demo is
basically how the select statement can be executed. For these things we assume that there
is already a table available in the database. We have already created a table for the
purpose of this demo. The Name of the table is javacourseold. Now as a yeah, so, this is
the table that it is there already stored in the MySQL server and we just applied operation
select statement on this.

For example, select star from javacourseold. So, basically it will execute this statement
and then on the successful execution it will produce a result, those result will be faced to
the application and from the application, we will be able to process it.

Now, here is the program. Let us see. As you see the program here so, few statements as
you know which are obvious like how to establish the connection.

(Refer Slide Time: 04:25)

So, as we see this is basically regarding the connecting to the server. So, as we see these
are the connection is there and then finally, in this statement we are executing the
statement. As you see the statement that we are going to execute select star from
javacourseold. So, from this table it will be there. Now if this command is executed then
this will basically produce a result. So, getResultSet will receive the result of the
statement object and then it will be stored in another object call the rs. So, rs is a result
set object is there. So, mainly three objects as I have already told you involved;
connection object, statement object and result sets. We you have already familiar in our

1276
last two demonstration, we have discussed about it. Now we are going to process this rs
objects.

Now, you know while rs dot next is basically written a Boolean value. So, it will
basically rs objects contents a set of records that will basically receive. So, all the records
it is there; that means, all rows we can say. Now rs dot next is basically till the end of the
rows it will process. So, initially the rows in number of rows is not empty actually. So, it
will the first row. So, it rs dot next is true actually. So, as it is true it will go to this one.
So, rs dot getString is basically for the record in the javacourseold; there is a one field
call Name then another is called Roll and Marks and Grade. So, for the current record the
field value which has the field name Name will be obtained and it basically read as a
string. So, java always read initially as a string and then we can convert into the other
form that is per as per our requirement. So, is basically read the string for the field Name
the value and we store is at a string.

So, similarly NameString, RollString, MarkString, GradeStrings are the four different
field values for a record; namely, Name, Roll, Marks and Grade and then we then we
convert all the values. For example, we are our objective is that once you read the marks
we have to calculate the TotalMarks sum of all the marks for all the records and then
finally, divide by the total number of records and then average will be calculated. So, this
basically is process is basically TotalMarks initially 0 and then Integer dot parseInt
MarkString because it is initially as a string and use this conversation we can convert the
integer value and then TotalMarks will be added. So, these basically reach a record each
time and then read the I mean at the values marks value to the TotalMarks and finally,
the total of all marks will be obtained here and here actually next is that.

So, System dot out dot println Name equals NameString Roll RollString and then Marks
is basically printed here. So, MarkString is there. And then next is basically rs dot last
means is basically when you reach to the last object, so, rs dot last is basically there. And
then number of students is basically can be obtained from the rs object itself by calling
the method getRow method. So, rs dot getRow. So, it basically says the total number of
records that we have read it. So, TotalMarks divided by this total number of records it
basically gives you the average calculation.

1277
(Refer Slide Time: 08:03)

As we see the average calculation is the average is basically calculated here and then we
print this average. And the rest of the thing is for the try, catch, block and everything this
is the customary try, catch, block we have to maintain and so that the program can be
executed in a reliable and robust manner.

So, these basically tell you that how the result set object can be processed. So, in this
session we will mainly emphasize of the processing of the results such that the or
alternatively the all result that will obtain after the execution of SQL statement from the
application itself ok. So, this is the demonstration, hope you have you are able to
understand it.

Our next demonstrations little bit simpler. We will see exactly how the different other
SQL type of statement. We will consider only execution of basic SQL statements and
this will be enough for the begin for the learning purpose only. So, in this case, we will
consider one table already available.

1278
(Refer Slide Time: 08:59)

Now, we will consider the create table right. So, we are going to consider how a new
table can be created and then so, we first see first from the application itself, we will
exactly check that what are the different tables are available there in the database server.
So, in that case we have to issue the command. So, tables and then once the table is there
we can create a new table. So, we just create a new table. The name of the new table
maybe say java course and then after in creating a new table we will again see the
confirmation about that new table has been created successfully. So, these are the steps
that we will follow one by one, but from the java application itself ok. So, here is a
program as we see go little bit ok.

1279
(Refer Slide Time: 09:57)

So, first few part of the program. So, first few part of the program is obvious is basically
connecting to the server using JDBC. So, loading JDBC connecting all these things are
there and then next is you see this is a statement that we are going to execute, show table
command. Now so, the result set will be obtained. Basically show table will see you all
the tables those are there in the current active database in this case may be test database.
So, rs will basically get the result sets includes all the tables those are there in the
database right now.

Now, the prompt is that results before creating the table and here is basically processing
the rs objects is basically doing nothing is basically getting each TableName from the
result sets and printing it on the screen that is all. So, it will basically do these things and
then after the next thing we execute another statement create table JavaCourse.

And as you know this is the full syntax about how to create a table new table, in fact, and
add into the database. So, is a statement execute and after this create a new table is
created. The show table, it is basically send the previous code right after getting all the
tables right; it will basically display all the tables. So, this is the part that ok, it will show
table before the creating and then in create a new table and after the creation it will show
again all the tables. Now, we will see the results that can be obtained from the java
application. It is a as you see here from the java application we are able to see it.

1280
(Refer Slide Time: 11:43)

Now, if we run this program, the execution will flow look like this. So, this is the
program and then ok. So, we just Table Name is a javacourse.

So these basically shows initially only one table is present there called the javacourseold.
Now results after creating the table as you see after creating the table. So, we run this
code again. After creating the table, it basically shows that javacourseold is there and
then javacourse table is there. So, two tables are here; javacourseold the previous and
then new one, it is there and then is basically is that basically this is the output actually as
we see here. So, the statements have been executed. After the execution we can see the
results and that results also through the JDBC itself.

Now, let us come to the next one another example where we are we can see exactly how
we can insert a record into an already existing table. We will consider inserting record
into the table say javacourseold. First we show before execution what is the content in
the table and then we will again issue the insert statement and then after the insert
statement the current data that is there.

1281
(Refer Slide Time: 13:09)

Now here is the course. Here is the obvious course for creating a connection and then
loading the JDBC driver and then, here is basically we creating the statement objects and
this is the first statement that we are going to create is the statement star from java
course. That means, before inserting what is the content it is there, the result sets and this
result set will basically display whatever the records that it returns to us and we will see
exactly before create before inserting a data, how what are the different records are there.

And then next we fire few statements regarding inserting one record at a time. So, here is
inserting first record then second record third record and fourth record. So, if the table is
empty then it will show only these four records. If table contents already data so, then all
these four newly inserted record will be added after the existing data and then this
statement execute select star from JavaCourse.

Basically, same is basically select all the records and get it the result set will receive it
and then finally, the result set will here is a while loop the result set will be process.

1282
(Refer Slide Time: 14:25)

And then result set will be processed and it will display all the records that we have
receive it. So, this is the program. Now, let us come to the execution of this program, so
that you can understand how it is working. So, insert record here.

(Refer Slide Time: 14:41)

As you see here Results Before Insert. So, these basically the table does not contain any
record. So, it basically empty. Then Result After Insert, as we see this is the record first
record we have in inserted this is the second record third record and fourth record. So,
the results have been receives and then they have been displayed on the screen; that

1283
means, we can confirm that the results are now available at the application in itself. So,
this is the example that is an insert, opposite to the insert our next example is update
example.

So, we will just going to update a particular record. As it is always there we will execute
the command that what are the records are there and then we will update a record and
then after the updation we will see whether updation is reflected or not.

(Refer Slide Time: 15:31)

So, we will receive the results after the updation and we will display the updated record
on the screen. So, this is the program flow and here is basically creating the connection
and then executing the statement that what are the records are there. So, the before
updation and then it basically show all the reports and here is the command by which we
execute the update. Here we see Update JavaCourse set Name Debasis where Name is
Debasis. So, if there is any record whose value is basically Debasis as a Name field and
it will basically change into this form. So, this is the next and this is the previous one.

So, it is the updation is there. Only one field value of a record will be updated here. If
there are many records containing the same thing, all records in fact, will be updated by
this commend because it will updated it will scan entire data base tables and then finally,
whichever the condition is match it will basically applied to this one, bind to that, records
and then do it.

1284
(Refer Slide Time: 16:45)

And then find and our next step is basically we are going to we are going to again
execute that select command as we see here select command Select star from
JavaCourse. It basically after the updation, it will receive the results and then all the
results are displayed on the screen and then these are the necessary try, catch formalities.

Now, let us have the execution of this program, it is called the update record. This is the
name of the program that we have given. We are running this program update record
right.

(Refer Slide Time: 17:15)

1285
And this will show the records before the updation. Now here is the execution the total
output of the execution. Here you see yeah. So, here as we see start from here, so, this is
the output started from the screen here after executing the update record. So, Results
Before Update as we see Debasis, Nilanjan, Tauheed, Priyabrata; four records are there.

Now, we have executed update command. Then results after update command as you see
initially, Debasis has been updated Debasis and it is only applicable to this record. So, it
is only one updation is there and then the result is there. So, now, we can understand that.
So, everything is possible from your program itself right and then all the SQL statement
either execution then after getting result after the result is available processing all those
results from the one point of node only.

(Refer Slide Time: 18:17)

Now, our next example; this is the example ok, so, for the delete is common. So, that
whether delete command can be also successfully executed or not. So, first in the same
manner we will first see all the tables; accountants, first records and then we will issue a
delete command and after the delete command we will exactly see the results.

So, here is the program flow, creating the connection. Then we execute the first
statement; Select star from JavaCourse is basically receive all the records and then
display all the results on the screen after the execution of the statement. Then we execute
the delete command; delete from java course where marks less than 66. If there are any
record records or there is any there is a record whose value of the field marks is less than

1286
66 will be deleted from the record and after the execution of this statement we will be
able to again see the records after the deletion.

So, we have to issue another command Select star from JavaCourse, it will get all the
results and then there result will be printed on the screen. The result will be printed on
the screen and then rest of the program is basically try catch. Now, let us run this
program, this program is a delete record.

(Refer Slide Time: 19:41)

And this is the execution results written results. As we see delete record is executed here.
So, Results Before Delete ok; result before delete any way. So, there is a mistakes there
in the program itself is updated. Anyway, so, you read add delete and then these are the
four records as we see. Results after deletion as we see here actually the marks is 75, 85,
65, 78.

So, if the execution is correct then the third records should be deleted from the table. As
you see the first record is there, second record is there, fourth record is there and third
record is no more. So, it has been deleted. So, we have learned about how the result set
object is there.

(Refer Slide Time: 20:25)

1287
Now, so far the JDBC programming is concerned there are few steps that we have learnt
about and all the steps that we have done it and then also the sufficient demonstration we
have given starting from how the MySQL server can be installed.

And then how the MySQL server can be used using the console based mySQL server
accessing. Then connection to the server using the JDBC and how the JDBC driver also
can be downloaded and it can be archived and then the command can be executed. And
then we can after the execution of command how the results can be obtained or receives
into the program and the program can process these things. So, this is the demo about the
our last third say part of the demo, so for the JDBC is concerned and this is the end of
our demonstration session as well as all the demonstration.

In this course we have covered around 20 22 demonstration and then other around 28
lecture slice in other. So, basically almost 50 percent demonstration followed by the 50
percent theoretical discussion, so that all the theoretically leaned concept can be
complimented through the demonstration.

I hope you have enjoyed the course and the demonstration. In our next section, we will
discuss about some java projects that projects can be handled by you as a single team
member or as a jointly with many team people involved. Now we will discuss the
projects and then we will basically see exactly how far you have leant and then whether
we can solve any real life application sort of things in this ok.

Thank you very much.

1288
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 56
Case Study – I

So, this is the last week of this course, it is the 12th week. Now, so far we have learned a
lot of regarding the Java Programming. And it is our now time to exercise, so practice
matters. In any programming, language learning, you can improve your skill only if you
can indulge yourself into doing some work, and then practice and practice.

So, considering these things, we have planned few projects that you can take off, so that
you can deal the projects, try to implement, and then ok, then you can learn many more
things, which basically is not possible to learn, only just using or attending a course
through video course or whatever it is there. So, a project is very important. So, now we
will discuss in this week, a bunch of projects will be discussed, how to solve all these
projects. And to solve these projects, what are the other skillset that you should have, all
these things will be discussed one by one.

(Refer Slide Time: 01:33)

So, let us have the first projects that we are going to discuss about. It is a data entry
system. So, by the name you can understand that, we have to develop one software by
which a data can be entered. Now, obviously data entry should be related to a certain

1289
application. So, here we will consider the application regarding the data entry for the
student’s record.

(Refer Slide Time: 02:01)

So, basically for this project, you need basic concepts about encapsulation, inheritance,
and then information hiding in the form of access specifier, the concept of package, and
little bit GUI programming. As you can see, we have to develop one program, it is just a
mini-software we can say. If you can develop these programs, then at a later stage any
large scale program also can be developed, it is similar to the same application.

Now, data entry application is huge, it is an everywhere actually. And this program is a
simple one that we have to plan, so that you can do it, maximum time that you can think
for solving this project only 1 month. So, in a month, in fact, for some students, it will
take only 1 week in fact. Anyway, so at the maximum, you can spend time to implement
in a month only.

1290
(Refer Slide Time: 03:11)

Now, let us discuss about the idea of the projects. Here the idea is you have to declare a
class. The name of the class, you can give as a student. This is because we are going to
enter the record or information about a student, so there should be a class declaration for
that.

Now, this class should take into account, the different varieties of students. Students may
not be the uniform only; there may be different category of students. Like some students
may be studying only undergraduate course, some students may be postgraduate courses,
namely M.Tech or Ph.D., there may be some higher than the PG course also, say post-
doctorate fellow or scientists like. So, we have and obviously as you know, so data entry
for UG students may not be the same the data entry for a PG student like a research
scholar. This is because there may be some methods which are required which does not
required in case of another category of objects.

Then we have to decide a procedure about data entering from the keyboard, so it is first
we will consider about console-based data entry from the key keyboard, how a user can
enter the keyboard, it will give a prompt that enters the name of the students. Then from
the keyboard, you will give the data, and then return. Then again it will prompt for what
is our roll number, you have to enter this kind. So, this is the console-based test entry.
Usually, you are familiar with this kind of entry, when you are learning about C
programming or something like that. Anyway, so this is a very trivial job.

1291
And then finally, we have to do the same idea using some different way. A different way
in because whenever, you use the console-based test entry; the data usually stored in
your main memory and so long your program is in execution, the data will be available.
However, if you quit the program or your system is goes off, then your data will be lost.
On the other hand, the data that you entered even if it is a console-based also, you can
pump it into secondary storage, so that in a file the data can be stored.

So, here data entry also very important that how you enter the data, and where this data
ultimately goes to, so it is basically a file. And then finally, we will consider about a little
bit sophisticated data entity, it is not console-based. It is basically, we can develop a GUI
windows program which allows a user to enter the data prompt will be in the GUI itself.
And then data once it is entered from the GUI, it will directly go to the file. Anyway, so
this is the idea about this project.

(Refer Slide Time: 06:09)

Now, let us have different steps. So, it is better than if the project is of large size, we
have to solve this project in a facet manner. I am giving an idea about how in phase by
phase, this project can be implemented. So, the first version of the project that we have
planned here that console-based data entry. And for these things, we have to have the
class declaration.

So, encapsulation of all the class two of the students based on inheritance also. And all
the class that you will build based on this class declaration, they should be stored in a

1292
package. Because, whenever the large classes are involved; the better idea that you
should not store all the classes in on directory, instead of you could you should maintain
all the classes in a several directory in a different directory.

This will basically help to manage the program at a later stage. It is basically required for
either modification or up-gradation to a latter version like, so that is the package concept
that you should exercise from here. So, all the class declaration that you will give, it is
basically in the form of a package. I am giving you a quick look at that how a class of the
students will look like.

(Refer Slide Time: 07:41)

So first, you have to decide a base class, the name of the base class that you can give as a
student. And then student base class can includes the fields and methods which I have
mentioned here as we see here. So, these are the different methods and fields not limited
to this one, you can think something else also that may be more suitable. I have given
here for your just a hint.

Now, so this is the base class. And then as you have told you, the class may be different,
then all students belong to this class student actually. And then there will be a category is
that UG, so UG has again different fields which are not there or there may be some
method, which needs to be overwritten there or the method you can declare here, you can
reuse to define these method here. So, this is the concept of inheritance that you can
follow is a single inheritance Java provides only, you use this one.

1293
And also some other data that you can include which is not here, so result UG. And this
result UG itself is another class ok. So, a course may be another class, because a course
can include some other, which is called the subjects also. Course under this course
subject 1, subject 2, subject 3, and for each subject again, they are maybe marked 1,
marks 2, marks 3. So, this basically is a composite subject.

Now, it is up to you up to which details level that you want to go. So, it is basically an
example of a nested class that you can do, even the class also. All those classes can be
declared in the package, and I can use it by means of import and others. So, this way the
bachelor class can be declared, like master class can be declared, Ph.D. and scientist
class can be declared. And they are a different class because it has certain fields or
methods which is not there either here or there, so that is why the different class
compositions are to be taken into account ok. So, this is about the different class
concepts that you should follow, and then store them in the package as we have
mentioned that student package it is.

(Refer Slide Time: 09:51)

And then our next step that you should after declaring the class and everything, you have
to create the objects. There may be n number of students can be created belongs to a
particular category, you can create the array of objects. And for each array of objects,
you can read the field values, the member elements from the keyboard, so that is what
the idea about.

1294
And then once you read it, whether you are reading is successful or not, then you can just
define a method the printRecord, so that all these things the data entry through the
console, again you can plan as a separate class. And all these classes can be put into
another directory let the name of this directory that is the package as an entry.

(Refer Slide Time: 10:37)

So, this is the second part of this first phase, namely entering the data. And then here is
the next phase of this is storing the data. As you have seen that data that you have stored,
it is stored in the objects only. And those objects are stored in an array, and this array is
basically in primary memory.

Now, so you have to store all the objects into a file that means the values that is there in
the different fields of objects should be passed into file. So, in this case, you can use the
IO stream handling more basically, you can file handling the class, and then use it, and
then you can do that. And then you can save this class for the data entry in another
package application. And this will be your main class actually. The data entered in this
case is the main class. So, in the main class, you can use all other class that you have
declared in the different packages like students, and then data the entry package it is
there. So, this is version 1.

1295
(Refer Slide Time: 11:49)

Our next version is basically; so long we have entered the data, and then store it in a file.
Our next version is basically data entry 2, so we can store earlier ok. In the next last
version, you can think about that do not store the data into any file. Now, in the next
version, we can store the data into a file. Everything is same only the thing is that the
input from the may primary memory will go to the file memory actually.

(Refer Slide Time: 12:13)

And then this is the version 3, the third phase of the program we can say, here you have
to define a GUI for data entry. Now, here again, the data will be entered from the

1296
graphical user interface that means some text field, and then some buttons will be there.
All those button also needs to be handled properly and then keyboard handling event
should also be implemented. And then once the data is entered one by one, it will
basically go to the file again.

(Refer Slide Time: 12:47)

Now, I am giving a quick lookup, how a data entry skill would look like, it is a very
simple one, you can use the AWT package for these to develop it. And in this case, you
have to have a this is basically the frame, this frame contents level, these are the level.
And these are a text field, and this is the button, and these are another button-like.

So, these are the basic components in addition to there is also some tab. So, if you want
to enter the data for the UG student if you click it, then all the this basically the
composition will change according to the data, those are relevant to the UG. Similarly, if
you end tab this one, then this text field actually will change according to the different
field which is relevant to this data.

So, this way you can have the tapped text entry system, and all this can be done using
even java swing also, AWT also. If you use java swing, absolutely this is very good;
otherwise, you can use also AWT. Anyway, so this is the way about the data entry that
can be done. And a simple program that you can think about, and you can take this as a
project. So, this is about the first project.

1297
(Refer Slide Time: 14:01)

Now, I am coming to the second project. Now, those are the students, who are having
some computer science background. This project mostly seems to be I mean feed for
them only, because it needs some computer science background actually. But, other
people also can do it, but in that case they have to learn some data structure related and
algorithm related concepts. So, it basically this program is a computationally bit
intensive, those are basically fond of solving problem, it is basically good for them.

(Refer Slide Time: 14:39)

1298
Now, let us have the idea about. Now, before going to the idea, I just see, I just
mentioned that what is the skill set or the programming confidence that you should have
core programming that means, all the control structure language reference and
everything should be there. Bit encapsulation, inheritance also can be a used here,
package concept is there, polymorphism, scope rule, and then finally also the graphics
should be here so that you can exercise graphics. But, here actually a little bit about
AWT only, and not so much details graphics, it is there.

(Refer Slide Time: 15:15)

Now, let us see what is the idea of this project. Now, this project is basically all about to
create binary trees, then sorting algorithms, and searching algorithms. So, the binary tree
is concerned as there are many binary trees, but we can limit it to only a few that you can
do. Even if you can do only one also that is good, not necessary to solve all the binary
trees in fact, but it is advisable that you should try to hands-on all the binary trees
actually. So, this will basically give a lot of programming grips, how it can be there.

So, here we have mentioned binary tree, binary search tree, AVL tree, and heap tree.
AVL tree is also called the height balance tree. So, any good book on data structures that
you can follow, and you can have the information from there. And before taking up this
project, you should have a good familiarity with all these concept trees algorithms,
sorting algorithms for searching like this.

1299
Now, so for the sorting algorithm is concerned, I have mentioned a few popular sorting
algorithms which are basically easy to code actually. So, heap sort, quick sort, merge
sort, bubble sort, selection sort, insertion sort etcetera. And then all the sorting and
searching algorithms that you have developed, we will go for visualization. Even the
binary tree construction also, I will come to the concept of visualization later on that
means, each process of the algorithm can be visualized, so that anybody who does not
know about how exactly the sorting takes place, they can see the visual progress. And
then understand about the technique like. So, this is about the idea.

And here one thing you should note that java does not support pointer concept. And you
may think that binary tree and everything how without a pointer, you can implement.
Absolutely pointer is not required there, because you can maintain the elements that are
required to be used in a tree can be stored in the form of an array.

So, array-based tree implementation is quite possible here, and you should do that. And
for this array, you can use the data that package java.utit.package from there lot of other
data structure, array, least, vector all these things you can use here. No need to defined or
the array of your own which is in a primitive way, all the API based the least can be used
for this purpose.

(Refer Slide Time: 17:37)

Now, the first version in the first phase that you should do is basically create and process
binary trees. Here you have to implement the algorithm, those are there which are

1300
available in the book of any book of data structures Binary Tree, Heap Tree, Binary
Search Tree, AVL tree and that is binary search tree, and all these things ok.

And then whenever you declare you have to basically for each class, you should declare
the different class in fact. For each tree, you should declare a different class in fact. And
then this class should include the different fields as well as the different method as I have
mentioned here, one field may be data. And data can be stored in the form of an array of
integers if you want to build the tree for an integer data or if you want to build the data
for a string, say an array of strings like this.

And then here the methods that you have to implement build tree, insert data, delete data,
search data, traverse data, draw data. Draw data means basically for the visualization and
others. So, all the classes that you will build, you can maintain them in a package. Here I
have given the name of the package, I will go. And you can note that whatever the name
of the package, you should give it should be in small letters. No capital letters, usually
advisable to give the package name. This is because in many operating systems, the
name of the directory is not case sensitive. So, capital letter, small letter, mixing the
package name is not usually allowed.

So, you should give the only small letters like a, and preferably as a three to four
characters max not more than that also. So, this is the package that you can develop. This
package algo, we will include the implementation of all possible trees, implementation
includes the different methods and fields, and also hierarchy you can mention, so that
means, you can make the basic tree and then inherited into the different tree structure
like a binary tree. A binary tree can have a special property binary search tree, heap tree
is also another kind of property.

So, there may be an inheritance from the tree binary tree, there are one inheritance is a
binary search tree. Another inheritance may be a heap tree. Then AVL tree is a special
kind of binary search tree. So, AVL tree can be considered as a subclass of binary search
tree-like. So, you can plan that how the hierarchy that means, encapsulation or
inheritance tree can be considered so that with a minimum number of code or code reuse
a using the method of code reuse or you can use it. So, this is about the second part first
part of the project.

1301
(Refer Slide Time: 20:27)

In our second part of the project, who have planned to implement the sorting and
searching algorithms. The sorting algorithms, again it requires a lot of fields. So, for each
sorting algorithm, you can plan one class. And this class will include the appropriate
fields and the methods. And again like the tree also, you can maintain an inheritance
structure, so that the different course that can be used, it can be store the in a general can
be stored in the base class. The other subclass can have their own codes and own
methods like this.

And then also the sorting searching algorithm can inherit that means, it can extend the
package the class those are there in algo package also, I mean trees so because some
trees also need to implement some sorting algorithms. For example, if you want to do the
heap sort, so it is basically needed the heap tree. So, this heap sort extends heap tree, and
then all the classes those are there can be utilized there.

So, if you can put into another package algo or in the same package also no issue, you
can do that. And the methods, you can do some open, insert, remove, save that mean,
after sorting the data can be saved. The opening means, you can open from the raw data
input data, and then remove also. If you can eliminate one item from this data sorted an
array or it can insert also, but insertion should be in a sorted manner. All those methods
also, you can implement for each sort of techniques.

1302
And also another method time is basically how much time that a sorting algorithm
required to complete the sorting task or a searching task. So, the time also you can use as
a method for a particular class. And all the implementation under this category can be
put into the package algo, so this is the second phase of the project.

(Refer Slide Time: 22:27)

And the third phase of the project is visualization and creating native API. So, in this
process, we will have a total visual impression of differently. For example, you are
building a tree. When you insert one single node, it will give only one node. When you
add another node, it will go to that tree, whether it is a left child or right child. So,
accordingly the tree will be built. And then the building process can be visualized one by
one as the things are going goes on. So, this is the visualization process.

And this process again to do these things, you should take the help of graphics package,
this which is there in AWT java.awt.packaged only graphics class actually, which is
defined in java.awt.package. And all the implementation related to the visualization, you
can put into some other package or you can put in the same package also, because it is
related to the sorting, searching, tree generation, and then visualization and everything.

Now, if you build one such package, it basically gives an idea about how a see a user can
develops their own package, which can be treated just like java APIs like say java.util or
java.io like this one. So, all these packages you can use, and then import also. And then
for further development, suppose in some other application, you need to use all the

1303
sorting and searching algorithms. So, import this package and use it. So, this way the
code reusability can be enjoyed at the maximum level, and then you can use it.

Actually, the software engineer or any software practitioner, they follow this kind of
process. They develop the code, code each stored or architech. And the archive code is
used or reused for development, development or for the modification whatever it is there.
And whenever you write the code, and then all the system and everything gives sufficient
comments, so that all the comments at a later stage if any other successor to you, who
can be given the responsibility to develop the program they can use it, so that comment is
very much essential. Every line, every statement, every class should have a good
comment and annotation, so that is will give you an idea about, how the two different
projects can be developed. And I hope if you can involve yourself to implement all those
projects, it will really improve your skill.

Thank you and best of luck.

1304
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 57
Case Study – II

So, this is another project that we are going to discuss. We have discussed two projects
in the last session. In this section we will discuss three more projects. All these are the
small projects in the same category like, but as you see as we go from one session of
projects to next session of projects, the complexity will be little bit increased. So, all the
projects that you have we have discussed we have learned about in the last session it is
simple to solve that again the complexity will be little bit increased.

Now, in this projects we will again consider that the different flavor of the Java
programming can be used, utilized, so that you can really along much more about while
you are involve in working with the project. Now, I will just discuss about the third
project, here drawing images on canvas. Probably you have already have an idea about
how the scribble can be there, so that user can draw some image using mouse pointer or
like this. But here it is not exactly the same thing. Its bit different thing, but here the idea
will be little bit in a phasor manner and then you can think about it.

(Refer Slide Time: 01:32)

1305
But if you can solve this problem definitely the lot of other different aspects of the
programming like say multi-level inheritance, polymorphism, graphics, applet will be
cover. So, this projects aims, so that it can cover all these concepts in Java programming.
Now, let us have the idea about this project.

(Refer Slide Time: 01:48)

Now, this project is basically drawing an image. The image is basically consists of the
several geometrical objects, a point may be a geometrical object, a line may be, a
triangle, a circle and ellipse or any polygon or some rectangle square like this one. Not
only this geometrical object they can be filled with different colour, different style, their
border or line can be also different colour, different style, like, like, like. So, this is
basically the way a geometrical objects can be drawn and again if you see an image an
image is nothing but a collection of several geometrical of a place in their appropriate
positions. So, this way it basically completes an image.

So, here is an idea about that how the different geometrical objects can be defined, so
that you can use to draw an image of your own. So, for these things our plan is to create
a class called the geo object class. We will discuss about the class structures in details
when you will discuss about how to solve this problem, how to deal with this project.
And second thing is that, if you create the geometrical object using this geometrical
objects how we can create an image that can be stored as a class structure and whenever
an object is created of that class; that means, an image will be created and that image can

1306
be again on execution it can display on the screen or it can be stored, later on you can use
it redraw these things these one.

And then the final stage of this project you have to do the animation. So, a circle if it is
there which is present there, initial it is a static, but you can move it; that means, a circle
can move from left to right or top to bottom from one any direction to another direction
like this one. So, all those things also can be done. So, this project is basically we will do
all this things together. Now, let us see how step by step we can do towards this project
implementation.

(Refer Slide Time: 03:46)

So, first thing that you should have the repository that all the objects of their different
type and how to draw everything should be defined in your own class declaration. You
can give the name of this class as a GeoObject.

Now, once this class is declared. So, this class and then an object of this class can be
used to create your own image. Here is an example about how an image will look like.

1307
(Refer Slide Time: 04:13)

As you see in this example and image consist of many structure say suppose this is the
one rectangle and this is also another rectangle, but the difference from this rectangle to
this rectangle their positions, their style. Here for example, the line by which this
rectangle is drawn with no colour, but the filling is some other colour, here filling is
different colour and this is the circle, this is also another circle. So, this the different
geometrical objects composed an image. So, this is basically we can say that image.

Now, these geometrical objects can be created by using any one class which you have
already defined belongs to the geo object class and geo object class can be obtained by
means of multilevel inheritance, multiple inheritance as the idea it is given there in the
form of a inheritance tree. And such an image therefore, is a in the form of a class not a
bits farm or image or not a dot jpeg form or pdf form or i m g form like the or p n g form.
It is just simply a class. And this class can be executed, so that you can see the image
actually. So, this is the idea about the painting an image on a canvas. And in the canvas,
here is basically a frame or panel you can think about in that case a little bit awt units to
be followed here.

1308
(Refer Slide Time: 05:50)

Now, so this is the idea about how and image can be created. Our next idea about that
how the movement of an object on the canvas can be added into this one; so, this is the
second phase of your project here you can create any one image initially you should
consider only one a simple image may be a circle.

Now, animate the moment of the image. Now, here you can we have only known about
the banner applet that we have discussed while we are discussing about applet. So, there
we have also made it. So, the movement can be achieved by means of repeated use of
update and repaint method that is there. So, I will I rather advice you to do it using an
applet because it is easier. Later on the same thing also can be added into any frame or in
a panel or in any other container class using A W T or Swing.

And better idea will be it is little bit difficult, but it is not as such so much difficult also
that it is moving of a geometric object is easier, but moving an composite object; that
means, a group of object may be say one circle and another box can move together. So,
that is also can be done.

So, if you do it is basically moving an object it is there. For example, you can draw a bar
using say few straight line and then point and then dot like and then the same can be
moved together, so that it will appear an animation that a bar is moving like. So, this is
the idea about moving an object on an image canvas and you really will be able to enjoy

1309
it if you can implement it, but it will little bit patience and then confidence is also
required.

(Refer Slide Time: 07:25)

Now, I will discuss about the control movement of an object; in the previous fetch we
have declared the movement in one direction only, but here you can fix that in this
direction you can move as a simpler version you should take in a simple way that is a
control movement in a specific direction. As I have mentioned from right to left or left to
right, top to bottom or bottom to left like this.

So, an image is anywhere then you can give an instruction is an even can be generated.
So, that if you click it then it will start moving and in a particular direction. So, here you
can just think an applet program for that and then view of the applet you will look like
this. So, this is basically the one area of the canvas we can say and this is basically the
control area.

1310
(Refer Slide Time: 08:07)

So, if the user selects up then what will happen this object will move up and then go
there again come here. So, this is way it is just in a movement the in this direction. On
the other hand, if it is the right then it will move from this direction to this direction and
come here again this direction this direction and if you click again it will stop its moving.

So, here if, so if there are many other objects also you can select which objects you want
to peruse the movement. Out of many objects some objects can be selected there is a
choice, in this choice also it can you can give that movement of few more. So, if you
choice a circle then you can select left, circle will move then another object may be
ellipse and then move right. So, right will be there and so on, so on.

So, you can just simply control the even handling mechanism here. Although the simple
even handling mechanism is there because here how many is a choice list and then this is
the four buttons are there and you have to just, ok, button handling mouse even handling
routine needs to be implemented there. So, you can try it and then it will given idea about
how nice a program can be there which basically use for animation purpose also, but at
this is at just for the beginners.

So, this is the fourth project in the today in this session second project, but all together is
a fourth project that this is a secure message transmission. This is also an very interesting
projects. Then you obviously, this project needs certain what is called the technological
concept. Again this project is good for the students who are from electronics electrical

1311
and computer science background because little bit security aspect learning is there
security means how the cryptography, encryption, decryption and all other methods are
there.

(Refer Slide Time: 10:16)

Now, let us see what are the skill set that you should have or the confidence level that
you should have; you should be a good core programmer. That means, you know exactly
good Java programming, syntax and others. Then GUI programming is also required,
you have to develop certain graphically user interface, windows is required and finally,
you should have a very good knowledge about the networking.

So, it will blend all three things together in these projects. So, if you can implement these
projects so, this project has its own value of course, and apart from this you will be able
to have a good confidence level, so far all this key concepts in Java programming each
concerned.

1312
(Refer Slide Time: 10:56)

Now, let us have the idea about these projects. Now, this project is basically as I told you
few technical things are involved, who is I have highlighted here you should have the
encryption, decryption and then cryptographic key. And then also you should have some
other ah networking all these things that is there.

Now, here is the what is the idea here? The idea is that a message whatever it is there
that can be encrypted. Encrypted means it change, so that nobody can read it even open it
they will not be able to get the meaning of this. So, this is the idea about the encryption
and whenever you want to send a document say suppose the document written in war or
pdf, I have no problem you can consider simply a text document in a R T F for whatever
it is there. So, using text editor, you can use it.

Now, the document will be encrypted from the sender. So, sender will do the encryption.
And to do these things sender should use one key it is called cryptographic key.
Similarly, the same document whenever it is received by another receiver, a documents
will be decrypted; that means, converted in the original form and for this conversion
called the description again we need some keys. May be the same key or different key
now there is a concept that I am going to discuss about how the same key or different
key can be used to use the encryption and decryptions are there. So, it is basically the
idea of the cryptographic key.

1313
So, if you do not have any idea about encryption, decryption and cryptographic concept.
So, you should go through some elementary documents that will give you enough idea.
You do not have to do the research in cryptography rather you have to know exactly
what is the different methods are there, so that all these methods can be used and then
you have to implement all those methods in a Java programming.

Even in the network in the internet also lot of readily available programs are there, even
inputting Java also there you can download this programs. So, you can use, it you can
little bit modify it and you can utilize in your program also. Absolutely, there is no harm
for that.

(Refer Slide Time: 13:18)

Now, I will discussed about the steps that you should follow. As a first step we have to
decide about the cryptographic key. So, there are two type of cryptographic key, one is
called the symmetric. Symmetric cryptographic key means the key which is used for
encryption the same key will be used for decryption. So, this is called the symmetric key
cryptography. In this case both sender and receiver should have this key and an
algorithm for both encryption and decryption.

On the other hand there is an another method that sender we will use one key which is
private to the sender only sender knows only, but receiver does not know it. On the other
hand, sender will communicate to each counterpart by a key it is called the public key
and using this public key the receiver will be able to encrypt it.

1314
Now, there is again different type of algorithms are for possible like say RSA algorithm,
DSA algorithm, like. So, using all those algorithm the asymmetric key cryptographic can
be there. Here again you have to know exactly how the key can be generated both the
two keys, public key and private key, those are not same different and they can be shared
among the two parties also and all those things are there. And their again keys sharing
key generation for asymmetric there any protocols. For example, Diffie Hellman
protocol, electric of cryptography protocol, DSA protocol, so many other protocols are
there. So, you have to little bit learn about all those things methods are there techniques
are there you have to implement in your Java environment.

And then you can develop all those things; that means, all the algorithms for encryption,
how the key can be generated, how the key can we shared, all these things you develop
as a program and you know in Java program means is a class all these class for you can
stored in a package. Let us give the name to this package as a security.

(Refer Slide Time: 15:14)

Now, here is an idea about how your framework will work so that you can develop
ultimately a system. I have just given a picture for your own understanding. So, here a
sender who wants to send some document. So, this is the document. So, basically sender
will use a key, that is a cryptographic key whether is a same or different that you think
about then encryption this algorithm.

1315
So, you need how this key can be generated how this technique can be done. So, these
two methods you have to learn it, and document can be any document word document or
note pad document or pdf document or image document, absolute no issue that algorithm
we will take care about it.

Now, so this algorithm take a document with the help of key will create one file it is
called the encrypted file. The same file will be sent to the net. So, there is a socket
program you can think about. So, a socket we will take this encrypted file and then
socket we will send it to the sender, receiver. So, this is the receiver, receiver has another
socket program at his machines. So, these two machines are different. They are
connected through the net. So, these are the two socket, one the receiver socket and then
server socket we will just ok, will be used for the communication purpose and any
protocol datagram protocol or TCP IP protocol you can follow through transmit
whatever the large document may be.

Now, this then they at the say receiver end there is a program or algorithm is a class
program, Java program you can say which basically decrypt the document which has
been received. And so, and for this decryption another key will be used cryptographic
key may be same or different whatever it is there. So, using this key the algorithm will
decrypt it and then finally, it will reach the, receive the documents and this document we
will be opened by the user.

Now, so this is the idea about the system that you have to develop and you have
understood that, you have to use it programming core programming and bit networking
also involved and also graphical user interface also needs to be there. And in the version
one you can just simply then generate the cryptographic key and in the second version
you can do is basically the graphical user interface.

1316
(Refer Slide Time: 17:34)

And here how the graphical user interface you will look like I have displayed here. So,
there will be just this is the view of a GUI windows program, and here if you click the
upload document it will basically just ok, go to the browser and then it will select the
directory and in this select the any file can be selected and then open it.

So, it will just display that this file has been successfully selected. And then you can
keep the encryption algorithm button it is if you click this, so it will basically follow the
algorithm and also it will take the cryptographic key and then it will be basically create
an encrypted file and encrypted file can be again send. So, you can see the ID, you can
give the URL address or local machine number or such thing and if you select it thus it
will go to the send receiver. The receiver window; that means, this is the program that
we have discussed about is a GUI program. It can be embedded in a socket and then
socket this is the GUI is basically punch in a socket program actually.

And this is another socket program at the receiver end. Receiver end once this program is
there then it will basically whatever the message that he has received will be there. So,
this is basically one inbox sort of thing. In this inbox he can select one and then he can
select this decrypt. In this once this encryption is then is a decrypt. So, these decrypt we
will basically convert the encrypted file into decrypt decryption one and then finally, it is
open.

1317
(Refer Slide Time: 19:16)

So, these are the two windows, at the server size, at the sender size, as the receiver size
needs to be implemented. So, here windows programming, also socket programming and
then the algorithm to be implemented together in at the both end. Now, then the message
transmission through network the network implementation is to be there and you know
exactly how the networking is possible using this one, two sides of client can be there
and then once the receiver receives a message it will send an acknowledgement to the
sender.

Now, all the system that you have developed is stored in a secure file better you can put
into the jar file and this jar file is installable in any other users machine, and using
installation of these jar file or using these jar file any people can send the document to
anyone and any people also receive the document sent by someone and then use it as an
encryption and decryption also.

Even you can plug in with your email system also. So, before sending or attaching, you
can encrypt it and then the receiver also can decrypt it using your same program. So,
plugging with your own program with the other program also possible that is another
lessons that you have to learn about it, anyway. So, forget about the plug in and others
you just simply used for a standalone system that is there.

Now, let us discuss about another projects is a fifth project. And as the name at the title
of the project is basically you have little bit idea about the bank transaction while we are

1318
discussing about multithreading in this course. It is basically heavily used based on this
concept transaction system, but using multithreading, but in addition to this threading
also it will considers few more Java programming aspects like GUI programming also,
networking and then JDBC.

(Refer Slide Time: 21:11)

So, this is the another little bit complex program or heavy program compared to the last
four program that we have discussed about because so many skill sets are there. If you do
it one by one then it will basically all this projects are planned in that order only. So,
slowly as we go from next project the complexity will be little bit high. Anyway, so this
is the project where you should have the knowledge or learning capability about all these
four aspects.

1319
(Refer Slide Time: 21:47)

Now, let us see what is idea of the project. It is very simple idea, as you know so for the
banking or any finance organization there is the one server which maintains the database
and the database includes the records of all the customers. So, basically customer ID, the
account number, the customer name, customer address, accounts and also the history of
transaction all these things are there. So, you can plan a database for that. A tables that
are relevant to this one and then so, you have to prepared one database for this.

Anyway so, a bank we will maintain all customer records in a database server. And then
customer can access his accounts online. Online means login password should be there
by which the customer will should be first authenticated, once the authentication is first
his information will go to the database and accordingly database will give that different
facilities or the operations like balance enquiry, or if you wants to deposit amount or
withdrawal amount and everything.

So, here actually no physical money is involved, the logical some things is there because
you have to just practice it how such a things are there and whenever the hardware can
be interfaced with this physically it can be there. In actual cases the banking system will
be there any way. So, it is like this one.

1320
(Refer Slide Time: 23:14)

Now, let us see the different steps that you should follow one by one, so that you can
implement this ah project very comfortably. So, first you have to develop one database
server you can use in this course MySQL, other then MySQL in this SQL or oracle
server also anyone, no issue you can use it. And JDBC also needs to be archived in your
program jar file is there available we have already discussed about how the database
JDBC connectivity can be done, here you can use it.

As a programs, so far the programs are concerned, so in this project we have to develop
for sever sockets. Server socket means this will basically handle with the database and
everything. So, that can be considered as a concurrent server because this server should
be ready to receive many request at the same time and therefore, it can process. As a
result of concurrent server you can implement a multithreading concept here. So, several
threads are to be executed whenever there is a request received from a client in a distance
from the distance location.

And then there will be another socket programs for the customer. So, the two sockets
here is the customer size. So, customer can be from his own machine or from his own
mobile, can run the sockets, the sockets will run then through the sockets customer can
place the request and then accordingly it will be executed.

1321
(Refer Slide Time: 24:43)

So, these are the things are there. Now, here again a little bit GUI components also
involved. As you see here, the first GUI interface for the login and password which will
look like trivial form as you are familiar to this one you have to do it. So, once the login
element is there login ID and then password is entered and then press 1. So, if the login
is successful it will basically can go to the next step that it will basically see that what
operation you need.

So, after these things it will basically, once the login is successful the online banking
system will appear to the user and if it is a failure it will deny to access it. Now, here
again balance enquiry if we click the balance enquiry it will just ok, because login
account number and everything fast after authentication is done. So, it will ok, connect to
the server and then that server will basically consult with the database server, get the
information and then display it here.

And then once it is there the next will be may say withdraw. Say similarly, withdraw it
will basically ask about what amount you want to withdraw. If you give in, so then after
the withdraw operation is successful it will give a message successful message. And then
the deposit, similarly deposit it is there if, so after the successful deposition it will give
the balance and all these things are there.

So, you have to just simply develop this kind of screen with dialogue box and you have
known you have learnt or using Java swing also how all those things can be developed.

1322
So, you just even handling, mechanism, the interface you have to develop and then it will
just do the socket programming, the networking and then JDBC the database handling
are to be there.

(Refer Slide Time: 26:26)

So, this is basically the idea about this one. And then once you develop this program and
this is a particular program whether you see whether this program is a very much robust
and then perform perfectly as it should be here. So, here are the different test that you
can accomplish. So, that you can just run the program, several sockets, client sockets
from the several points and then execute and try to access the database as well as the
concurrent server simultaneously.

So, here I have mentioned with a single deposit with multiple deposit, both say deposits
as well as withdrawal at the same time and then there are so many other variation that
you can do, so testing. You can include in your friend also in your the in this testing, and
then you can do it and then get the results it is really if you can do it and then we it will
improve your confidence like anything.

So, these are the things that we have discussed about. The three projects in this session
and then best idea would be if you can do alone, so do it. If you cannot then best idea is
that you can do as a team, right. So, you can include some of your friends into the team
and then discuss how to solve it, what to do, what are the difference are there and then
you can do it together. First two programs you can do alone, but whenever the

1323
complexities because different components are there, better that you can do in a two
manner. And then teamwork is very important because whenever we have to use in a
software development firm right you have to work as a team. So, from this time onwards
you should practice these things.

So, thank you for attention.

Thank you.

1324
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 58
Case Study – III

(Refer Slide Time: 00:35)

Let us continue about a few more projects using applying the concepts that we have
learned in this course. Now, this is the third case study, here also again we will discuss
two projects. The first project that is we are going to discuss about the systematic design
towards an advanced calculator.

Now, we have already had an idea about how a calculator can be designed. And now we
discussed about how the same can be applied to develop a more advanced calculator. So,
the first phase that we will consider about designing a simple calculator using the simple
features, this is the beginning of the projects. And then we will slowly try to add few
more features, for example, few more functionalities, more operations, equations, others.

And then finally, we will develop an advanced calculator having more complex
functionalities like this say using the bracketed expression, and then some others also.
And then scope of customization, setting the styles and everything.

1325
(Refer Slide Time: 01:38)

So, let us discuss about the flow of the projects, the different steps or the versions of the
project. In the first version, as you are very much familiar to this kind of projects, and we
have developed this kind of project using applet, you can do it is in the using simple non-
applet program also using swing or AWT as well as anyway so both applet version and
then non-applet version program also can be written for this purpose.

So, this is very simple. We have already had an idea about that this is the few buttons are
to be there, among text field area will be there, and then the user performs any
operations. Those operations are basically binary operations, like no unary operation. For
example, square root, cube, log, all these things not involved here. So, it is simple.

So, here you have to just create the layout, and then include certain component into that
layout. And then finally, we have to add the listener methods, so that events can be
handled. So, there are many programs, you can find on the internet. So, for that are Java
calculator is concerned right, you can check all the programs, those are available try to
understand those programs.

In this course also, we have used several programs for Java calculator, as a Java
calculator, you can nurture those programs also. Then you will be able to learn it, then
you can try to modify of your own like say setting the different fonts or the button color
or whatever it is there, so that you can exercise, whether the change that you have
desired, whether you can reflect into the program, and you can see it or not. So, this will

1326
basically gives a lot of practice. And then as the beginning of the design of a calculator,
this is mass structure.

(Refer Slide Time: 03:29)

Now, our next part is basically, if they're a little bit improve version. So, this is the
simple calculator, we have already learned about, after learning the simple calculator.
Our next step, this is the basic simple calculator as you see and then we will basically
change this into this one, you can see the difference. Here the difference is basically as
you see the difference here is basically add few more buttons as we have mentioned here,
so few more buttons we have added here.

1327
(Refer Slide Time: 04:07)

Like say C buttons C means clear, then is whatever the previous calculation, we can load
into the memory, and then read or memory can be clear. And, here we have used one
more functionality say square root calculation or square calculation, whatever it is there.

Now, I can advise you to have this is a usual symbol, not the square level. The square
root symbol can be put into there also ok. So, we have check that ok, after adding this
one, how the same calculator can be improved to have this kind of look, and how the
even handling operation related to this CM or MR, MC can be added there. We will be
able to try to do that, and then you that is the only thing that you have to apply your ideas
about how these things can be done.

So, let us see, whether you can do it or not. In case suppose, you are finding any
difficulty, we will be available to have any interaction not the direct online interaction
rather, you can send your problems through mail or you can request for an interaction
program so that we can sit and then discuss and solve the problems. But, before that, you
should fire all the problems to us, so that we can go through the program problems, and
then get ready to resolve it quickly.

The next version of this is basically to have a more improved calculator design. So, this
is the last calculator version, we have to change it into their as you see in this calculator
version, we can do many things. So, the previous calculator is basically adding two
numbers and operation, then it will give the result. But, here we can do say add, sub,

1328
division together many operations, and then final the result, so 5 plus 6 plus 10 into 2
minus 8 that is the result will be calculated like. So, this calculator, we will provide these
facilities.

In addition to this, this calculator also allowed to have the bracketed expression,
bracketed expression means is basically within this bracket, so 2 plus 3 multiplied by say
5, it basically gives the result accordingly, so the brackets. And then complex bracket all
the matching parenthesis should be there, it should be; in case there is an error in the
matching practice, your calculator should report an error message on the screen. I mean
text (Refer Time: 06:53) instead of the result. And so this is the method that we have
discussed is an improved version of the previous one, you have to add few more buttons.
And then for each button, we have to add the listening methods.

(Refer Slide Time: 07:06)

And then finally, the next is advance calculator design. And as you see little bit more
buttons are there. And here I have made it a little bit open space for you so that you can
think about how more advanced calculator more sophisticated calculator can be
designed. You can follow for an example; the Casio math calculator which is very
famous among the students popular among the students.

So, you can follow this calculator, and see whether the same can be developed in your
Java environment. And you can see many calculators available in your Windows
environment, in your Linux system as well as if you have the mobile also, you can find

1329
many calculators there also. You can think about the calculator, the calculator that you
can develop in Java can be exported to a mobile setting; so, there mobile app as a
calculator can be used, your advance calculator.

Now, let us see, what is the advance component that we are thinking about, so power
button that we have considered that means, if you click the power for example, so all the
things will be deemed, and then there will be no highlights like that. It since that the
calculator is power off like, so it is power on and off like sort of thing, so some setting
changes. And after that power on and off, if anybody uses any keys and everything, so
calculator we will not work for you, so it becomes disabled.

And then there is about, so here you can see the different other component style. Say
suppose you have to change the background, because I do not like these background so,
user can customize the background color, foreground color, font, font size, and then
orientation if you want to change the orientation in this light or everything that you can
allow using this one.

And exit basically if you do certain changes, whatever it is there exit. Now, you can
replace this exit button, which some other buttons like all other trigonometric functions
say sin, cos, tan, cot like this one that also if you clicked it, and then this of this operator,
we will add. Because, if we add more buttons, the size of the applet will increase, and at
the cost of the size of the fonts and button size, and then error will be there. If you want
to click this one by mistake because of the small size in button, you go to some other
button or whatever it is there.

So, in that case, some other functionalities like log functionalities, trigonometric
functionalities or some other functionalities can be added there also ok. So, this way the
calculator can be improved. And, another scope of improvement is that so log table also
can be there, and then some statistical table also can be added into this log at this
calculator itself, so that in the memory the table will be stored. And whenever you give
any value say a degree of freedom, and then the value, then it will result in the return. So,
if you are a little bit knowledge about the statistical process or statistical tables or
distribution function all these things, those also think can be incorporated into it.

There are many scopes of improvement again. Now, here we have designed the
calculator in English, but those do not know English for them, how this calculator can be

1330
facilitated. So, for these things all the things which are there in English, it can be
converted into other languages Hindi or some Telugu or Tamil like. So, here all these
characters can be changed, it is just minimum effort is required.

So, in the style file or about or in the setting file, you can change that calculator in which
language, so language setting also can be there. So, a lot of things can be done. And this
way, you can innovate that how you can better calculator can be designed. And the
calculator design is a very good example for and usually many teacher, the many author
also, they preferred that calculator should be discussed while they discussed the different
Java concepts. We have done the same thing also here, but there is a starting point, you
can go on, and carry with this, and they learn many things are there.

Now, let us come to the next projects, this project is again very similar to the project as
you can see, if you are familiar to Kaun Banega Crorepati right. So, there is a one quiz
game is there, where Mr. Bachchan, who is basically conducting this one. So, we can
implement the quiz game application, but Bachchan should not be available all the time.
So, in place of Bachchan, our computer can play the role of Bachchan.

So, here questions a quiz can be popped off from the repository, and then the user will be
allowed to select an of select and option and if it is a correct option, his score will be
increased. And if it is a wrong option or if it has suspect about any results, then we will
just like a Kaun Banega Crorepati quiz, it will basically give that 50 percent off, then
accordingly a score will be reduced. And then only two options will be given, out of
these two options, you have to select. All those things can be done. So, this is the exactly
quiz game application, it is there.

1331
(Refer Slide Time: 12:28)

Now, let us see, what is an idea? And for this, obviously things to implement it, the
different concept that you have to apply Java swing is required, event handling, I-O
stream is needed to be followed, and JDBC also to be there. So, if you have the
confidence in all of these concepts, then definitely you can study. Even if you do not
have any confident also, let us start dealing with these projects and then try to learn as it
is required. And then this is also one way of learning process.

(Refer Slide Time: 12:56)

1332
Now, here is the idea about quiz game application. So, first of all, you have to create a
question bank. The question bank means, it is basically set of all questions maybe 500,
maybe 5000, maybe 50,000, absolutely no issue there is a little bit no limit. And then the
question bank needs to be prepared, and this question bank needs to be maintained in a
server.

So, in this way JDBC coming into the picture, a database server is coming into the
picture. I will tell you the idea, how this question bank server can be created in this
project. And then user will be allowed to play for this game playing, definitely there
should be one GUI to be developed. So, a GUI based engine needs to be developed by
which it can play the game, it will basically be asked what questions, then questions will
be there, options will be there, then the select button will be there, other options will be
there, so many things are there. So, the GUI program is basically a front end for the user.
And there are many facilities, flexibility, so the game can be tuned as per the different
twists, and then the requirement is concerned.

(Refer Slide Time: 14:15)

Now, let us discuss each step one by one, so that we can understand about how the
project can be carried out one by one. So, the question bank database server creation.
There are two things that can be done, you can add the database by using a skill
commands, it is there sitting on the console typing each command at a time, and then
adding the record into the database.

1333
Now, here I want to say is that if the database table needs to be created, then what will be
the structure of the table, it has one field about the question itself. Then the other four
fields, for the four options. Then another field the 6th field, it should be the correct
option because this information is required, so that the program can process it. And then
whenever this database whenever the game is in running condition, it will phase 1
question as well as all options, and then correct option.

And then we will throw the question as well as the options, and then it will select the
choice from the user verify the option if the correct one, and then accordingly score will
be calculated like this one. Now, one process that I told you that you have enter the data
one by one, but 500 enter data those are the text and then typing error and everything, so
it is very difficult. So, we can write one program automatically that the program will
basically take as an input as a document file.

And then that file will be scanned and each record will be entered automatically to the
server, so that file can be created using an excel sheet-like, and I have given an idea here
CSV file, it is just similar to Excel file only the comma-separated. So, each field will be
separated by a comma, you have to scan it. Whenever you find a comma, you can take
that this is the one field value, and then go into that field value, the next and so on so on.
So, this way 6th field question four options, and a then correct option will be selected
and then accordingly, populated to the database server.

So, here is the idea it is given, this is the CSV file that you created, and that can be cut
and paste for document can be created, and then one. And that program, if you run with
another CSV file, it will be automatically updating the database easily just running the
program itself. So, developing the program only the issues are there, but it is only a few
lines code is required. Let us try to do it, how the CSV file can be read and then the
content can be retrieved, and the same content can be sent and executed as an insert
record to the database server. So, this way it can be done.

And another thing that ok, there are you the as a database administrator, you can create
the database table also from the JDBC also you can create the table absolute no problem.
Whatever the way you there, we can do there, and there may be different topics can be
included in your game. So, some topics maybe say related to the politic, some maybe
related to the entertainment, some maybe related to the other topic say computer science

1334
or physics chemistry like this one. Users can be given a chance therefrom which topic he
is interested to play the game. So, accordingly, the topic can be selected maybe two or
more top is can be selected, so that the question can be read can be fetched from all the
topics that the user has selected like. So, topic wise the different tables also can be
maintained, and it can be updated into the server or data can be loaded with the
corresponding topic tables and so on.

(Refer Slide Time: 17:43)

So, this is the data entry. So, for the I mean MySQL the server database creation is
concerned. And here is a GUI forgiving at the very beginning stage, you can have a very
simple look of the game as you see here, it will first discuss the question number. And
then the question will be appeared here, and then four options like option 1, option 2,
option 3 is there. And then all the options are not highlighted.

Whenever user select an option, it will click it. And then here another option that the
correct option, which will be selected will be displayed or if the option that has been
selected is not correct, the correct option actually according to this question will be
displayed there. Anyway, so it will after the selection of an option, the correct option will
be displayed, and accordingly the score also will be computed.

So, this GUI program, we will take care everything. So, here the interface to be
developed, and for the event handling routine asked to be written, so that it can do the

1335
work as per the requirement it is there. So, this is the idea about the first phase of the
program.

(Refer Slide Time: 18:47)

In the second phase, GUI plus program for gaming as we have send that at the front-end
the GUI should appear, and at the back-end there lot of other activity should be carried
out. For which we need to develop socket program, because this GUI should interact
with the socket that socket will be responsible through the server so that on a network if
your server is not connected users in the same machine, then you have to do it.

Anyway, so that if you have to have access to JDBC, then you have to have the
connectivity and everything is the whether in the host machine and the game may
playing a machine in the same system or in the remote system, whatever it is there. So,
you can develop the socket program for that socket will basically run the networking,
and then JDBC related program elements, and then this is the backend program actually.

And then this program, we will take a selection from the user at the end of the round, the
correct option will be highlighted, and score will be updated. These are the program
activities that it should go, the game will continue until there maybe say 15 rounds or
until there will be an option that if you want to quit, then the quit option should be asked
from the user, and then quit it. Then finally, the game whenever it is over, then the total
score that the user the pair has achieved will be displayed on the screen and like this one.
So, this is the idea about the second version.

1336
(Refer Slide Time: 20:21)

And then the third version is basically, let us improve the interface as well as the
interface will change, all the backend program also has to be changed, all this thing that
you have to do it. Here I have given some ideas, but you can think some better idea than
this one. I wanted to make the idea little bit simple so that you can implement you can
handle this project in the shortest possible time.

And here is the idea that we are going to see here, the topic selection should be given as
an extra facilities to is earlier version it was not there, so topic 1, topic 2, everything is
here start the quiz. And if it is start, then this button will be changed to the stock quiz-
like. So, this button will be needed toggle mode. One start means, it will be start, and
then everything we will start like this one.

And whatever the topic that you selected, the topic will be highlighted here, so that you
can understand that on which topic he is giving the answer. And so in this case, only one
topic that one user can be selected at a time. So, at every round, the user can change this
topic, and then accordingly the question will be faced, the question will be displayed
here, these are the all same things it is there, so as you there.

And then so here again another facility so this is another improved version of the layout
that you can think about, and this is the another more improve version, where we can add
a few more button as we see. So, remove one question, remove two question, and all this
thing. So, remove one question means, it is basically one-third score will be reduced.

1337
And then out of 4, it basically only 3, out of which one should be the correct of course is
there.

Remove 2 question means, 50-50 right means, it is basically two questions will two
options will be removed. And then only two options out of which one is there, so the is
basically then the player can guess more precisely so that the more score can be there, it
is just like an in the form of a Kaun Banega Crorepati quiz style. And then this is the
interface that you can develop it. So, here it will basically few more buttons can be
added, and for these buttons, we have to add the interface program accordingly. So, this
is the 7th program, and this is the quiz playing game, actually we have discussed.

I hope, you are finding these projects interesting. And these are the small projects as
obviously, because the purpose that I have already tended you as motivated with that you
can apply your learning skill to developing this project. And if this project also, you can
carry out as your undergraduate project curriculum also, if you are an undergraduate
student like. And so this way, you can learn much more.

And then I have given the initial idea, not necessary initial idea is you can improve this
idea of your own, creativity is an essential part should be that the software engineer
should have. So, I have also that expectation from you, so that you can add a few more
novelty, more creativity in the project. So, these are the sit project, we can say, starting
with this one, then improve it. And then see what are the based product, you can
developed. Thank you for your endeavor.

Thank you very much.

1338
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 59
Case Study – IV

Welcome to the session. In this session we will be discuss few more projects. So, the
projects idea actually so that you can work on the projects and then improve your skill
so, this is the 8th project in the series of projects that we are discussing in this week. This
project is based on the Tic-tac-toe game development. Tic-tac-toe game is very familiar
game and you can find some apps also available now-a-days in the mobile.

So, that this game is available and then this game can be played between the user and the
machine, system, computer. So, one party; one player is user and another player is
computer. However, in this game we will discussed about how the game can be played
by two users that users; obviously, with their own computer and the two computers the
players which they are using the playing the games is connected through the net. So, this
is the requirement it is required here.

(Refer Slide Time: 01:34)

Now, let us have the idea about this game. Now, before going to discuss the idea what
are the basic skill that is required so that you can cope with this project. Obviously, you
should have the good knowledge about Java swing and then little bit graphics also

1339
involved event handling mechanism. So, it is basically GUI programming related issues
and the networking concept is required. So, if you have cover all those concepts then you
are ready for this project.

(Refer Slide Time: 02:04)

Now, so, the idea about this project; here the idea as we see the tic-tac-toe board as it
appears and is a familiar form as it is shown here this is the tic-tac-toe board and there
are markings. So, there are two types of marking as you see here; one is marking is cross
and another is 0. So, cross markings by one player whereas 0 markings will be indicated
by another player. So, as a simple form of this tic-tac-toe game as we see here there is a 3
cross 3 board. There may be some complex version also there 4 cross 4, 5 cross 5 and
much more also.

Anyway let us just work with the 3 cross 3, later on if your time permit and if your
interest grows then you can extend easily to 4 cross 4 or 5 cross 5. Anyway so, we will
consider a 3 cross 3 tic-tac-toe game here. Now, as I have only mentioned that this game
will be between two players. Two players will play the game from their machines; the
machines are remotely located and of course, the machines are connected through the
network.

Now so, two applications therefore, we have to develop, rather two programs we have to
develop; two programs we can say the two socket programs more precisely the two
socket programs will be executed in to host machines that into machines of the users.

1340
And, then the two games that two socket programs we will learn concurrently;
concurringly say the at the same time in the two machines the programs are to be run and
then once the program is in execution the user can play the game. And, the game we will
continue you can fix a time or the game may be continued until user wants to do so. So,
this is the idea about this game.

(Refer Slide Time: 04:22)

Now, let us see how we can deal with this project. Now, we will again follow a step by
step incremental procedure so that we can develop this game easily. The first at task is to
design the gaming windows as we see it is a frame and this frame includes the you can
say 4 fields rather we can say 4 button sort of thing sorry not 4 is a 9 bottom sort of thing
and we can easily do this frame work easily the actually. So, this is a very trivial task and
this is obviously, the first phase of the projects and in our next part.

So, the event handling if we say, the even handling will be like this so, people we will
select a particular button and then one players selection will be marked with X. So, the
other player selection will be marketed as 0 and then it will continue. And, then every
times the player will get his own turn to mark the selection and once a player win the
game automatically a message box will appear showing that this player A or player B
won the match. So, this is the interface that you have to develop first and this is the first
version first phase of the program.

1341
(Refer Slide Time: 05:50)

In our second phase of the program, we can say it is the second version of the tic-tac-toe
game. Here we have to add few more functionalities into the gaming windows. Now, let
us see what the functionality that can be considered here are. So, initially the initial
interface is there. Now, after the initial interface there will be a start or stop button; that
button can be a toggle button so that once the start then it will be automatically next go
to the stop. So, if we will select it automatically that portion will be there. So, if a player
wants to start his game so, the player; the start button should be there. And restart means
say suppose you want to abandon the game in the mid way then you can follow that a
start button.

Now, once the start is there either start after start the restart will be an executable, if it is
stop no restart button. So, this is an enabled, disabled depending on the first button that
you have selected. Once the start button is selected other than the start and restart or start
and stop and restart buttons we have to also around one another initiatives or facilities to
connect the user to some other machine; some other users; some other player. So, a
connect button will take care for this and disconnected basically if you want to quit the
game.

1342
(Refer Slide Time: 07:20)

So, one user; one player click a connect button, then it will pop up a window, so, it
basically the game ID. So, your name can be the game ID again. Now, if you are already
using then or all or say some user all already working on that then the same game ID can
be use. Say suppose player X is already in the field I mean in the active then we can
game ID is X actually otherwise if you want to create the game from your side only. So,
you can give a your game ID.

Now, that game ID will be available to all the users who are connected in the net and
then they can select that they to with home, they want to play all this things. Once the
game is created then there is a join option will be there, so that if user can join the game.
And then game once the game ID is created it will appear a game ID which is the game
ID that we have been created.

So, now, this is the starting of the session of a game from a player sides. So, other player
knowing that what are the game ID’s available, he can select and then join and then I can
start the gaming.

1343
(Refer Slide Time: 08:43)

And this is basically from one side so, one machine, one socket we can say. So, in the; in
two sockets that if programs if it is run then the network connectivity we will take care
about these execution. So, this is the third version is that you have developed the things
in a standalone in a one side only and how the two programs can run concurrently in two
different machines and they are connected through the net. So, here networking is
required so that all the sockets can communicate among the two between the two players.

Now, as a part of the communication few things that we have to take care about it; so,
this tic-tac-toe board should be visible from the continuing the same state of information
to both the users. So, initially it is blank no clicking is there, no ticking is there now, say
suppose player 1 here and player 2, they are playing the game and player 1 ticks it. So, as
soon as his ticking is over, then it will be marked and the same marking also will be
visible to the other player as well as.

Now, it is the player turn and here when the player turn is there, the player 1 cannot
initiate any move it is not allowed. So, game will take care about this. So, game we will;
in you will wait until player to finish his game; finished his turn move. Now, here the
again player 2 we will move. So, player 2 we will click and then according to this that
click we will appear in his own board as well as the same will be appear in to the other
parties board also. So, this will continue and this is the type of the game that you have to
implement and definitely the socket programming is required and then GUI

1344
programming is required. These are the two I mean programming aspects are to be
exercise in this project.

Now, let us come to the next project. This project is as we have given the title of this
project is document browser, you know exactly browser. Browser is basically is a
interface right, like say Internet Explorer or say Mozilla or Chrome you know these are
the browsers. Now, so Browser basically take a link and based on the link or browser we
will take a I mean link and then they will navigate to that link and then it will fetch some
things like that.

Also some time browser if it is a search engine like for example, Google then they will
take a link as well as they will take some keywords. And then related to the keyword
they will search the entire internet and then and whatever the document matches with
this keyword they will fetch it to the user. That may be a million of link whatever it is
there million of documents is there whatever it is there.

Now, so, there is a search engine, the search engine can be accessed from any program.
In fact, there is a little tricks about the tricks can be readily available from the internet if
you just take a quick search and then you can find many solution to that. Anyway, I will
come to that discussion again in a detail way later on. So, what is the idea about is that a
browser will basically browse; browse in the sense that it will surf the net and then
retrieve the documents to the say browsers machine or the users machine.

So, user will browse the system. So, here user is a browser and user will browse through
an interface. That interface we are going to develop and we term is a document browser.
Definitely it will not browse you just want to make it little simple so that we can restrict
to a particular kind of documents let it be an only PDF documents. That mean those are
the documents available in the net. There is a lot of I mean million of documents, billion
of documents are available in the net which are basically in a PDF format. Anyway, so if
this document browser will only search the PDF contents those are available in internet,
in the www dot w in what is called the World Wide Web link actually there.

1345
(Refer Slide Time: 13:04)

So, this; so, idea about ok so, before coming to this idea what are the concept that it will
cover, so far this browser development is concerned Swing is required to be apply to be
exercised here and then networking. Obviously, it is there, but this is a simple
networking in fact.

(Refer Slide Time: 13:26)

Now, let us come to the discussion over this project it is there. So, here basically you
have to develop a java program which will help a user, user is an I mean user means we
searching for a document in the net for any PDF documents available. User will provide

1346
definitely a keyword. A keyword can be a group of words or whatever it is there, no
issue. So, a keyword maybe say NPTEL course so, this keyword. So, it will be fetched
all PDF file related NPTEL course like there.

So, anyway so once the user provide a search word; so keywords rather right then your
program will search using some search engine and fetch all the documents with matches
with the keyword, that is the concept it is there that you have to implement it. All
documents fetch will be populated in a list in your in the local machine of the browser.

So, that means, the it is not exactly same as the search engine like Google does for you, it
basically give a link of all the document then user has to click with some snippets that is
there. However, I am telling is that you can bring it, but we have to process this phase
little bit who is basically search engine returns and then get the PDF file, and download
these PDF file of your own and then make a list in your own machine. So, this is the
extra step that your browser should do or the proposed browser should do.

And then once the list of documents are fetched in to the users machine then a user can
select any documents of each choice given the title of all the documents in the listed
itself. And, then document needs to be read by the user. Here again some functionalities
are to be added here functionalities that document will be open, a document will be
marked, a document will be saved, a document will be rated whatever it is there.

So, you are proposing that if the document like say document like anything so, we can
give the 10 point and if he does not like at all then it is a 0 point. So, 0 to 10 a Likert
scale a document can be rated. And, then this rating can be maintained in the document
itself and user can save this document for further reading in future. So, the document will
be stored with this rating point and everything. So, these are the things that your
document browser will facilitate to the user.

1347
(Refer Slide Time: 15:55)

Now, let us see how we can develop this document step by step. So, first we have to
create a simple layout as we have shown here the layout will includes away on simple
text field level and then button. So, here the level is basically what is the keyword that
you want to supply enter text like and then this is a text field where the keyword that is
basically user will provide it and then finally, search. So, whenever if the button will be
clicked, it will basically connect to the Google search engine or some other search engine
whichever you want to use in your machine and then say this search engine.

Again, you have to just communicate this search keyword to the search engine; search
engine take it, search engine will fetch the document for you, return all the pages
containing snippets and links and everything, then your program will right browse the
links and then connect the network corresponding to the given link and fetch the
document. Here is a networking issues will be there. So, you have to process all the
things and then and then network communication needs to be done so that it can be a
retrieve the files and everything.

Anyway, so, this is the first level interface that you have to develop. Here little bit heavy
code is involved whenever user enter search keyword. It is a little bit time consuming job
and little bit innovations are also there because it is not so easy going task actually, but if
you try and then if you little bit experienced user then it is very simple things. And, this

1348
kind of an experience if you gather, if you learn it, it is really useful in any future
development of this kind of software development.

Now, so, here is an example. So, once the user click the search engine it will basically
contact to the search engine and then it basically return the link, as you see the different
links those are continuing PDF file and all the PDF file will be fetched to the documents
as a next in turn.

(Refer Slide Time: 17:55)

Now, here you see our next version of the interface that you have to add the fetch
document and they list box will be there. As we see here basically; so, this is basically
list box will contains all the documents that have been fetched based on these keyword in
the system. So, it will tooled there. Then user can navigate this list and then scroll it then
clicking this all the list will be a formed and then select one list of his own interest.

One particular document is selected then the open button will be there if it is clicked, the
document will be opened. And then for the opening these document another interface
should be there; that means, you have to develop another one user program which will
basically open the document. You should not use any adobe PDF or some PDF, Browser
like this; you have to develop the browser document of your own so that it will basically
browser windows are there.

1349
(Refer Slide Time: 19:02)

Now, the browser window typically it will look like this, here is suppose this is the
interface and then browser window and here is the look of the browser window. So, this
is another GUI that you have to develop once the user selects the open button it will
appear. And in this browser you have to added some facilities like say plus and minus as
you see.

So, if you click the plus, the document will be zoomed little bit higher resolution and is a
minus it will be a lower. So, depending on the user’s choice and requirement so, the
document will be either zoomed in or zoomed out like. And, then there is also back
button should be there, back button will scroll from the next previous page and the next
button also we can apply here also, so that it in go to the next page. So, it is page up,
page down sort of things are there.

In addition to this, there is a scrollbar should be there if the document is too big in size,
so scrollbar needs to be followed there. So, using the scrollbar user can scroll the
document up and down also from this side to that side also. So, both vertical scroll bar
and horizontal scrollbar can be included in this what is called the document reader
actually you can say.

1350
(Refer Slide Time: 20:27)

So, this is the idea and in addition to this also we can add few more facilities like rating
and as I told you rating and then saving the document for future referral. So, that can be
carried out as a next phase of your project as a third version. As you see here so, in
addition to this all these things are we have already discussed about it. Now, I just in the
document reader only I want to add few more things as you see here. So, at a one button
like rate; that means, if you read this document then you can read this document from 0
to 10 Likert scale both inclusive and then save offline.

Here is the another button; that means, if you like this document and if you want to save
this document then it will basically give this. When you click this it will find the save
location and then name of the file that you want to save it, you can do it and then save
button can be clicked and then it will save the document in your own machine. So, this
document whenever it is saved; it will saved with it is rating values also. So, the two
things are to be maintained so; accordingly the saving pattern should be created.

So, it is not the simple saving as the windows operating system or other saving, other
ways does for you. So, you have to do little bit how the two things can be maintained. It
is not a very big job you can maintain one simple lock file and in the lock file you can
include all these information live.

So, this is basically the idea about document browser and I hope you have understood it.
In case of some difficulties to understand you are feel free to approach to me, to my team

1351
also, they are constantly will be available for your support. So, this is the idea about two
projects and we will discuss few more projects in the next session.

Thank you for your attention.

1352
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 60
Case Study – V

So, we are almost at the end of our course plan and definitely which is my endpoint, in
fact, it is your I mean point of starting. So, my endpoint means your beginning, in fact,
you have to start it. Now, anyway so, this is the concluding section session and in the
sessions, we are going to discuss about two more interesting projects so that these
projects you can take as a challenge and then try to implement these projects. And,
definitely I am sure that if you can take this project and then you will enjoy a lot.

Now, let us have a discussion about the project idea. This is the 10th program projects
and we as the name that you can see here the name of the project is Course Management
Systems. You probably know exactly it is managing the course. What is the course?
Whenever students attend some classes and take some involvement in a course he
becomes the participants of the course; then there is a teacher called the course
coordinator, who basically control many information about, right say what are the marks
obtained by each student and then grading and so many these things are there.

Now, in these projects similar kind of things needs to be maintained so that the course-
related information needs to be stored and then the user can enter the marks and you can
process the results, the results can be available, the user can see, the teacher can see, a
student also can see whatever it is there. So, many other improvement can be done. It is a
starting point of the projects and then you can extend this project adding some idea from
your side as well as.

1353
(Refer Slide Time: 02:03)

Now, let us see exactly for this project what is the skillset that you should have. You
have to implement this project using Java Swing as it is proposed here, then JDBC and
networking that knowledge is required so that you can implement this project.

(Refer Slide Time: 02:18)

Now, idea about this project let us come to the idea. So, we have to maintain a server
database. This server database will store a number of entries; it is basically a number of
tables I can say, each tables for each subject. Say suppose one student taking physics,
maths, chemistry then three tables are to be maintained. It may be that is all students'

1354
same students are not taking all the subjects. So, there should be another table also which
includes all the students under this particular year or semester who are active in an
academic program. So, there will be a list of student, the student’s information and then
marks obtained by different students in different courses.

So, this is the table or database that needs to be maintained and here the administrator
can maintain this information otherwise you can develop one interface for which
database can be enter whatever the projects that you have already some idea can be
applied here also, but I am thinking that all the database table is entered by the
administrator. So, here you do not have any burden on a responsibility for this.

So, create a GUI program therefore, here the teacher can enter the marks obtained by the
students in the course he has offered. So, here the facilities that will be available so that
is to user can run a program. Once the user runs the program and interface will appear
and using this interface the user can enter the marks obtained by the different subjects
who attended the course.

And, then there will be a computation aspect, the results of the results stored in the
database will be compiled for either for each student or for each course whatever the way
that will be decided. And, then accordingly the results will be compared result means
grading can be done depending on some rule base say if marks are greater than 90
percent then he should be added EX grade if 80 to 90 percent A grade or this kind of
grading composition you can decide and implement it.

So, the computing server will be there which will basically do all this computation task,
not in the teacher's machine. So, the teacher’s machine is another machine, the server
will compute all this thing another machine and then database which will be stored
maybe in the different machine or the same server machine we will assuming that
database can be maintained in a different server.

So, there is three-layer architecture as we see from the user site from the server site
computation and then from another server from the storing the database.

1355
(Refer Slide Time: 05:09)

Anyway, so, now we will consider for simplicity maintain a database server in some
machine which is connected to the net and the database should contents two tables as we
have mentioned here as a practice purpose you can just simply add on more only you can
add some other subjects other things also. So, the student table is there, maths subjects
mathematics table is there and the physics table is there; three tables are to be maintained
in the MySQL server.

(Refer Slide Time: 05:38)

1356
Then whenever the database administrator will maintain this table we have to fix the
table database. So, I have given an idea about how the database table look like. So, for
the students, it will have the roll number and name, and then we have given the type that
our roll is of type integer of size 10, then name is varchar of size 50 and then roll number
is the primary key here and then this is the other is there.

Now similarly, for the maths, roll, attendance and then marks obtained will be to be
added here. Similarly, physics also the name roll number and the marks need to be
maintained here. In the slides marks are not shown here, but you have to add the marks
they are also in this entry. Anyway, so, these are the different entries are to be there.

(Refer Slide Time: 06:17)

And so, GUI program; this is a typical look I am not necessary that you have to follow
the same look. If you have some better aesthetic sense then you can design the layout of
your own and then you can use it. So, you can develop the layer in such a way that the
user, maybe say teacher from his own mobile also can access this program. So, a browser
should be according to that way only. So, the GUI window will be planned this way. So,
that it is compatible to anywhere actually there.

Anyway, so, the first task in this project is basically there; after the database is created
this is the first task. Our second task is basically to create the GUI programs for the data
entry interface for the teacher and so I have already told you this is the look of that
teacher interface is there. Here the user will enter the student name and then enter the

1357
marks and everything, and then order and everything if you want to face the data it will
show in which order it will get it and then rank and everything will be there. Otherwise,
you can decide some other interface of your own also so that the user can use it and then
can go on adding the data into the system.

(Refer Slide Time: 07:39)

Now, once the user enter the data, it will go directly to the computing server and then
from the computing server, it will go to the MySQL database that the user or any user
cannot directly access the database. So, a database is a back end server we can say and
then add them. So, this is the database server at the backend of the computing server.
And at the front end the user program so that the user interface is there which will
communicate to the computing server which can be again communicated to the back end
server like this.

Now so now, next is the data processing mechanism. Here the computing server will take
care. Computing server can access the database server by means of program and then
depending on the user requirement either preparing the results or sorting of the marks
based on some ascending or descending order and many other utilities that can be added
here in the computing server.

1358
(Refer Slide Time: 08:39)

So, this is the data processing mechanisms are there. Now, I will just quickly brief about
the data processing mechanism that you should follow here; nowhere the step by step.
So, there is a socket program that you have to develop and we can say it is a client socket
and then the server socket is basically at the server end which will basically you
computing aspects will be there and then MySQL the server is there. So, there are three
entities, three computing entities; one is the client-server and then the database server is
to be there in this system.

And, then the teacher who can insert the marks is there. So, a teacher will be there who
can enter the marks. So, from the GUI interface here the teacher will enter the marks
here and then once the teacher enter the marks it will go to the client sockets. These
sockets can run in the same machine or like it is actually basically it should run in the
same machine. Once the result is going there it will go to the server socket whatever the
in data that the user that the teacher has populated it will go to the server. Then the server
will send it to the MySQL server through the JDBC connectivity.

Now, again if either wants to retrieve something any user say student or any other
teacher then another GUI should be developed there, then through the same GUI it sends
a request go to the computing server first, then MySQL and the MySQL written the
result computing server we will process according to the requirement or some retrieval

1359
information that is there and then it will go to the client sockets and then finally, it will
display on the users machine.

So, this is basically the idea about how the flow of data we will take place from the user
to the system itself. As this is the three-tier architecture as I told you. So, these basically
look like a three-tier architecture as it is shown here. So, this is basically the architecture
that you have to consider for in this project actually and this architecture has been
planned little bit typically level I should say bit high because here so, many tiers are to
be implemented and then they should be properly synchronized communicates, but it is
only for the experienced user and they can do it easily. And, it is not the very heavy job
actually you can make the cattle the job according to your own time and then knack and
interest you can do it the minimum version of it also. So, this is about our tenth projects.

(Refer Slide Time: 11:16)

And our next project and this is the most challenging project. Challenging project in the
sense that it is because a lot of other things are to be exercised and then your the
knowledge level has to be highly applied here and the program is called Java WordPro
Duo. So, here the name is not complete here. So, Java Word Pro Duo this is the project
actually that we are going to discuss. Now, let us see what is the project idea so that you
can understand what exactly this project it is and this project is as the name implies word
pro stands for word processing and duo means it will do more than one job actually at the
same time. So, that is why it is a duo.

1360
(Refer Slide Time: 12:09)

Now, for this project the skillset that you should consider here swing, even handling,
encapsulation handling, that is all; it is no network involved, it is no JDBC involved, no
other and a what is called the things involved, only the GUI and the programming is
involved. Now, so, this is the smallest level, but lot of other things. So, if you want to
make yourself is a I mean great Swing programmer, then this project really you can think
for as a good what is called the task actually, is a good challenge for you.

(Refer Slide Time: 12:50)

1361
Now, let us see what is the idea of the project. So, as I have mentioned that this project is
basically is a word processing is there. So, we have to develop a word processing editor.
You are already familiar which some word processing the editor that most only you have
used while you are compiling you are typing your program. For example; Notepad plus,
WordPad, Notepad these are the work. So, a similar kind of software you have to
develop. It is also I mean the problem is solved actually, but from your side, whether you
have solved this problem? If the answer is no, then there is a challenge that how you can
develop such a word processing document editor or word processing editor, text editor
we can say like that. So, it is not a big job. It is a simple application of Java Swing that
can help you to do the job very easily actually.

Now, next is that you have to develop a GUI program for the WordPro. So, is very nice
looking graphical user interface to be developed you have to have a little bit some ideas
so that whatever the existing or processor is there how your software can be comparable
to them. So, you can add a few more things so that you can say that you see this is the
thing that is my program where the other program does not have this kind of thing are
there. So, colorings and so many other things also you can add it if you can do it. It is not
the big job, it is not infeasible, it is practically feasible. So, you can do it, only you have
to think about that what you want to do and then think about how this can be done.

So, this what and how to resolve rigid if you re can resolve these what and how questions
then you can solve these problems very easily. So, that is why there is a lot of
customization and moreover, the main customization is that how this word processing
system can be used for both the composing a document as well as is a calculator purpose.
So, an idea is there and if you can then such a document I mean word processing
document can be also implemented compatible with any Indian language; that is also a
challenging job and that is also a very beautiful project also and the calculator also can
be ok. So, if it is an Indian language compatible maybe say in Hindi or in Bengali then
you can do it typing in Bengali or Hindi like this one.

So, a job is it is not a very novel of it is kind, but it is a challenging as well as and it will
give a lot of experience and learning scope. So, that you can use to develop more other
more advanced and sophisticated program in different application and moreover you if
you developed in here you can use it in the windows the android operating system, if we
can develop it here you can use it in a macOS if you can develop infer the desktop you

1362
can use also in for laptop or tabloid or it is in notebook or it is in a mobile handset,
Smartphone whatever it is there. So, the scope is very high, application potential is also
heavy.

(Refer Slide Time: 16:04)

Now, let us see how it looks like in the first phase the step by step if you do it then the
job becomes easier. You should not try to do all the things together, one by one. So, first,
you have to see how a canvas sort of thing which basically appears is a Windows should
be given to the user so that the user can type anything. Whatever the user we will type it
will appear on the canvas itself. So, this basically adds an editing panel or frame looks
like. So, a typical look as it is shown here you have to implement like this.

1363
(Refer Slide Time: 16:37)

Then you have to add on functionalities into this frame one by one. As you see here we
have added one functionalities called the file. You can see any word processing what are
the menus are there you can go on adding all those things one by one. Once the file it is
there it will give New, Open, Save or Exit these kind of things are there. So, this File
Open if it is there, now if you want to save it for example, here then it will ask that Save
or Don’t Save or Cancel whatever it is there.

So, after adding this File option you can add few more buttons also there and then you
can add it is. For example, after File, Edit; Edit means it can have the editing facilities
like editing, Cut, Paste and then Select All whatever the things are there you can apply it
here. So, here basically even handling for each component if you add one by one, go on
adding, test the program and go to the next step and so on, so on. This way you can see
an after few efforts you can develop a nice document WordPro program like.

1364
(Refer Slide Time: 17:47)

Then, our next version is that so, input, as I told you it should be used for a dual purpose
dual, means text editing. So, if it just text editing, then fine. Now, whenever if the text
editor from where you can type it. So, obviously, you use the standard keyboard which is
already attached to the things, but in some mobile environment there is no standard
keyboard. So, if you want to use it for the mobile setting then how it can do that.

So, for these things you can develop one software keyboard. Even the software keyboard
also can be used using your lap laptop or using your PC also. If your PC or laptop touch
enable, so, after touching also it can be done or clicking also by mouse pointing also it
can be done whatever it is there. So, keyboard and then keyboard has the software,
keyboard, as well as the hardware keyboard, is compatible with there.

Now, so far the software keyboard it is there I have given a layout of the software
keyboard. Once the user selects that system keyboard or virtual keyboard; I mean a
software keyboard, then this kind of things will appear for the user. So, that user can
click it or touch it and then accordingly the text will be entered and then it will display
on the screen. So, this is the only layout and this basically obviously, a little bit complex.
It is not so simple as the calculator panel is there, it is very difficult.

It is not difficult actually, it is only voluminous because so many keys are involved and
not all keys are of equal size. There are maybe function keys also which I have not
mentioned here you can do; again the caps key click also caps is there also, numeric keys

1365
there also, punctuation keys are there also, all those things will be settled it out. But,
everything is possible writing a simple software program in fact, and using Java is not a
very difficult job for any programmer.

(Refer Slide Time: 19:48)

And, then the software keyboard that you have developed also can be utilized to use as a
calculator. So, a calculator for the display here is there and then the you see whenever
you use as a calculator here. So, there is a calculator button will be there if you select it
then it will act as a calculator, in this case, all the button will be in a disable stage. So, no
response will be there, no event operations will be there. However, all the calculator
related buttons will be there and then you can use it.

And, more important thing is that you can little bit improve this calculator by adding
some more I mean character button also there so that some expression; say, suppose A
equals to 5, B equals to 10 and C equals to 100. If you add and then you can express A
star B plus C divided by A plus B plus C this kind of an expression also can be carried
out using this calculator is easy. So, this is the advantage of this calculator in addition to
the calculator for text entry and really very useful because you will get the two facilities
in the same product that is why this product is called the duo project.

Anyway, so, we have discussed about many other things which are related to this then I
am almost at the concluding part. But, before going to this concluding portion I want to

1366
make one more thing very clear that whatever the programs that we have used in our
entire throughout the entire course those programs are available.

(Refer Slide Time: 21:26)

And, the link I have given in these slides, you can see the link. So, it is basically https
then cse.iitkgp.ac.in/dsamanta. So, this is the link actually as we see. In this link if you
follow then you will find one HTML page there which contains all the necessary pieces
of information; those I have used in this course also it is already there. This is a very
huge resource and then you can get all the documents from there also.

In addition to this resource where all the programs that I have used I have already
deposited there, you should download all the program and run them. Just try to run it if
you run it then you can learn it. If you do not nurture this program you will not be there,
only learning theory, syntax and everything we will help we will not help you to learn it
much more.

And, then another thing is that in the first introduction slides in the first lectures you can
note I have given one tutorial link of the website. So, it is called a Java tutorial from the
Oracle you can even the from the Google search engine type that Java tutorial from
Oracle. So, it will give the link. So, it is basically standard edition is there and the Oracle
is the one another party of now developing these Java system actually. They are a part of
the Java development team. So now, they maintained a very nice link nice web page
which basically gives for all aspects of the Java programming with examples and all the.

1367
So that you can consider as a complement to this course learning whatever you are. If
you find any difficulties to learn from my delivery then you can consult quickly there
and you can learn also like that. Another important resource that you should consider so
that you can horn your skill is basically Java API. Now, Java API is very important; very
important because if you know the different methods belongs to the different class then
you can try to apply it. But, I have not mentioned all the methods that can belong to a
particular class. For example, the string. Under the string, there may be said a hundred
methods are there. How so many methods can be discussed in a short duration of half an
hour lectures or like that I did not do that.

However, you can have all the methods, their constructors, the return type, the peels and
then description everything that is also from the Java Oracle sites again; the same Oracle
website you can follow. It will give you all the information about. So, you can give a
type like Java API from Oracle. So, it will give all the packages whatever it is and it is
basically the genuine source; the source from the developer itself. So, source from the
creator itself. So, this is a very important source, that you can think about it.

And, as I told you already, so, I am almost at the endpoint and I told you my endpoint is
not it is my endpoint is basically your starting point for your things are. So, with these
things, I would like to conclude this course here and then I obviously, wish you all the
best and ever success in your career. And, also I want to convey my thanks to all of you
for attending this course and thanks for your attention throughout this long journey. I
wish you all the very best for the career point of view, from your development point of
view ok.

Thank you very much.

1368

You might also like