100% found this document useful (3 votes)
7K views1,373 pages

NPTEL Java Lecture Book

This document provides an overview of a 60-lecture course on Java programming. It includes a week-by-week outline of topics to be covered along with demonstrations. The lectures will cover core Java concepts as well as more advanced topics like interfaces, exceptions, multithreading, I/O streams, applets, AWT, Swing, networking, and JDBC. The course will conclude with a mini-project to provide students hands-on experience developing a software application using the skills learned throughout the course. Reference materials including textbooks and an online resource page with sample code and explanations are also mentioned.

Uploaded by

vespubek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
7K views1,373 pages

NPTEL Java Lecture Book

This document provides an overview of a 60-lecture course on Java programming. It includes a week-by-week outline of topics to be covered along with demonstrations. The lectures will cover core Java concepts as well as more advanced topics like interfaces, exceptions, multithreading, I/O streams, applets, AWT, Swing, networking, and JDBC. The course will conclude with a mini-project to provide students hands-on experience developing a software application using the skills learned throughout the course. Reference materials including textbooks and an online resource page with sample code and explanations are also mentioned.

Uploaded by

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

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
o