You are on page 1of 275

ITA2402handout 3

ITA2402Notes-1 10
ITA2402Notes-2 16
ITA2402Notes-3 20
ITA2402Notes-4 36
ITA2402Notes-5 40
ITA2402Notes-6 49
ITA2402Notes-7 51
ITA2402Notes-8 66
ITA2402Notes-9 77
ITA2402Notes-10 87
ITA2402Notes-11 91
ITA2402Notes-12 93
ITA2402Notes-13 108
ITA2402Notes-14 116
ITA2402Notes-15 122
ITA2402Notes-16 124
ITA2402Notes-17 128
ITA2402Notes-18 133
ITA2402Notes-19 138
ITA2402Notes-20 139
ITA2402Notes-21 141
ITA2402Notes-22 149
ITA2402Notes-23 152
ITA2402Notes-24 154
ITA2402Notes-25 159
ITA2402Notes-26 168
ITA2402Notes-27 175
ITA2402Notes-29 179
ITA2402Notes-30 183
ITA2402Notes-31 185
ITA2402Notes-32 186
ITA2402Notes-33 191
ITA2402Notes-34 196
ITA2402Notes-35 198
ITA2402Notes-36 199
ITA2402Notes-37 201
ITA2402Notes-38 207
ITA2402Notes-39 209
ITA2402Notes-40 212
ITA2402Notes-41 215
ITA2402Notes-42 217
ITA2402Notes-43 220
ITA2402Notes-44 224
ITA2402Notes-45 234
ITA2402Tutorial-1 238
ITA2402Tutorial-2 241
ITA2402Tutorial-4 244
ITA2402Tutorial-5 251
ITA2402Tutorial-6 253
ITA2402Tutorial-7 257
ITA2402Tutorial-8 259
ITA2402Tutorial-9 262
ITA2402Tutorial-10 264
ITA2402Tutorial-11 266
ITA2402Tutorial-12 269
ITA2402Tutorial-13 270
ITA2402Tutorial-15 273
COURSE HANDOUT

B.Tech -6th Semester

Course Title : OOPS THROUGH JAVA Dated: 05-12-2015


Course Code : IT 2402 Academic Year 2015-16
Course Structure : 3-1-0-4
Course coordinator : G.NARASINGA RAO
Instructor(s) : G.NARASINGA RAO, P. MURALIDHAR, A.ANUPAMA
1. Course description
This course presents a conceptual and practical introduction to object oriented programming, exemplified by
Java. As well as providing grounding in the use of Java, the course will cover general principles of
programming in object oriented frameworks. The course is intended to make the students to aware the
features of object-oriented approach to application development makes programs more intuitive to design,
faster to develop, more amenable to modification, and easier to understand.

2. Scope and objective


Students undergoing this course are expected to:
• Understand fundamentals of object-oriented concepts through Java.
• Understand how java achieves platform independence using concept of byte code.
• Extend existing code and develop new application to demonstrate code reusability
• Keep the related class of code together to create a package and import the same for future application
development.
• Implement multiple inheritances using interface concept.
• Explore concepts of concurrent programming by using multithreading.
• Handle runtime errors through exception handling mechanism.
• Provide graphical user interface for their application programs.
• Write applications that handle user interactions through various peripheral devices.

At the end of the course, the students can:


• Know the concepts of classes, objects, members of a class and the relationships among them
• Implement Applications using Packages
• Handle runtime errors using Exceptions handling mechanism.
• Develop application for concurrent processing using Thread concepts
• Design interactive applications for use on internet.
• Design applets that take user response through various peripheral devices such as mouse and
keyboard by event handling mechanism
Text Books:
1. Java: The complete reference, Herbert schildt, 7th Edition, TMH.
2. An Introduction to Object-Oriented Programming by Timothy A Budd, 3rd Edition ,Addison Wesley
Longman

Reference Books:
1. Java: How to Program, Dietal & Dietal, 8th Edition, PHI
2. Programming with Java A Primer, E.Balaguruswamy Tata McGraw Hill Companies
3. Core Java 2, Vol 1, Fundamentals by Cay. S.Horstmann and Gary Cornell, 7th Edition, Pearson
Education.
4. BIG JAVA Compatible with Java 5 & 6, Cay Horstmann , 3rd Edition , Wiley Publishers.

Syllabus
UNIT- I (11+3) Hrs.
Introduction to Java:
Overview of Object Oriented Programming principles, Importance of Java to the Internet, Byte code,
Methods, classes and instances. Data types, arrays, control statements, simple java program. Classes and
Objects – constructors, methods, access control, this keyword, overloading methods and constructors,
garbage collection.

UNIT-II (11+4) Hrs.


Inheritance: Hierarchical abstractions, Base class and subclass, subtype, substitutability, forms of
inheritance-specialization, specification, construction, extension, limitation, combination. Benefits of
inheritance, super keyword, final keyword with inheritance, polymorphism, abstract classes.
Packages: Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing packages,
Member access rules.
Interface: Defining an interface, differences between classes and interfaces, implementing interface,
variables in interface and extending interf aces.

UNIT- III (11+4) Hrs.


Exception handling: Concepts and benefits of exception handling, exception hierarchy, usage of try, catch,
throw, throws and finally, built-in and User Defined Exceptions.
Multithreading: Definition thread, thread life cycle, creating threads, synchronizing threads, daemon
threads.

UNIT IV (12+4) Hrs.


Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet, types of
applets, creating applets, passing parameters to applets, The AWT class hierarchy, user interface
components- labels, button, Text components.
Event Handling: Events, Delegation event model, handling mouse and keyboard events, Adapter classes,
inner classes. Compare basic AWT components with swing components. More user interface components -
canvas, scrollbars, check box, choices, lists panels – scroll pane, dialogs, menu bar, layout manager types.
5. Lesson plan
Lecture
Learning Objectives Topics to be covered Reference
No.
Unit – I : Introducing to Java
1 Understand the difference Overview of OOP Principles- Object, T1 Ch.2 19
b/w Procedure Oriented Class
Programming and OOP,
Introduction to OOPs
Principles
2 Learn the Java Buzz Java Buzz words, importance of Java to T1 Ch.1 9,11
words and importance of Internet, Byte code
Java for internet
3 Importance of Classes, Classes instance methods T1
methods and instances Ch.110,11

4 Understand the basic data Data types and Simple java program T1 Ch.3 43
types like Integers,
floating points characters
and Boolean and able
to write Simple java
program

5 Able to use different Control statements T1 Ch.5 99


control statements like if,
if-else, switch, while, for ,
do while etc.
6 TUTORIAL-1(Java Buzzwords, Objects, classes, methods)

7 Apply knowledge of 1- Arrays T1 Ch.3 61


D,2-D, multidimensional
arrays
8 Creation and usage of Classes and Objects T1 Ch.6
classes and objects 130,134

9 Purpose and usage of Constructors, methods T1 Ch.6


constructors, methods 138,145

10 TUTORIAL-2(Arrays, constructors)

11 Understand the purpose of Access control and This keyword T1 Ch.7,6


public , private, protected, 172,149
this keywords
12 Overloading Constructors and method overloading T1 Ch.7,6
156,150
13 Purpose of Garbage Garbage collection and Sample programs T1 Ch.7,6
collection 150

14 TUTORIAL-3(constructor and method overloading)


UNIT-II Inheritance, Packages, Interfaces

15 Understanding the Hierarchical Abstractions, base class, T2


importance of subclass, subtype, substitutability
Inheritance
16 Learn the different Specialization, specification, construction, T2
forms of inheritance extension, limitation, combination

17 To know the benefits of Benefits of Inheritance, super keyword T1 Ch.8 197


Inheritance and the
purpose of super
keyword
18 Understand the final keyword T1 Ch.8 219
importance of the
final keyword

19 TUTORIAL-4(Inheritance)

20 To know the different Polymorphism T1 Ch.8


types of 208
Polymorphism,
Overloading and
Overriding

21 Learn the importance Abstract Classes T1 Ch.8


and usage of 216
Abstract classes

22 TUTORIAL-5(Polymophism and Abstract classes)

23 Understand the Defining , creating and accessing a T1 Ch.9 224


importance and usage Package
of packages

24 To know the usage and Understanding CLASSPATH, importing T1 Ch.9 226


importance of packages 232
CLASSPATH and
importing packages
25 To understand the Member access Rules T1 Ch.9 227
importance of Member
access rules in packages
26 TUTORIAL-6(Packages)

27 To understand purpose , Defining and implementing interfaces, T1 Ch.9


usage and variables in interfaces 235,236
implementation of
interfaces
28 To study the differences differences between T1 Ch.9 247
between interfaces and interfaces and classes , extending
classes , extending interfaces
interfaces

29 TUTORIAL-7(Interfaces)

UNIT-III :Exception Handling and Multithreading

30 To learn the purpose and Concepts and benefits of exception T1Ch.10 250
concepts of exception handling
handling.
31 To know the Exception Exception hierarchy T1Ch.10 251
class hierarchy

32 Basics of exception Usage of try, catch T1Ch.10


handling 253-263

33 Purpose of throw, Usage of throw , throws, finally T1Ch.10


throws, finally 253-263

34 TUTORIAL-8(Exceptions)

35 Usage of built-in Built-in Exceptions T1Ch.10 265

36 Implementing User User defined exceptions T1Ch.10 267


defined Exceptions

37 TUTORIAL-9(Built-in and User defined Exceptions)

38 Understanding the Definition of Thread T1Ch.11 275


importance of
Threads and usage

39 To learn Thread Life Life cycle of Thread T1Ch.11


cycle
40 To learn creation of Creating Threads T1Ch.11 280
Threads

41 TUTORIAL-10(Threads)
42 To learn about Synchronizing Threads T1Ch.11.292
Synchronization

43 To know about Daemon Daemon Threads, Sample Program T1 Ch. 11


Threads

44 TUTORIAL-11(Synchronizing Threads)

UNIT-IV Applets and Event Handling

45 To learn the concepts of Concepts of Applets and understand the T1Ch.19 628
Applets and understand difference between applets and application
the difference between programs
applets and application
programs

46 To understand the life Life cycle of Applet and types of Applets T1Ch.19 634
cycle of an Applet and
different types of applets
47 Creation of applets and Creating applets, passing parameters to T1Ch.19 644
passing parameters to applets
applets
48 TUTORIAL-12(Applets)

49 Understand the AWT AWT classes T1Ch.21 688


class hierarchy

50 Usage of various User Labels, Button, Text Components T1 Ch.22


interface 737 739 758
components

51 TUTORIAL-13(User interface components)

52 To know the importance Events, Event Delegation model T1 Ch.20


of events and different 653 654
event models
53 To know the various Handling mouse events T1 Ch.20
events generated 663 664
by a mouse
54 To learn the various Handling keyboard events T1 Ch.20
keyboard events 664

55 TUTORIAL-14(Event handling)

56 Importance and usage of Adapter classes, Inner classes T1 Ch.20


adapter and inner classes 680 682

57 Comparison between Compare basic AWT components with T1 Ch.26


AWT and Swings Swing components , Canvas, Scroll bars, 921
check boxes T1Ch.22 693
754 745

58 Usage of various User Choices, list panels, scroll panes ,Dialogs , T1 Ch.22
interface components menubar 748 752
775 782

59 Layout Managers Layout Managers T1Ch.21 763

60 TUTORIAL-15(Swings)

Evaluation scheme:
Duration % of
Component Marks Date & Time Venue
(minutes) weightage
Sessional Test – 1 90 20 20 18.01.16 to 23.01.16 Block-6
Sessional Test – 2 90 20 (Best 2 tests 29.02.16 to 05.03.16 Block-6
Sessional Test – 3 90 20 average) 11.04.16 to 16.04.16 Block-6
Comprehensive
20 10 10 11.04.16 to 16.04.16 Block-6
Quiz Examination
Semester End Block-
180 70 70 25.04.16 to 07.05.16
Examination 1,2,3,4,5,6

Chamber Consultation Hour: Evening 4 PM to 5 PM


Venue: Block -5 CSE Staff Room
Notices: Department Notice Board/Main Notice Board

G. Narasinga Rao
Signature of the Instructor Signature of the course-coordinator
OOPS Through JAVA Lecture Notes-1 Unit- I

OOPs concepts, Objects and Classes


The following arethe oops concepts:
1.Objects.
2.Classes.
3.Data Abstraction.
4.Data Encapsulation.
5.Inheritance.
6.Polymorphism.
7.Dynamic Binding.
8.Message Passing
A way of viewing world
Agents:
OOP uses an approach of treating a real world agent as an object.

Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that data.

An object-oriented program can be characterized as data controlling access to code by switching


the controlling entity to data.

Responsibility
primary motivation is the need for a platform-independent (that is, architecture- neutral)
language that could be used to create software to be embedded in various consumer electronic
devices, such as microwave ovens and remote controls.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-1 Unit- I

Objects with clear responsibilities

Each class should have a clear responsibility.

If you can't state the purpose of a class in a single, clear sentence, then perhaps your class
structure needs some thought.

Messages
We all like to use programs that let us know what's going on. Programs that keep us informed
often do so by displaying status and error messages.

These messages need to be translated so they can be understood by end users around the world.

Benefits of Messages

An object's behavior is expressed through its methods, so (aside from direct variable access)
message passing supports all possible interactions between objects.
Objects don't need to be in the same process or even on the same machine to send and receive
messages back and forth to each other

Methods
Method is an action required by an object.
Methods allow the programmer to modularize the program.
All variables declared in method definitions are local variables.
That means they are known only in the method in which they are defined.
Most methods have a list of parameters that provide the means for communicating information
between the methods.
Methods parameters are also local variables.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-1 Unit- I

A method is a group of instructions that is given a name and can be called up at any point in a
program simply by quoting that name.

Drawing a Triangle require draw of three straight lines. This instruction three times to draw a
simple triangle.

We can define a method to call this instruction three times and draw the triangle(i.e. create a
method drawLine() to draw lines and this method is called repeatedly to achieve the needed task)

The idea of methods appears in all programming languages, although sometimes it goes under
the name functions and sometimes under the name procedures.

The name methods is a throw-back to the language C++, from which Java was developed.

In C++, there is an object called a class which can contain methods. However, everything in Java
is enclosed within a class .so the functions within it are called methods

CLASSES AND INSTANCES

The class is at the core of Java.


It is the logical construct upon which the entire Java language is built because it defines the
shape and nature of an object.
As such, the class forms the basis for object-oriented programming in Java. Any concept you
wish to implement in a Java program must be encapsulated within a class. Because the class is so
fundamental to Java.
The classes created in the preceding description primarily exist simply to encapsulate the main( )
method, which has been used to demonstrate the basics of the Java syntax. As you will see,
classes are substantially more powerful than the limited ones presented so far. Perhaps the most
important thing to understand about a class is that it defines a new data type. Once defined, this
new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class. Because an
object is an instance of a class, you will often see the two words object and instance used
interchangeably.

The General Form of a Class

When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data. While very simple classes may

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-1 Unit- I

contain only code or only data, most real-world classes contain both. As you will see, a class’
code defines the interface to its data.
A class is declared by use of the class keyword. The classes that have been used up to this point
are actually very limited examples of its complete form. Classes can (and usually do) get much
more complex.
The general form of a class definition is shown here:

class classname {type instance-variable1;


type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method}
type methodname2(parameter-list) {
// body of method
}
// ...
typemethodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called
members of the class. In most classes, the instance variables are acted upon and accessed by the
methods defined for that class. Thus, it is the methods that determine how a class’ data can be
used.
Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another. All methods have the same general form
as main( ), which we have been using thus far. However, most methods will not be specified as
static or public. Notice that the general form of a class does not specify a main( ) method. Java

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-1 Unit- I

classes do not need to have a main( ) method. You only specify one if that class is the starting
point for your program. Further, applets don’t require a main( ) method at all.
A class is a software construct that defines the data(states) and methods(behavior) of the specific
concrete objects that are subsequently constructed from that class. In Java terminology, a class is
built out of members, which are either fields or methods. Fields are the data for the class.
Methods are the sequences of statements that operate on the data. Fields are normally specific to
an object-that is, every object constructed from the class definition will have its own copy of the
field. Such fields are known as instance variables. Similarly methods are also normally declared
to operate on the instance variables of the class, and are thus known as instance methods.
A class in and of itself is not an object. A class is like a blueprint that defines how an object will
look and behave when the object is created or instantiated from the specification declared by the
class. You obtain concrete objects by instantiating a previously defined class. You can instantiate
many objects from one class definition, just as you can construct many houses all the same from
a single architect’s drawing.

Inheritance
Methods allows to reuse a sequence of statements

Inheritance allows to reuse classes by deriving a new class from an existing one

The existing class is called the parent class, or superclass, or base class

The derived class is called the child class or subclass.

The child class inherits characteristics of the parent class(i.e the child class inherits the methods
and data defined for the parent class
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. Inheritance supports the concept of hierarchical classification. A deeply inherited
subclass inherits all of the attributes from each of its ancestors in the class hierarchy.
Most people naturally view the world as made up of ojects that are related to each other in a
hierarchical way.
Inheritance: A new class (subclass, child class) is derived from the existing class(base class,
parent class).
Main uses of Inheritance:
1.Reusability
2.Abstraction

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-1 Unit- I

Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing
to the parent class

MethodBinding:

Method binding is an object that can be used to call an arbitrary public method, on an instance
that is acquired by evaluating the leading portion of a method binding expression via a value
binding.

It is legal for a class to have two or more methods with the same name.

Java has to be able to uniquely associate the invocation of a method with its definition relying on
the number and types of arguments.

Therefore the same-named methods must be distinguished:


o by the number of arguments, or
o by the types of arguments
Overloading and inheritance are two ways to implement polymorphism.
Method Overriding:
There may be some occasions when we want an object to respond to the same method but have
different behaviour when that method is called.

That means, we should override the method defined in the superclass. This is possible by
defining a method in a sub class that has the same name, same arguments and same return type
as a method in the superclass.

Then when that method is called, the method defined in the sub class is invoked and executed
instead of the one in the superclass. This is known as overriding.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-2 Unit-I

Java Buzz words, importance of Java to Internet, Byte code

The Java Buzzwords


The key considerations were summed up by the Java team in the following list of buzzwords:
1. Simple

2. Secure

3. Portable

4. Object-oriented

5. Robust

6. Multithreaded

7. Architecture-neutral

8. Interpreted

9. High performance

10. Distributed

11. Dynamic

 Simple – Java is designed to be easy for the professional programmer to learn and use.

 Object-Oriented: a clean, usable, pragmatic approach to objects, not restricted by the need for
compatibility with other languages.

 Robust: restricts the programmer to find the mistakes early, performs compile-time (strong
typing) and run-time (exception-handling) checks, manages memory automatically.

 Multithreaded: supports multi-threaded programming for writing program that perform


concurrent computations
 Architecture-neutral: Java Virtual Machine provides a platform independent environment for
the execution of Java byte code

 Interpreted and high-performance: Java programs are compiled into an intermediate


representation – byte code:
can be later interpreted by any JVM
can be also translated into the native machine code for efficiency.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-2 Unit-I

 Distributed: Java handles TCP/IP protocols, accessing a resource through its URL much like
accessing a local file.

 Dynamic: substantial amounts of run-time type information to verify and resolve access to
objects at run-time.

 Secure: programs are confined to the Java execution environment and cannot access other parts
of the computer.
 Portability: Many types of computers and operating systems are in use throughout the world—
and many are connected to the Internet.

 For programs to be dynamically downloaded to all the various types of platforms connected to
the Internet, some means of generating portable executable code is needed. The same mechanism
that helps ensure security also helps create portability.

 Indeed, Java's solution to these two problems is both elegant and efficient.

Why java is important to the Internet

 The Internet helped catapult java to the forefront of programming, and java, in turn, has had a
profound effect on the Internet. The reason for this is quite simple: Java expands the universe of
objects that can move about freely in cyberspace.
 In a network, two very broad categories of objects are transmitted between the server and your
personal computer: passive information and dynamic, active programs. For example, when you
read your e-mail, you are viewing passive data. Even when you download a program, the
program’s code is still only passive data.
 Even when you download a second type of object can be transmitted to your computer: a
dynamic, self-executing program. Such a program is and the server yet initiates active agent on
the client computer. For example, the server to display properly the data that the server is sending
might provide a program.
 As desirable as dynamic, networked programs are, they also present serious problems in the
areas of security and portability. Prior to java, cyberspace was effectively closed to half the
entities that now live there, as you will see, java addresses those concerns and, by doing so, has
opened the door to an exciting new form of program: the applet.

 Java Applets and Applications

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-2 Unit-I

Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. That is , an
application created by java is more or less like one created using C or C++. When used to create
applications, java is a not much different from any other computer language. Rather, it is java’s
ability to create applets that makes it important. An applet is an application designed to be
transmitted over the Internet and executed by a java-compatible Web browser. An applet is
actually a tiny java program, dynamically downloaded across the network, just like an image,
sound file, or video clip. The important difference is that an applet is an intelligent program, not
just and animation or media file. In other words, and applet is a program that can react to user
input and dynamically change not just run the same animation or sound over and over.

 Security
As you are likely aware, every time that you download a “normal ” program, you are risking a
viral infection. Prior to java, most users did not download executable programs frequently, and
those who did scanned them for viruses prior to execution. Even so, most users still worried
about the possibility of infection their systems with a virus. In addition to viruses, another type of
maillicious program exists that must be guarded against. This type of program can gather private
information, such as credit card numbers, bank account balances, and passwords, by searching
the contents of your computer’s local file system, java answer both of these concerns by
providing a “firewall” between a networked application and your computer.
 Portability
Many types of computers and operating systems are in use throughout the world - and many are
connected to the Internet. For programs to be dynamically downloaded to all the various types of
platforms connected to the Internet, some means of generating portable executable code is
needed. As you will soon see, the same mechanism that helps ensure security also helps create
portability. Indeed, java’s solution to these two problems is both elegant and efficient.
Byte code
• For most languages, compilation produces machine code
• Java compilation produces “bytecode”
– Intermediate code readable by the VM
– Transferable across the Internet as applets
• VM interprets BC into instructions
– Partly responsible for performance lag

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-2 Unit-I

• ByteCode produced on any platform may be executed on any other platform which supports a
VM

Write Once, Run Anywhere

Advantages of Bytecode

 Bytecode is architecture independent (and writing a VM is easier than rewriting a compiler for
every architecture)
 VMs can enforce different levels of security automatically (applets versus applications)
 Just In-Time (JIT) compiling helps achieve same or better speed than traditional compiled code

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Methods, classes and Instances


The class is at the core of Java. It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.

As such, the class forms the basis for object-oriented programming in Java. Any concept you wish to
implement in a Java program must be encapsulated within a class. Because the class is so fundamental to
Java.

Class Fundamentals:

The classes created in the preceding chapters primarily exist simply to encapsulate the main( )method,
which has been used to demonstrate the basics of the Java syntax. As you will see, classes are
substantially more powerful than the limited ones presented so far.

Perhaps the most important thing to understand about a class is that it defines a new data type, defined,
this new type can be used to create objects of that type.

Thus, a class is a template for an object, and an object is an instance of a class.

Because an object is an instance of a class, you will often see the two words object and instance used
interchangeably.

The General Form of a Class:

When you define a class, you declare its exact form and nature. You do this by specifying the data that it
contains and the code that operates on that data. While very simple classes may contain only code or
only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its
data.

A class is declared by use of the class keyword. The classes that have been used up to this point are
actually very limited examples of its complete form. Classes can (and usually do) get much more
complex. Asimplified general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

// ...

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

type instance-variableN;

type methodname1(parameter-list) {

// body of method

type methodname2(parameter-list) {

// body of method

// ...

type methodnameN(parameter-list) {

// body of method

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the
class. In most classes, the instance variables are acted upon and accessed by the methods defined for that
class. Thus, as a general rule, it is the methods that determine how a class’ data can be used.

Variables defined within a class are called instance variables because each instance of the class (that is,
each object of the class) contains its own copy of these variables. Thus, the data for one object is
separate and unique from the data for another.

All methods have the same general form as main( ), which we have been using thus far. However, most
methods will not be specified as static or public.

Notice that the general form of a class does not specify a main( )method. Java classes do not need to
have a main( ) method. You only specify one if that class is the starting point for your program. Further,
applets don’t require a main( ) method at all.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Declaring Member Variables


There are several kinds of variables:

 Member variables in a class—these are called fields.

 Variables in a method or block of code—these are called local variables.

 Variables in method declarations—these are called parameters.

The Bicycle class uses the following lines of code to define its fields:

public int cadence;


public int gear;
public int speed;
Field declarations are composed of three components, in order:

1. Zero or more modifiers, such as public or private.

2. The field's type.

3. The field's name.

The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The
public keyword identifies these fields as public members, accessible by any object that can access the
class.

A Simple Class:

Let’s begin our study of the class with a simple example. Here is a class called Box that defines

three instance variables: width, height, and depth.

// This program declares two Box objects.

class Box {

double width;

double height;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

double depth;

class BoxDemo2 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's

instance variables */

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;

System.out.println("Volume is " + vol);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

The output produced by this program is shown here:

Volume is 3000.0

Volume is 162.0

 As you can see, mybox1’s data is completely separate from the data contained in mybox2.
 As stated, a class defines a new type of data. In this case, the new data type is called Box.
 You will use this name to declare objects of type Box. It is important to remember that a class
declaration only creates a template; it does not create an actual object. Thus, the preceding code
does not cause any objects of type Box to come into existence.

To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

 After this statement executes, mybox will be an instance of Box. Thus, it will have “physical”
reality. For the moment, don’t worry about the details of this statement.
 As mentioned earlier, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
 Thus, every Box object will contain its own copies of the instance variables width, height, and
depth.
 To access these variables, you will use the dot (.) operator. The dot operator links the name of the
object with the name of an instance variable.

For example, to assign the width variable of mybox the value 100, you would use the following
statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object
the value of 100.

 In general, you use the dot operator to access both the instance variables and the methods within
an object.
 You should call the file that contains this program BoxDemo2.java, because the main() method is
in the class called BoxDemo2, not the class called Box.
 When you compile this program, you will find that two .class files have been created, one for
Box and one for BoxDemo2.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

 The Java compiler automatically puts each class into its own .class file. It is not necessary for
both the Box and the BoxDemo2 class to actually be in the same source file. You could put each
class in its own file, called Box.java and BoxDemo2.java, respectively.

To run this program, you must execute BoxDemo2.class. When you do, you will see the

following output:

Volume is 3000.0

Volume is 162.0

 As stated earlier, each object has its own copies of the instance variables.

This means that if you have two Box objects, each has its own copy of depth, width, and height. It is
important to understand that changes to the instance variables of one object have no effect on the
instance variables of another.

Declaring Objects

An object is an instance of a class. An object is known by a name and every object contains a state. The
state is determined by the values of attributes (variables). The state of an object can be changed by
calling methods on it. The sequence of state changes represents the behavior of the object.

An object is a software entity (unit) that combines a set of data with a set of operations to manipulate
that data.

As just explained, when you create a class, you are creating a new data type. You can use this type to
declare objects of that type.

However, obtaining objects of a class is a two-step process.

 First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
 Second, you must acquire an actual, physical copy of the object and assign it to that variable.
You can do this using the new operator.

 Declaration: The code set in variable declarations that associate a variable name with an object
type.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

 Instantiation: The new keyword is a Java operator that creates the object.

 Initialization: The new operator is followed by a call to a constructor, which initializes the new
object.

The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is, more or less, the address in memory of the object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated. Let’s look at the details of this procedure.

In the preceding sample programs, a line similar to the following is used to declare an object of type
Box:

Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like this to show each step
more clearly:

mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. After this line executes, mybox
contains the value null, which indicates that it does not yet point to an actual object.

Any attempt to use mybox at this point will result in a compile-time error. The next line allocates an
actual object and assigns a reference to it to mybox. After the second line executes, you can use mybox
as if it were a Box object. But in reality, mybox simply holds the memory address of the actual Box
object. The effect of these two lines of code is depicted in Figure.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Assigning Object Reference Variables:

Object reference variables act differently than you might expect when an assignment takes place. For
example, what do you think the following fragment does?

Box b1 = new Box();

Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is,
you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong.
Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1
to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the
same object as does b1. Thus, any changes made to the object through b2 will affect the object to which
b1 is referring, since they are the same object.

This situation is depicted here:

Although b1 and b2 both refer to the same object, they are not linked in any other way.

For example, a subsequent assignment to b1 will simply unhook b1 from the original object without
affecting the object or affecting b2. For example:

Box b1 = new Box();

Box b2 = b1;

// ...

b1 = null;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Here, b1 has been set to null, but b2 still points to the original object.

Description2:

As you know, a class provides the blueprint for objects; you create an object from a class. Each of the
following statements taken from the CreateObjectDemo program creates an object and assigns it to a
variable:

Point originOne = new Point(23, 94);


Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

The first line creates an object of the Point class, and the second and third lines each create an object of
the Rectangle class.

Each of these statements has three parts (discussed in detail below):

1. Declaration: The code set in bold are all variable declarations that associate a variable name
with an object type.

2. Instantiation: The new keyword is a Java operator that creates the object.

3. Initialization: The new operator is followed by a call to a constructor, which initializes the new
object.

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

type name;

This notifies the compiler that you will use name to refer to data whose type is type. With a primitive
variable, this declaration also reserves the proper amount of memory for the variable.

You can also declare a reference variable on its own line. For example:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Point originOne;

If you declare originOne like this, its value will be undetermined until an object is actually created and
assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use
the new operator, as described in the next section. You must assign an object to originOne before you
use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the variable
name, originOne, plus a reference pointing to nothing):

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to
that memory. The new operator also invokes the object constructor.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a
variable of the appropriate type, like:

Point originOne = new Point(23, 94);


The reference returned by the new operator does not have to be assigned to a variable. It can also be
used directly in an expression. For example:
int height = new Rectangle().height;

This statement will be discussed in the next section.

Initializing an Object

Here's the code for the Point class:

public class Point {


public int x = 0;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

This class contains a single constructor. You can recognize a constructor because its declaration uses the
same name as the class and it has no return type. The constructor in the Point class takes two integer
arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values
for those arguments:

Point originOne = new Point(23, 94);

The result of executing this statement can be illustrated in the next figure:

Here's the code for the Rectangle class, which contains four constructors:

public class Rectangle {


public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public Rectangle() {
origin = new Point(0, 0);
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle


public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing the area


// of the rectangle
public int getArea() {
return width * height;
}
}

Each constructor lets you provide initial values for the rectangle's size and width, using both primitive
and reference types. If a class has multiple constructors, they must have different signatures. The Java
compiler differentiates the constructors based on the number and the type of the arguments. When the
Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that
requires a Point argument followed by two integer arguments:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Rectangle rectOne = new Rectangle(originOne, 100, 200);

This calls one of Rectangle's constructors that initializes origin to originOne. Also, the constructor sets
width to 100 and height to 200. Now there are two references to the same Point object—an object can
have multiple references to it, as shown in the next figure:

The following line of code calls the Rectangle constructor that requires two integer arguments, which
provide the initial values for width and height. If you inspect the code within the constructor, you will
see that it creates a new Point object whose x and y values are initialized to 0:

Rectangle rectTwo = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a
no-argument constructor:

Rectangle rect = new Rectangle();

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no
other parent. If the parent has no constructor (Object does have one), the compiler will reject the
program.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Using Objects
Once you've created an object, you probably want to use it for something. You may need to use the value
of one of its fields, change one of its fields, or call one of its methods to perform an action.

Referencing an Object's Fields

Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a statement within
the Rectangle class that prints the width and height:

System.out.println("Width and height are: " + width + ", " + height);


In this case, width and height are simple names.

Code that is outside the object's class must use an object reference or expression, followed by the dot (.)
operator, followed by a simple field name, as in:

objectReference.fieldName
For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to
refer to the origin, width, and height fields within the Rectangle object named rectOne, the
CreateObjectDemo class must use the names rectOne.origin, rectOne.width, and rectOne.height,
respectively. The program uses two of these names to display the width and the height of rectOne:

System.out.println("Width of rectOne: " + rectOne.width);


System.out.println("Height of rectOne: " + rectOne.height);
Attempting to use the simple names width and height from the code in the CreateObjectDemo class
doesn't make sense — those fields exist only within an object — and results in a compiler error.

Later, the program uses similar code to display information about rectTwo. Objects of the same type
have their own copy of the same instance fields. Thus, each Rectangle object has fields named origin,
width, and height. When you access an instance field through an object reference, you reference that
particular object's field. The two objects rectOne and rectTwo in the CreateObjectDemo program have
different origin, width, and height fields.

To access a field, you can use a named reference to an object, as in the previous examples, or you can
use any expression that returns an object reference. Recall that the new operator returns a reference to an
object. So you could use the value returned from new to access a new object's fields:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

int height = new Rectangle().height;


This statement creates a new Rectangle object and immediately gets its height. In essence, the statement
calculates the default height of a Rectangle. Note that after this statement has been executed, the
program no longer has a reference to the created Rectangle, because the program never stored the
reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java
Virtual Machine.

Calling an Object's Methods

You also use an object reference to invoke an object's method. You append the method's simple name to
the object reference, with an intervening dot operator (.). Also, you provide, within enclosing
parentheses, any arguments to the method. If the method does not require any arguments, use empty
parentheses.

objectReference.methodName(argumentList);
or:

objectReference.methodName();
The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change
the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:

System.out.println("Area of rectOne: " + rectOne.getArea());


...
rectTwo.move(40, 72);
The first statement invokes rectOne's getArea() method and displays the results. The second line moves
rectTwo because the move() method assigns new values to the object's origin.x and origin.y.

As with instance fields, objectReference must be a reference to an object. You can use a variable name,
but you also can use any expression that returns an object reference. The new operator returns an object
reference, so you can use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).getArea()


The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As
shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the
area of the new rectangle.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -3 Unit-I

Some methods, such as getArea(), return a value. For methods that return a value, you can use the
method invocation in expressions. You can assign the return value to a variable, use it to make decisions,
or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:

int areaOfRectangle = new Rectangle(100, 50).getArea();


Remember, invoking a method on a particular object is the same as sending a message to that object. In
this case, the object that getArea() is invoked on is the rectangle returned by the constructor.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -4 Unit-I

Data Types and Sample Java Program


 Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false

 byte:
8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data streams.
 short:
16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.

 int:
32-bit integer type.

Range: -2147483648 to 2147483647.


Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte, short and int values are promoted to int before
calculation.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -4 Unit-I

 long: 64-bit integer type.


Range: -9223372036854775808 to 9223372036854775807.
Example: long l = 10000000000000000;
Usage:useful when int type is not large enough to hold the desired value
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.

 float: 32-bit floating-point number.


Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -4 Unit-I

2) large degree of precision is not required

 double:
64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers

// Compute the area of a circle.


class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}

 char:
16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = ‗a‘;
Usage:
1) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in (almost) all human languages.
2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.

 boolean: Two-valued type of logical values.


Range: values true and false.
Example: boolean b = (1<2);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -4 Unit-I

Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for

// Compute distance light travels using long variables.


class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

Control Statements
Control statements are the statements which alter the flow of execution and provide better
control to the programmer on the flow of execution.
In Java control statements are categorized into :
selection control statements,
iteration control statements and
jump control statements.
 Java’s Selection Statements: Java supports two selection statements: if and switch. These
statements allow us to control the flow of program execution based on condition.
o if Statement: if statement performs a task depending on whether a condition is true or false.
Syntax: if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block). The condition is any expression that returns a boolean
value. The else clause is optional.
Program : Write a program to find biggest of three numbers.
//Biggest of three numbers
class BiggestNo
{ public static void main(String args[])
{ int a=5,b=7,c=6;
if ( a > b && a>c)
System.out.println ("a is big");
else if ( b > c)
System.out.println ("b is big");
else
System.out.println ("c is big");
}
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

Output:

o Switch Statement: When there are several options and we have to choose only one option from
the available ones, we can use switch statement.
Syntax: switch (expression)
{ case value1: //statement sequence
break;
case value2: //statement sequence
break;
………….…..
case valueN: //statement sequence
break;
default: //default statement sequence
}
Here, depending on the value of the expression, a particular corresponding case will be
executed.
Program : Write a program for using the switch statement to execute a particular task depending on
color value.
//To display a color name depending on color value
class ColorDemo
{ public static void main(String args[])
{ char color = ‘r’;
switch (color)
{ case ‘r’: System.out.println (“red”); break;
case ‘g’: System.out.println (“green”); break;
case ‘b’: System.out.println (“blue”); break;
case ‘y’: System.out.println (“yellow”); break;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

case ‘w’: System.out.println (“white”); break;


default: System.out.println (“No Color Selected”);
}
}
}
Output:

 Java’s Iteration Statements: Java’s iteration statements are for, while and do-while. These
statements are used to repeat same set of instructions specified number of times called loops.
A loop repeatedly executes the same set of instructions until a termination condition is met.
o while Loop: while loop repeats a group of statements as long as condition is true. Once
the condition is false, the loop is terminated. In while loop, the condition is tested first; if
it is true, then only the statements are executed. while loop is called as entry control loop.
Syntax: while (condition)
{
statements;
}
Program : Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
while (i <= 20)
{ System.out.print (i + “\t”);
i++;
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

}
}
Output:

o do…while Loop: do…while loop repeats a group of statements as long as condition is


true. In do...while loop, the statements are executed first and then the condition is tested.
do…while loop is also called as exit control loop.

Syntax: do
{
statements;
} while (condition);

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
do
{ System.out.print (i + “\t”);
i++;
} while (i <= 20);
}
}
Output:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

o for Loop: The for loop is also same as do…while or while loop, but it is more compact syntactically.
The for loop executes a group of statements as long as a condition is true.
Syntax: for (expression1; expression2; expression3)
{ statements;
}
Here, expression1 is used to initialize the variables, expression2 is used for condition
checking and expression3 is used for increment or decrement variable value.

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i;
for (i=1; i<=20; i++)
System.out.print (i + “\t”);
}
}
Output:

· Java’s Jump Statements: Java supports three jump statements: break, continue and return.
These statements transfer control to another part of the program.
o break:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

Ø break can be used inside a loop to come out of it.


Ø break can be used inside the switch block to come out of the switch block.
Ø break can be used in nested blocks to go to the end of a block. Nested blocks represent a
block written within another block.
Syntax: break; (or) break label;//here label represents the name of the block.
Program : Write a program to use break as a civilized form of goto.
//using break as a civilized form of goto
class BreakDemo
{ public static void main (String args[])
{ boolean t = true;
first:
{
second:
{
third:
{
System.out.println (“Before the break”);
if (t) break second; // break out of second block
System.out.println (“This won’t execute”);
}
System.out.println (“This won’t execute”);
}
System.out.println (“This is after second block”);
}
}
}
Output:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

o continue: This statement is useful to continue the next repetition of a loop/ iteration.
When continue is executed, subsequent statements inside the loop are not executed.
Syntax: continue;

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main (String args[])
{ int i=1;
while (true)
{ System.out.print (i + “\t”);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
Output:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

o return statement:
Ø return statement is useful to terminate a method and come back to the calling method.
Ø return statement in main method terminates the application.
Ø return statement can be used to return some value from a method to a calling method.
Syntax: return;
(or)
return value; // value may be of any type

Program : Write a program to demonstrate return statement.


//Demonstrate return
class ReturnDemo
{ public static void main(String args[])
{ boolean t = true;
System.out.println (“Before the return”);
if (t)
return;
System.out.println (“This won’t execute”);
}
}
Output:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 5 Unit- I

Note: goto statement is not available in java, because it leads to confusion and forms infinite
loops.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-6 Unit-I

Arrays
 An array is a group of liked-typed variables referred to by a common name, with individual
variables accessed by their index.

 Arrays are: 1) declared 2) created 3) initialized 4) used

 Also, arrays can have one or several dimensions.

 Array declaration involves:


1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
 Two styles of array declaration:
type array-variable[];
or
type [] array-variable;

Array Creation

 After declaration, no array actually exists.

 In order to create an array, we use the new operator:

type array-variable[];
array-variable = new type[size];
 This creates a new array to hold size elements of type type, which reference will be kept in the
variable array-variable.
Array Indexing
 Later we can refer to the elements of this array through their indexes:

array-variable[index]

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-6 Unit-I

 The array index always starts with zero! The Java run-time system makes sure that all array
indexes are in the correct range, otherwise raises a run-time error.

Array Initialization
•Arrays can be initialized when they are declared:

•int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};

Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements

Multidimensional Arrays

 Multidimensional arrays are arrays of arrays:

1) declaration: int array[][];


2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

Classes and Objects

The class is at the core of Java. It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.

As such, the class forms the basis for object-oriented programming in Java. Any concept you wish to
implement in a Java program must be encapsulated within a class. Because the class is so fundamental to
Java.

Class Fundamentals:

The classes created in the preceding chapters primarily exist simply to encapsulate the main( )method,
which has been used to demonstrate the basics of the Java syntax. As you will see, classes are
substantially more powerful than the limited ones presented so far.

Perhaps the most important thing to understand about a class is that it defines a new data type, defined,
this new type can be used to create objects of that type.

Thus, a class is a template for an object, and an object is an instance of a class.

Because an object is an instance of a class, you will often see the two words object and instance used
interchangeably.

The General Form of a Class:

When you define a class, you declare its exact form and nature. You do this by specifying the data that it
contains and the code that operates on that data. While very simple classes may contain only code or
only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its
data.

A class is declared by use of the class keyword. The classes that have been used up to this point are
actually very limited examples of its complete form. Classes can (and usually do) get much more
complex. Asimplified general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

// ...

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

type instance-variableN;

type methodname1(parameter-list) {

// body of method

type methodname2(parameter-list) {

// body of method

// ...

type methodnameN(parameter-list) {

// body of method

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the
class. In most classes, the instance variables are acted upon and accessed by the methods defined for that
class. Thus, as a general rule, it is the methods that determine how a class’ data can be used.

Variables defined within a class are called instance variables because each instance of the class (that is,
each object of the class) contains its own copy of these variables. Thus, the data for one object is
separate and unique from the data for another.

All methods have the same general form as main( ), which we have been using thus far. However, most
methods will not be specified as static or public.

Notice that the general form of a class does not specify a main( )method. Java classes do not need to
have a main( ) method. You only specify one if that class is the starting point for your program. Further,
applets don’t require a main( ) method at all.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

NOTE: C++ programmers will notice that the class declaration and the implementation of the methods
are stored in the same place and not defined separately. This sometimes makes for very large .java files,
since any class must be entirely defined in a single source file. This design feature was built into Java
because it was felt that in the long run, having specification, declaration, and implementation all in one
place makes for code that is easier to maintain.

Declaring Member Variables


There are several kinds of variables:

 Member variables in a class—these are called fields.

 Variables in a method or block of code—these are called local variables.

 Variables in method declarations—these are called parameters.

The Bicycle class uses the following lines of code to define its fields:

public int cadence;


public int gear;
public int speed;
Field declarations are composed of three components, in order:

1. Zero or more modifiers, such as public or private.

2. The field's type.

3. The field's name.

The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The
public keyword identifies these fields as public members, accessible by any object that can access the
class.

A Simple Class:

Let’s begin our study of the class with a simple example. Here is a class called Box that defines

three instance variables: width, height, and depth.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

// This program declares two Box objects.

class Box {

double width;

double height;

double depth;

class BoxDemo2 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's

instance variables */

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;

System.out.println("Volume is " + vol);

The output produced by this program is shown here:

Volume is 3000.0

Volume is 162.0

 As you can see, mybox1’s data is completely separate from the data contained in mybox2.
 As stated, a class defines a new type of data. In this case, the new data type is called Box.
 You will use this name to declare objects of type Box. It is important to remember that a class
declaration only creates a template; it does not create an actual object. Thus, the preceding code
does not cause any objects of type Box to come into existence.

To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

 After this statement executes, mybox will be an instance of Box. Thus, it will have “physical”
reality. For the moment, don’t worry about the details of this statement.
 As mentioned earlier, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
 Thus, every Box object will contain its own copies of the instance variables width, height, and
depth.
 To access these variables, you will use the dot (.) operator. The dot operator links the name of the
object with the name of an instance variable.

For example, to assign the width variable of mybox the value 100, you would use the following
statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object
the value of 100.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

 In general, you use the dot operator to access both the instance variables and the methods within
an object.
 You should call the file that contains this program BoxDemo2.java, because the main() method is
in the class called BoxDemo2, not the class called Box.
 When you compile this program, you will find that two .class files have been created, one for
Box and one for BoxDemo2.
 The Java compiler automatically puts each class into its own .class file. It is not necessary for
both the Box and the BoxDemo2 class to actually be in the same source file. You could put each
class in its own file, called Box.java and BoxDemo2.java, respectively.

To run this program, you must execute BoxDemo2.class. When you do, you will see the

following output:

Volume is 3000.0

Volume is 162.0

 As stated earlier, each object has its own copies of the instance variables.

This means that if you have two Box objects, each has its own copy of depth, width, and height. It is
important to understand that changes to the instance variables of one object have no effect on the
instance variables of another.

Objects

An object is an instance of a class. An object is known by a name and every object contains a state. The
state is determined by the values of attributes (variables). The state of an object can be changed by
calling methods on it. The sequence of state changes represents the behavior of the object.

An object is a software entity (unit) that combines a set of data with a set of operations to manipulate
that data.

As just explained, when you create a class, you are creating a new data type. You can use this type to
declare objects of that type.

However, obtaining objects of a class is a two-step process.

 First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

 Second, you must acquire an actual, physical copy of the object and assign it to that variable.
You can do this using the new operator.

 Declaration: The code set in variable declarations that associate a variable name with an object
type.

 Instantiation: The new keyword is a Java operator that creates the object.

 Initialization: The new operator is followed by a call to a constructor, which initializes the new
object.

The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is, more or less, the address in memory of the object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated. Let’s look at the details of this procedure.

In the preceding sample programs, a line similar to the following is used to declare an object of type
Box:

Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like this to show each step
more clearly:

mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. After this line executes, mybox
contains the value null, which indicates that it does not yet point to an actual object.

Any attempt to use mybox at this point will result in a compile-time error. The next line allocates an
actual object and assigns a reference to it to mybox. After the second line executes, you can use mybox
as if it were a Box object. But in reality, mybox simply holds the memory address of the actual Box
object. The effect of these two lines of code is depicted in Figure.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

Assigning Object Reference Variables:

Object reference variables act differently than you might expect when an assignment takes place. For
example, what do you think the following fragment does?

Box b1 = new Box();

Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is,
you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong.
Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1
to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the
same object as does b1. Thus, any changes made to the object through b2 will affect the object to which
b1 is referring, since they are the same object.

This situation is depicted here:

Although b1 and b2 both refer to the same object, they are not linked in any other way.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

For example, a subsequent assignment to b1 will simply unhook b1 from the original object without
affecting the object or affecting b2. For example:

Box b1 = new Box();

Box b2 = b1;

// ...

b1 = null;

Here, b1 has been set to null, but b2 still points to the original object.

REMEMBER: When you assign one object reference variable to another object reference variable, you
are not creating a copy of the object, you are only making a copy of the reference.

1. Declaration: The code set in bold are all variable declarations that associate a variable name
with an object type.

2. Instantiation: The new keyword is a Java operator that creates the object.

3. Initialization: The new operator is followed by a call to a constructor, which initializes the new
object.

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to
that memory. The new operator also invokes the object constructor.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a
variable of the appropriate type, like:

Point originOne = new Point(23, 94);


The reference returned by the new operator does not have to be assigned to a variable. It can also be
used directly in an expression. For example:
int height = new Rectangle().height;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

This statement will be discussed in the next section.

Initializing an Object

Here's the code for the Point class:

public class Point {


public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

This class contains a single constructor. You can recognize a constructor because its declaration uses the
same name as the class and it has no return type. The constructor in the Point class takes two integer
arguments, as declared by the code (int a, int b). The following statement provides 23 and 94 as values
for those arguments:

Point originOne = new Point(23, 94);

Here's the code for the Rectangle class, which contains four constructors:

public class Rectangle {


public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle


public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing the area


// of the rectangle
public int getArea() {
return width * height;
}
}

Each constructor lets you provide initial values for the rectangle's size and width, using both primitive
and reference types. If a class has multiple constructors, they must have different signatures. The Java
compiler differentiates the constructors based on the number and the type of the arguments. When the
Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that
requires a Point argument followed by two integer arguments:

Rectangle rectOne = new Rectangle(originOne, 100, 200);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

This calls one of Rectangle's constructors that initializes origin to originOne. Also, the constructor sets
width to 100 and height to 200. Now there are two references to the same Point object—an object can
have multiple references to it, as shown in the next figure:

The following line of code calls the Rectangle constructor that requires two integer arguments, which
provide the initial values for width and height. If you inspect the code within the constructor, you will
see that it creates a new Point object whose x and y values are initialized to 0:

Rectangle rectTwo = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a
no-argument constructor:

Rectangle rect = new Rectangle();

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no
other parent. If the parent has no constructor (Object does have one), the compiler will reject the
program.

Using Objects
Once you've created an object, you probably want to use it for something. You may need to use the value
of one of its fields, change one of its fields, or call one of its methods to perform an action.

Referencing an Object's Fields


Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a statement within
the Rectangle class that prints the width and height:

System.out.println("Width and height are: " + width + ", " + height);


In this case, width and height are simple names.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

Code that is outside the object's class must use an object reference or expression, followed by the dot (.)
operator, followed by a simple field name, as in:

objectReference.fieldName
For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to
refer to the origin, width, and height fields within the Rectangle object named rectOne, the
CreateObjectDemo class must use the names rectOne.origin, rectOne.width, and rectOne.height,
respectively. The program uses two of these names to display the width and the height of rectOne:

System.out.println("Width of rectOne: "


+ rectOne.width);
System.out.println("Height of rectOne: "
+ rectOne.height);
Attempting to use the simple names width and height from the code in the CreateObjectDemo class
doesn't make sense — those fields exist only within an object — and results in a compiler error.

Later, the program uses similar code to display information about rectTwo. Objects of the same type
have their own copy of the same instance fields. Thus, each Rectangle object has fields named origin,
width, and height. When you access an instance field through an object reference, you reference that
particular object's field. The two objects rectOne and rectTwo in the CreateObjectDemo program have
different origin, width, and height fields.

To access a field, you can use a named reference to an object, as in the previous examples, or you can
use any expression that returns an object reference. Recall that the new operator returns a reference to an
object. So you could use the value returned from new to access a new object's fields:

int height = new Rectangle().height;


This statement creates a new Rectangle object and immediately gets its height. In essence, the statement
calculates the default height of a Rectangle. Note that after this statement has been executed, the
program no longer has a reference to the created Rectangle, because the program never stored the
reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java
Virtual Machine.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

Calling an Object's Methods


You also use an object reference to invoke an object's method. You append the method's simple name to
the object reference, with an intervening dot operator (.). Also, you provide, within enclosing
parentheses, any arguments to the method. If the method does not require any arguments, use empty
parentheses.

objectReference.methodName(argumentList);
or:

objectReference.methodName();
The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change
the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:

System.out.println("Area of rectOne: " + rectOne.getArea());


...
rectTwo.move(40, 72);
The first statement invokes rectOne's getArea() method and displays the results. The second line moves
rectTwo because the move() method assigns new values to the object's origin.x and origin.y.

As with instance fields, objectReference must be a reference to an object. You can use a variable name,
but you also can use any expression that returns an object reference. The new operator returns an object
reference, so you can use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).getArea()


The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As
shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the
area of the new rectangle.

Some methods, such as getArea(), return a value. For methods that return a value, you can use the
method invocation in expressions. You can assign the return value to a variable, use it to make decisions,
or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle:

int areaOfRectangle = new Rectangle(100, 50).getArea();


Remember, invoking a method on a particular object is the same as sending a message to that object. In
this case, the object that getArea() is invoked on is the rectangle returned by the constructor.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 7 Unit- I

name. The qualified name of an instance variable looks like this:

objectReference.variableName
The qualified name of a method looks like this:

objectReference.methodName(argumentList)
or:

objectReference.methodName()
The garbage collector automatically cleans up unused objects. An object is unused if the program holds
no more references to it. You can explicitly drop a reference by setting the variable holding the reference
to null.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

Constructors and Methods

A constructor initializes an object immediately upon creation. It has the same name as the class in which
it resides and is syntactically similar to a method. Once defined, the constructor is automatically called
immediately after the object is created, before the new operator completes. Constructors look a little
strange because they have no return type, not even void. This is because the implicit return type of a
class’ constructor is the class type itself. It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully initialized, usable object immediately.

You can rework the Box example so that the dimensions of a box are automatically

initialized when an object is constructed. To do so, replace setDim( ) with a constructor.

Let’s begin by defining a simple constructor that simply sets the dimensions of each box

to the same values. This version is shown here:

/* Here, Box uses a constructor to initialize the

dimensions of a box.

*/

class Box {

double width;

double height;

double depth;

// This is the constructor for Box.

Box() {

System.out.println("Constructing Box");

width = 10;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

height = 10;

depth = 10;

// compute and return volume

double volume() {

return width * height * depth;

class BoxDemo6 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

When this program is run, it generates the following results:

Constructing Box

Constructing Box

Volume is 1000.0

Volume is 1000.0

As you can see, both mybox1 and mybox2 were initialized by the Box( ) constructor when they were
created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both mybox1 and
mybox2 will have the same volume. The println( ) statement inside Box( ) is for the sake of illustration
only.

Most constructors will not display anything. They will simply initialize an object. Before moving on,
let’s reexamine the new operator. As you know, when you allocate an object, you use the following
general form:

class-var = new classname( );

Now you can understand why the parentheses are needed after the class name. What is actually
happening is that the constructor for the class is being called. Thus, in the line

Box mybox1 = new Box();

new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor for a class,
then Java creates a default constructor for the class. This is why the preceding line of code worked in
earlier versions of Box that did not define a constructor. The default constructor automatically initializes
all instance variables to zero.

The default constructor is often sufficient for simple classes, but it usually won’t do for more
sophisticated ones. Once you define your own constructor, the default constructor is no longer used.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

Parameterized Constructors

While the Box( ) constructor in the preceding example does initialize a Box object, it is not very useful
—all boxes have the same dimensions. What is needed is a way to construct Box objects of various
dimensions. The easy solution is to add parameters to the constructor.

As you can probably guess, this makes them much more useful. For example, the following version of
Box defines a parameterized constructor that sets the dimensions of a box as specified by those
parameters. Pay special attention to how Box objects are created.

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.*/

class Box {

double width;

double height;

double depth;

// This is the constructor for Box.

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

// compute and return volume

double volume() {

return width * height * depth;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

class BoxDemo7 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

The output from this program is shown here:

Volume is 3000.0

Volume is 162.0

As you can see, each object is initialized as specified in the parameters to its constructor.

For example, in the following line,

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

Box mybox1 = new Box(10, 20, 15);

the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object. Thus,
mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15, respectively.

Overloading Constructors:

Since Box( ) requires three arguments, it’s an error to call it without them.

This raises some important questions.

What if you simply wanted a box and did not care (or know)

what its initial dimensions were? Or,

what if you want to be able to initialize a cube by specifying only one value that would be used for all
three dimensions?

As the Box class is currently written, these other options are not available to you.

Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it
handles the situations just described. Here is a program that contains an improved version of Box that
does just that:

/* Here, Box defines three constructors to initialize

the dimensions of a box various ways.

*/

class Box {

double width;

double height;

double depth;

// constructor used when all dimensions specified

Box(double w, double h, double d) {

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

width = w;

height = h;

depth = d;

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

// compute and return volume

double volume() {

return width * height * depth;

class OverloadCons {

public static void main(String args[]) {

// create boxes using the various constructors

Box mybox1 = new Box(10, 20, 15);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

// get volume of cube

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

The output produced by this program is shown here:

Volume of mybox1 is 3000.0

Volume of mybox2 is -1.0

Volume of mycube is 343.0

As you can see, the proper overloaded constructor is called based upon the parameters specified when
new is executed.

Parameter Passing
In general, there are two ways that a computer language can pass an argument to a subroutine.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

The first way is call-by-value. This approach copies the value of an argument into the formal parameter
of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the
argument.

The second way an argument can be passed is call-by-reference. In this approach, a reference to an
argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference
is used to access the actual argument specified in the call. This means that changes made to the
parameter will affect the argument used to call the subroutine.

As you will see, Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.

For example, consider the following program:

// Primitive types are passed by value.

class Test {

void meth(int i, int j) {

i *= 2;

j /= 2;

class CallByValue {

public static void main(String args[]) {

Test ob = new Test();

int a = 15, b = 20;

System.out.println("a and b before call: " +

a + " " + b);

ob.meth(a, b);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

System.out.println("a and b after call: " +

a + " " + b);

The output from this program is shown here:

a and b before call: 15 20

a and b after call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b used in
the call; their values here did not change to 30 and 10.

When you pass an object to a method, the situation changes dramatically, because objects are passed by
what is effectively call-by-reference.

Keep in mind that when you create a variable of a class type, you are only creating a reference to an
object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument. This effectively means that objects are passed to
methods by use of call-by-reference. Changes to the object inside the method do affect the object used as
an argument.

For example, consider the following program:

// Objects are passed by reference.

class Test {

int a, b;

Test(int i, int j) {

a = i;

b = j;

// pass an object

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 8 Unit- I

void meth(Test o) {

o.a *= 2;

o.b /= 2;

class CallByRef {

public static void main(String args[]) {

Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " +

ob.a + " " + ob.b);

ob.meth(ob);

System.out.println("ob.a and ob.b after call: " +

ob.a + " " + ob.b);

This program generates the following output:

ob.a and ob.b before call: 15 20

ob.a and ob.b after call: 30 10

As you can see, in this case, the actions inside meth( ) have affected the object used as an argument.

As a point of interest, when an object reference is passed to a method, the reference itself is passed by
use of call-by-value. However, since the value being passed refers to an object, the copy of that value
will still refer to the same object that its corresponding argument does.

Note: When a primitive type is passed to a method, it is done by use of call-by-value. Objects are
implicitly passed by use of call-by-reference.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

Access Control and This keyword

Access Specifiers: An access specifier is a key word that represents how to access a member

of a class. There are mainly four access specifiers in java.

o private: private members of a class are not available outside the class.

o public: public members of a class are available anywhere outside the class.

o protected: protected members are available outside the class.

o default: if no access specifier is used then default specifier is used by java compiler.

Default members are available outside the class.

The access modifiers supported by Java are static, final, abstract, synchronized, native, volatile, transient
and strictfp.

Can u declare a class as ‘private’?

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

No, if we declare a class as private, then it is not available to java compiler and hence a compile time
error occurs. But, inner classes can be declared as private.

An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s
declaration statement. Here is an example:

public int i;

private double j;

private int myMethod(int a, char b) { // ...

To understand the effects of public and private access, consider the following program:

/* This program demonstrates the difference between

public and private.

*/

class Test {

int a; // default access

public int b; // public access

private int c; // private access

// methods to access c

void setc(int i) { // set c's value

c = i;

int getc() { // get c's value

return c;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

class AccessTest {

public static void main(String args[]) {

Test ob = new Test();

// These are OK, a and b may be accessed directly

ob.a = 10;

ob.b = 20;

// This is not OK and will cause an error

// ob.c = 100; // Error!

// You must access c through its methods

ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " +

ob.b + " " + ob.getc());

As you can see, inside the Test class, a uses default access, which for this example is the same as
specifying public. b is explicitly specified as public. Member c is given private access. This means that it
cannot be accessed by code outside of its class. So, inside the AccessTest class, c cannot be used
directly. It must be accessed through its public methods setc( ) and getc( ). If you were to remove the
comment symbol from the beginning of the following line,

// ob.c = 100; // Error!

then you would not be able to compile this program because of the access violation.

To see how access control can be applied to a more practical example, consider the following improved
version of the Stack class shown at the end.

// This class defines an integer stack that can hold 10 values.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

class Stack {

/* Now, both stck and tos are private. This means that they cannot be accidentally or maliciously altered
in a way that would be harmful to the stack.*/

private int stck[] = new int[10];

private int tos;

// Initialize top-of-stack

Stack() {

tos = -1;

// Push an item onto the stack

void push(int item) {

if(tos==9)

System.out.println("Stack is full.");

else

stck[++tos] = item;

// Pop an item from the stack

int pop() {

if(tos < 0) {

System.out.println("Stack underflow.");

return 0;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

else

return stck[tos--];

As you can see, now both stck, which holds the stack, and tos, which is the index of the top of the stack,
are specified as private. This means that they cannot be accessed or altered except through push( ) and
pop( ). Making tos private, for example, prevents other parts of your program from inadvertently setting
it to a value that is beyond the end of the stck array.

The following program demonstrates the improved Stack class. Try removing the commented-out lines
to prove to yourself that the stck and tos members are, indeed, inaccessible.

class TestStack {

public static void main(String args[]) {

Stack mystack1 = new Stack();

Stack mystack2 = new Stack();

// push some numbers onto the stack

for(int i=0; i<10; i++) mystack1.push(i);

for(int i=10; i<20; i++) mystack2.push(i);

// pop those numbers off the stack

System.out.println("Stack in mystack1:");

for(int i=0; i<10; i++)

System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");

for(int i=0; i<10; i++)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

System.out.println(mystack2.pop());

// these statements are not legal

// mystack1.tos = -2;

// mystack2.stck[3] = 100;

Although methods will usually provide access to the data defined by a class, this does not always have
to be the case. It is perfectly proper to allow an instance variable to be public when there is good reason
to do so. However, in most real-world classes, you will need to allow operations on data only through
methods. The next chapter will return to the topic of access control. As you will see, it is particularly
important when inheritance is involved.

Understanding static

There will be times when you will want to define a class member that will be used independently of any
object of that class. Normally, a class member must be accessed only in conjunction with an object of its
class. However, it is possible to create a member that can be used by itself, without reference to a
specific instance. To create such a member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of its class are created, and without
reference to any object.

You can declare both methods and variables to be static. The most common example of a static member
is main( ). main( ) is declared as static because it must be called before any objects exist.

Instance variables declared as static are, essentially, global variables. When objects of its class are
declared, no copy of a static variable is made. Instead, all instances of the class share the same static
variable.

Methods declared as static have several restrictions:

• They can only call other static methods.

• They must only access static data.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

• They cannot refer to this or super in any way. (The keyword super relates to inheritance.).

If you need to do computation in order to initialize your static variables, you can declare a static block
that gets executed exactly once, when the class is first loaded.

The following example shows a class that has a staticmethod, some static variables, and a static
initialization block:

// Demonstrate static variables, methods, and blocks.

class UseStatic {

static int a = 3;

static int b;

static void meth(int x) {

System.out.println("x = " + x);

System.out.println("a = " + a);

System.out.println("b = " + b);

static {

System.out.println("Static block initialized.");

b = a * 4;

public static void main(String args[]) {

meth(42);

As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the
static block executes, which prints a message and then initializes b to a*4 or 12. Then main( ) is called,

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

which callsmeth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and
b, as well as to the local variable x.

Here is the output of the program:

Static block initialized.

x = 42

a=3

b = 12

Outside of the class in which they are defined, static methods and variables can be used independently of
any object. To do so, you need only specify the name of their class followed by the dot operator.

For example, if you wish to call a static method from outside its class, you can do so using the following
general form:

classname.method( )

Here, classname is the name of the class in which the static method is declared. As you can see, this
format is similar to that used to call non-static methods through object-reference variables.

A static variable can be accessed in the same way—by use of the dot operator on the name of the class.
This is how Java implements a controlled version of global methods and global variables.

Here is an example. Inside main( ), the static method callme( ) and the static variable b are accessed
through their class name StaticDemo.

class StaticDemo {

static int a = 42;

static int b = 99;

static void callme() {

System.out.println("a = " + a);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

class StaticByName {

public static void main(String args[]) {

StaticDemo.callme();

System.out.println("b = " + StaticDemo.b);

Here is the output of this program:

a = 42

b = 99

This Keyword :
•Can be used by any object to refer to itself in any class method

•Typically used to
–Avoid variable name collisions

–Pass the receiver as an argument

–Chain constructors
•Keyword this allows a method to refer to the object that invoked it.

•It can be used inside any method to refer to the current object:

Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
}

The keyword ‘this’: There will be situations where a method wants to refer to the object which
invoked it. To perform this we use ‘this’ keyword. There are no restrictions to use ‘this’ keyword

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes-9 Unit- I

we can use this inside any method for referring the current object. This keyword is always a
reference to the object on which the method was invoked. We can use ‘this’ keyword wherever a
reference to an object of the current class type is permitted. ‘this’ is a key word that refers to
present class object. It refers to

Present class instance variables

Present class methods.

Present class constructor.

Program : Write a program to use ‘this’ to refer the current class parameterized constructor

and current class instance variable.

//this demo
class Person
{ String name;
Person ( )
{ this (“Theressa”); // calling present class parameterized constructor
this.display ( ); // calling present class method
}
Person (String name)
{ this.name = name; // assigning present class variable with parameter “name”
}
void display( )
{ System.out.println ("Person Name is = " + name);
}
}
class ThisDemo
{ public static void main(String args[])
{
Person p = new Person ( );
}
}
Output: Person Name is = Theressa

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 10 Unit- I

Overloading Methods and Constructors

Overloading Methods

 The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists (there are some qualifications to this
that will be discussed in the lesson titled "Interfaces and Inheritance").
 Suppose that you have a class that can use calligraphy to draw various types of data (strings,
integers, and so on) and that contains a method for drawing each data type. It is cumbersome to
use a new name for each method—for example, drawString, drawInteger, drawFloat, and so
on. In the Java programming language, you can use the same name for all the drawing methods
but pass a different argument list to each method. Thus, the data drawing class might declare four
methods named draw, each of which has a different parameter list.

public class DataArtist {


...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}

 Overloaded methods are differentiated by the number and the type of the arguments passed into
the method. In the code sample, draw(String s) and draw(int i) are distinct and unique
methods because they require different argument types.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 10 Unit- I

 You cannot declare more than one method with the same name and the same number and type of
arguments, because the compiler cannot tell them apart.
 The compiler does not consider return type when differentiating methods, so you cannot declare
two methods with the same signature even if they have a different return type.
 Overloaded methods should be used sparingly, as they can make code much less readable.

Overloading Constructors:

Since Box( ) requires three arguments, it’s an error to call it without them.

This raises some important questions.

What if you simply wanted a box and did not care (or know)

what its initial dimensions were? Or,

what if you want to be able to initialize a cube by specifying only one value that would be used for all
three dimensions?

As the Box class is currently written, these other options are not available to you.

Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it
handles the situations just described. Here is a program that contains an improved version of Box that
does just that:

/* Here, Box defines three constructors to initialize

the dimensions of a box various ways.

*/

class Box {

double width;

double height;

double depth;

// constructor used when all dimensions specified

Box(double w, double h, double d) {

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 10 Unit- I

width = w;

height = h;

depth = d;

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

// compute and return volume

double volume() {

return width * height * depth;

class OverloadCons {

public static void main(String args[]) {

// create boxes using the various constructors

Box mybox1 = new Box(10, 20, 15);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 10 Unit- I

Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

// get volume of cube

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

The output produced by this program is shown here:

Volume of mybox1 is 3000.0

Volume of mybox2 is -1.0

Volume of mycube is 343.0

As you can see, the proper overloaded constructor is called based upon the parameters specified when
new is executed.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 11 Unit- I

Garbage Collection
Garbage collection is a mechanism to remove objects from memory when they are no longer needed.

Garbage collection is carried out by the garbage collector:

1) The garbage collector keeps track of how many references an object has.

2) It removes an object from memory when it has no longer any references.

3) Thereafter, the memory occupied by the object can be allocated again.

4) The garbage collector invokes the finalize method.

 Since objects are dynamically allocated by using the new operator, you might be wondering how
such objects are destroyed and their memory released for later reallocation. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator.
 Java takes a different approach; it handles deallocation for you automatically. The technique that
accomplishes this is called garbage collection. It works like this: when no references to an object
exist, that object is assumed to be no longer needed, and the memory occupied by the object can
be reclaimed. There is no explicit need to destroy objects as in C++.
 Garbage collection only occurs sporadically (if at all) during the execution of your program. It
will not occur simply because one or more objects exist that are no longer used.
Furthermore,different Java run-time implementations will take varying approaches to garbage
collection, but for the most part, you should not have to think about it while writing your
programs.
The finalize( ) Method
 Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-Java resource such as a file handle or window character font, then
you might want to make sure these resources are freedbefore an object is destroyed.
 To handle such situations, Java provides a mechanism called finalization. By using finalization,
you can define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector. To add a finalizer to a class, you simply define the finalize( ) method.
 The Java run time calls that method whenever it is about to recycle an object of that class. Inside
the finalize( ) method you will specify those actions that must be performed before an object is
destroyed.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 11 Unit- I

 The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state or indirectly through other referenced objects. Right before an asset is freed,
the Java run time calls the finalize( ) method on the object.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class. It is important to understand that finalize( ) is only called just prior to
garbage collection. It is not called when an object goes out-of-scope, for example. This means
that you cannot know when—or even if—finalize( ) will be executed. Therefore, your
program should provide other means of releasing system resources, etc., used by the object. It
must not rely on finalize( ) for normal program operation.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

Hierarchical Abstractions, base class, subclass, subtype, substitutability

Hierarchical abstractions
Hierarchical abstractions of complex systems can also be applied to computer programs. The data from a
traditional process-oriented program can be transformed by abstraction into its component objects. A
sequence of process steps can become a collection of messages between these objects. Thus, each of
these objects describes its own unique behavior. You can treat these objects as concrete entities that
respond to messages telling them to do something. This is the essence of object-oriented programming.

Up to this point, we have been using simple class hierarchies that consist of only a super class and a
subclass. However, you can build hierarchies that contain as many layers of inheritance as you like. As
mentioned, it is perfectly acceptable to use a subclass as a super class of another. For example, given
three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of
situation occurs, each subclass inherits all of the traits found in all of its super classes. In this case, C
inherits all aspects of B and A.

Types of Inheritance are use to show the Hierarchical abstractions. They are:

 Single Inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Hybrid Inheritance

Single Inheritance: Simple Inheritance is also called as single Inheritance. Here One subclass is deriving
from one super class.
A
SUPER CLASS A

EXTENDS

B SUB CLASS B

Example:
import java.io.*;
abstract class A
{
abstract void display();

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

class B extends A
{
void display()
{
System.out.println("hello");

}
public static void main(String args[])
{
B b=new B();
b.display();
super.display();

}
}
Output:
Hello

Multiple Inheritance: Deriving one subclass from more than one super classes is called multiple
inheritance.

INTERFACE1 INTERFACE2
A B

(Animal) (Bird)

IMPLEMENTS

SUBCLASS(InterfaceDemo2)

We know that in multiple inheritance, sub class is derived from multiple super classes. If two super
classes have sane names for their members then which member is inherited into the sub class is the main
confusion in multiple inheritance. This is the reason, Java does not support the concept of multiple
inheritance,. This confusion is reduced by using multiple interfaces to achieve multiple inheritance.

Interface: An interface is a class containing a group of constants ans method declarations, that does not
provide implementation. In essence, an interface allows you to specify what a class must do, but not how
to do.

Interface syntax:

An interface is defined much like a class. This is the general form of an interface:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

All the methods in an interface must be abstract and public. If we not mention these keywords then JVM
will treats all methods as public and abstract implicitly.

All the constants are treated as public, final and static.

Example:
interface Animal
{
public abstract void moves();
}
interface Bird
{
void fly();
}
public class InterfaceDemo2 implements Animal,Bird
{
public void moves()
{
System.out.println("animal move on land");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

}
public void fly()
{
System.out.println("birds fly in air");
}
public static void main(String args[])
{
InterfaceDemo2 id=new InterfaceDemo2();
id.moves();
id.fly();
}
}

Output:
animal move on land
birds fly in air

Hierarchical Inheritance: Only one base class but many derived classes.

SUPERCLASS
Figure

EXTENDS
Rectangl Triangle
SUBCLASS
e

Example:
abstract class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}

// override area for rectangle


double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

public static void main(String args[])


{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

output:
Inside area for Rectangle.
Area is 45.0
Inside are for Triangle.
Area is 40.0
Multilevel Inheritance: In multilevel inheritance the class is derived from the derived class.

SUPER-CLASS
A
EXTENDS

B SUB-CLASS

EXTENDS
C

SUB-SUBCLASS

Example: As mentioned, it is perfectly acceptable to use a subclass as a superclass of another. For


example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A.
When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses.
In this case, C inherits all aspects of B and A. To see how a multilevel hierarchy can be useful, consider
the following program.

// Create a super class.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
As you can see, the constructors are called in order of derivation. If you think about it, it makes sense
that constructors are executed in order of derivation. Because a super class has no knowledge of any
subclass, any initialization it needs to perform is separate from and possibly prerequisite to any
initialization performed by the subclass. Therefore, it must be executed first.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

Hybrid Inheritance: It is a combination of multiple and hierarchical inheritance.

HIERARCHICAL INHERITANCE
B C

D
MULTIPLE INHERITANCE

Base class Object or The Object class

Object class: Super class for all the classes in java including user defined classes directly or
indirectly.
Importing Object class: Java Library
Lang package
Object class
Object class is implicitly(automatically) imported into our source code, because it is in “lang” package.
Lang package is also implicitly imported into every java program.
Object class reference can store any reference of any object. This means that a reference variable of type
Object can refer to an object of any other class.
Advantage: When we want to write a method that needs to handle objects if unknown type. If we define
a parameter of object type, any class object can be passed to the method. Thus the method can receive
any type of object and handle it.

Method Description
boolean This method compares the references of two objects and if they are equal,
equals(Object obj) it returns true, otherwise false.
String toString() This method returns a string representation of an object.
Class getClass() This method gives an object that contains the name of a class to which an
object belongs. Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking object. This method
returns hash code number of an object.
void notify( ) This method sends a notification to a thread which is witing for an object.
void notifyAll( ) This method sends a notification for all waiting threads for the object.
void wait( ) This method causes a thread to wait till a notification is received from a
notify() or notifyAll() methods.
Object clone( ) This method creates a bitwise exact copy of an existing object. Creates a
new object that is the same as the object being cloned.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

void finalize( ) Called before an unused object is recycled. This method is called by the
garbage collector when an object is removed from memory.

Note: The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others.
Example programs:
Example program for equal():
import java.io.*;
import java.util.*;
class Myclass
{
int x;
Myclass(int x)
{
this.x=x;
}
}

class Compare
{
public static void main(String args[])
{
Myclass obj1=new Myclass(15);
Myclass obj2=new Myclass(15);
Integer obj3=new Integer(15);
Integer obj4=new Integer(15);
if(obj1.equals(obj2))
System.out.println("obj1 and obj2 are same");
else
System.out.println("obj1 and obj2 are not same");
if(obj3.equals(obj4))
System.out.println("obj1 and obj2 are same");
else
System.out.println("obj1 and obj2 are not same");
}
}
Output: obj1 and obj2 are not same
obj1 and obj2 are same
Example program for getClass():
import java.io.*;
import java.util.*;
class Myclass
{
int x;
Myclass(int x)
{
this.x=x;
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

}
class GetName
{
static void printName(Object obj)
{
Class c=obj.getClass();
String name=c.getName();
System.out.println("the class name:"+name);
}
}
class Getclass
{
static
{
Myclass obj=new Myclass(10);
GetName.printName(obj);
System.exit(0);
}

}
Output: the class name: Myclass

Example program for cloning:


The process of creating an exact copy of creating an exact copy of an existing object is called ‘cloning’.
In cloning, already an object should exist and when we clone the object, a bitwise copy of the object will
result. The original and the cloned object will be exactly the same bit to bit. If the original object has
some data in it, it also automatically comes into cloned object.
types of cloning:
1.when the cloned object is modified, same modification will alsoaffect the original object. This is
called ‘shallow cloning’.
2. when the cloned object is modified, if the original object is not modified, then it is called ‘deep
cloning’.
When we have new operator to create the objects, why do we need the cloning technology?
 Using new operator, we can create another object. But, when new operator is used to create the
object, the object is created by using the initial values as object1. So,the same processing should
be repeated on this object to get the intermediate object,i.e.,object2.
 The other way is to clone the object2, so that we get exact copy of the object. This preserves a
copy of the intermediate object and hence the original object and the cloned objects can be
processed separately. This method is easy because, we can avoid a lot of processing to be done
on the object.
Program:
import java.io.*;
import java.util.*;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

class Employee implements Cloneable


{
int id;
String name;
Employee(int id,String name)
{
this.id=id;
this.name=name;
}
void getData()
{
System.out.println("id:"+id);
System.out.println("name:"+name);
}
public Object myClone() throws CloneNotSupportedException
{
return super.clone();
}
}
class CloneDemo
{
public static void main(String args[])throws CloneNotSupportedException
{
Employee e1=new Employee(10,"cnu");
System.out.println("original object:");
e1.getData();
Employee e2=(Employee)e1.myClone();
System.out.println("cloned object:");
e2.getData();
System.exit(0);
}
}
Output: original object:id:10
Name:cnu
cloned object:id:10
Name:cnu
Subtype & Substitutability

Subclass:when a new class is constructed using inheritance and contains an ‘extends’ keyword in the
program’s source description then that class is said to be subclass. Generally, a subclass is similar to a
subtype.

Inheritance is a concept where subclass (new classes) can be produced from existing classes (super
class).The newly created subclass acquires all the features of existing classes from where it is derived.

Class subclassname extends superclassname{}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

Referenced Data Types: class is a references data type. It is used to store the several values. Converting
a class into another class type is also possible through casting. But the classes should have some
relationship between them by the way of inheritance.

Example: You cannot convert a Dog class into a Horse class, as those classes do not have any
relationship between them. But you can convert a College class into a University class, since College is
derived from University. And you can convert a Department class into a College,since Department is
subclass of College class.

University Super class

College Sub class

Department sub-sub class

Type Casting: Converting one data type into another data type is called ‘type casting’ or simply
‘casting’. Whenever we assign a value to a variable using assignment operator, the Java compiler checks
for uniformity and hence the data types at both sides should be same. If the data types are not same, then
we should convert the types to become same at the both sides.

To convert the data type, we use ‘cast’ operator. Cast operator means writing the data type between
simple braces, before a variable or method whose value is to be converted.

Subtype: A subtype describes the relationship between different types that will lead to explicit
recognition of substitution principle,

A type y will be a subtype(subclass) of x(superclass) only if it holds the following two conditions,

1. A variable of type x can be assigned an instance of y.


2. The resulting value can e used by the variable without changing the behavior,

Substitutability: Means the type of a variable can differ from the type of the value stored in that
variable.

When interfaces are used, there will be a possibility of the occurrence of substitutability.

Types of Castings:

1. Widening or Implicit or Up-casting:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

Converting lower data type into higher data type is widening. And it is performed by system, here is no
need to put cast operator hence it is implicit casting. Lower datatype (subtype or subclass) is promoted
to up(supertype or superclass), hence it is called as up-casting.

Note: In inheritance it is Generalization.

Example:
class One
{
public void show1()
{
System.out.println("hi");
}
}
class Two extends One
{
public void show2()
{
System.out.println("hello");
}
}
class WCast
{
public static void main(String args[])
{
One o=new Two();
o.show1();

}
}
Output: hi
2. Narrowing or Explicit or Down-casting:
Converting Higher data type(super class) into lower (subclass) data type is called narrowing. And it is
performed by the programmer hence it is explicit casting. Here must and should we have to put cast
operator. Higher data type(super class) is dragged to down, hence it is down casting.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

Note: In Inheritance it is Specialization.


Example:
class One
{
public void show1()
{
System.out.println("hi");
}
}
class Two extends One
{
public void show2()
{
System.out.println("hello");
}
}
class NCast
{
public static void main(String args[])
{
One o=(One) new Two();
Two t=(Two)o;
t.show1();
t.show2();
}
}
Output: hi
Hello
Two types of casting in one program:
class Flower
{
public void smell()
{
System.out.println("flowery smell");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 12 Unit- II

}
}
class Rose extends Flower
{
public void smell()
{
System.out.println("rose smell");

public static void main(String args[])


{
Flower f=new Flower();
Rose r=new Rose();
f=r; Implicitly substituting
f.smell();
//r=f; destination source
r=(Rose)f; Explicitly substituting
f.smell();
} cast operator
}
Output: rose smell
Rose smell

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

Specialization, specification, construction, extension, limitation, combination

Forms of Inheritance

The various forms of inheritance are,

 Specialization
 Specification
 Construction
 Extension
 Limitation
 Combination

Specialization: Inheritance is commonly used for specialization purpose. Here, a child class or a new
class is a specialized form of the parent class and it conforms to all specifications of the parent. Thus, a
sub type(sub class) is created using this form and the substitutability is also maintained explicitly.

Example program:
Narrow casting or explicit casting program.
class One
{
public void show1()
{
System.out.println("hi");
}
}
class Two extends One
{
public void show2()
{
System.out.println("hello");
}
}
class NCast
{
public static void main(String args[])
{

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

One o=(One) new Two();


Two t=(Two)o;
t.show1();
t.show2();
}
}
Output: hi
Hello

Specification: Inheritance can also be used to allow the classes to implement those methods that have
the same names. The parent class can define operations with or without implementations. The operation
whose implementation is not defined in the parent class will be defined in the child class. Such kind of
parent class that defines abstract methods is also called as “abstract specification class”.

To support inheritance of specification, java language provides two different techniques. They are,

1 Using interfaces 2. Using classes

Example program:
interface Animal
{
public abstract void moves();
}
interface Bird
{
void fly();
}
public class InterfaceDemo2 implements Animal,Bird
{
public void moves()
{
System.out.println("animal move on land");
}
public void fly()
{

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

System.out.println("birds fly in air");


}
public static void main(String args[])
{
InterfaceDemo2 id=new InterfaceDemo2();
id.moves();
id.fly();
}
}
Output: animal move on land
Birds fly in air
2.using classes example program:
import java.io.*;
abstract class A
{
abstract void display();

}
class B extends A
{
void display()
{
System.out.println("hello");

}
public static void main(String args[])
{
B b=new B();
b.display();

}
}
Output:hello

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

Construction: A child class can inherit most of the properties from its parent class, even if these classes
do not have abstract concept in common.

Example program: single inheritance

import java.io.*;
class A
{
void display()
{
System.out.println("hi");
}

}
class B extends A
{
void display()
{
System.out.println("hello");

}
public static void main(String args[])
{
B b=new B();
b.display();

}
}
Output:hello

Extension: The sub classification for extension is achieved if a child class adds an additional behavior
to the parent class without modifying the attributes that are inherited from that parent class. The parent

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

class functionality is made available to its child class without any modifications. Thus, such classes are
also the subtypes because the subclassification for extension also supports the substitutability principle.

Example program is Multi level inheritance:

// Create a super class.


class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

Limitation: If a subclass restricts few behaviors to be used that are inherited from the parent class, then
the sub classification for limitation was occurred.

Example program for Limitation is using final methods with inheritance:

import java.io.*;
class A
{
final void display();
}
class B extends A
{
void display()
{
System.out.println("hello");

}
public static void main(String args[])
{
B b=new B();
b.display();

}
}

Output: display() in B cannot be overridde display() in a; overridden method is final.

Combination: Java language does not allow a subclass to inherit more than one class. Thus, solution for
this problem is to extend a parent class and implement any number of interfaces.

Example program is multiple inheritance.


interface Animal
{
public abstract void moves();

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

}
interface Bird
{
void fly();
}
public class InterfaceDemo2 implements Animal,Bird
{
public void moves()
{
System.out.println("animal move on land");
}
public void fly()
{
System.out.println("birds fly in air");
}
public static void main(String args[])
{
InterfaceDemo2 id=new InterfaceDemo2();
id.moves();
id.fly();
}
}

Output:
animal move on land
birds fly in air
Summary of Forms of Inheritance:

• Specialization. The child class is a special case of the parent class; in other words, the child class
is a subtype of the parent class.

• Specification. The parent class defines behavior that is implemented in the child class but not in
the parent class.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 13 Unit- II

• Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.

• Generalization. The child class modifies or overrides some of the methods of the parent class.
(widening.up-casting)

• Extension. The child class adds new functionality to the parent class, but does not change any
inherited behavior.

• Limitation. The child class restricts the use of some of the behavior inherited from the parent
class.

• Variance. The child class and parent class are variants of each other, and the class-subclass
relationship is arbitrary.

• Combination. The child class inherits features from more than one parent class. This is multiple
inheritance and will be the subject of a later chapter.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

Benefits of Inheritance, super keyword

The benefits of inheritance are as follows:

 Increased reliability
 Software reusability
 Code sharing
 To create software components
 Consistency of interface
 Polymorphism
 Information hiding
 Rapid prototyping

Increased Reliability: If a code is frequently executed then it will have very less amount of bugs,
compared to code that is not frequently executed.(error free code)

Software reusability: properties of a parent class can be inherited by a child class. But, it does not
require to rewrite the code of the inherited property in the child class. In OOPs, methods can be written
once but can be reused.

Code sharing: At one level of code sharing multiple projects or users can use a single class.

Software components: Programmers can construct software components that are reusable using
inheritance.

Consistency of interfaces: when multiple classes inherit the behavior of a single super class all those
classes will now have the same behavior.

Polymorphism: Oops follows the bottom-up approach. And abstraction is high at top, these are exhibit
the different behaviors based on instances.

Information hiding: interfaces’s or abstracts classes’s methods definition is in super class, methods
implementation is in subclasses. Means we know what to do but not how to do.

Rapid prototyping: By using the same code for different purposes, we can reduce the lengthy code of the
program.

Cost of inheritance:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

Following are the costs of inheritance:

 Program size: If the cost of memory decreases, then the program size does not matter. Instead of
limiting the program sizes, there is a need to produce code rapidly that has high quality and is
also error-free.
 Execution speed: The specialized code is much faster than the inherited methods that manage the
random subclasses.
 Program complexity: Complexity of a program may be increased if inheritance is overused.
 Message-passing: The cost of message passing is very less when execution speed is considered.

Super Uses

Whenever a subclass needs to refer to its immediate super class, it can do so by the use of the keyword
super.

Super has the two general forms.

1. super (args-list) : calls the Super class’s constructor.


2. Super . member: To access a member of the super class that has been hidden by a member of a
subclass. Member may be variable or method.

Use: Overriden methods allow Java to support Run-time polymorphism. This leads to Robustness by
Reusability.

The keyword ‘super’:

super can be used to refer super class variables as: super.variable

super can be used to refer super class methods as: super.method ()

super can be used to refer super class constructor as: super (values)

Example program for


super can be used to refer super class constructor as: super (values)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

class Figure
{
double dim1;
double dim2;
Figure(double a,double b)
{
dim1=a;
dim2=b;
}
double area()
{
System.out.println("Area for figure is undefined");
return 0;
}

}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{ calling super class constructor
super(a,b);
}
double area()
{
System.out.println("Inside area for rectangle");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

double area()
{
System.out.println("Inside area for triangle");
return dim1*dim2/2;
}
}
class FindAreas
{
public static void main(String args[])
{
Figure f=new Figure(10,10);
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
System.out.println("area is"+figref.area());
figref=t;
System.out.println("area is"+figref.area());
figref=f;
System.out.println("area is"+figref.area());
}
}
OUTPUT:
Inside area for rectangle
area is 45
Inside area for triangle
area is 40
Inside area for figure is undefined
area is 0

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

2.Accessing the member of a super class:

The second form of super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used. This usage has the following general form:

super.member;

Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name in the
superclass. Consider this simple class hierarchy:

// Using super to overcome name hiding.


class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:

i in superclass: 1

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 14 Unit- II

i in subclass: 2

Although the instance variable i in B hides the i in A, super allows access to the i defined in the
superclass. As you will see, super can also be used to call methods that are hidden by a subclass.

Super uses: super class’s method access

import java.io.*;
class A
{
void display()
{
System.out.println("hi");
}
}
class B extends A
{
void display() calling super class method
{
super.display();
System.out.println("hello");

}
static public void main(String args[])
{
B b=new B();
b.display();
}
}
Output: hi
Hello

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 15 Unit- II

Using final with Inheritance


Final is a keyword in Java which generically means, cannot be changed once created. Final behaves very
differently when variables, methods and classes. Any final keyword when declared with variables,
methods and classes specifically means:

 A final variable cannot be reassigned once initialized.


 A final method cannot be overridden.
 A final class cannot be extended.

Classes are usually declared final for either performance or security reasons. Final methods work like
inline code of C++.
Final with variables
Final variables work like const of C-language that can’t be altered in the whole program. That is, final
variables once created can’t be changed and they must be used as it is by all the program code.
Example program:
import java.io.*;
class FinalVar
{
static
{
int x=10;
final int y=20;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
x=30;
y=40;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
}
}
Output:
Cannot assign a value to final variable y

Final with methods:


Generally, a super class method can be overridden by the subclass if it wants a different functionality.
Or, it can call the same method if it wants the same functionality. If the super class desires that the
subclass should not override its method, it declares the method as final. That is, methods declared final
in the super class can not be overridden in the subclass(else it is compilation error). But, the subclass can
access with its object as usual.
Example program:
import java.io.*;
class A
{
final void display()

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 15 Unit- II

{
System.out.println("hi");
}

}
class B extends A
{
void display()
{
super.display();
System.out.println("hello");
}
static public void main(String args[])
{
B b=new B();
b.display();
}
}
Output:
Display() in B cannot override display() in A; overridden method is final.

Final with classes:


If we want the class not be sub-classed(or extended) by any other class, declare it final. Classes declared
final can not be extended. That is, any class can use the methods of a final class by creating an object of
the final class and call the methods with the object(final class object).
Example program:
import java.io.*;
final class Demo1
{
public void display()
{
System.out.println("hi");
}
}
public class Demo3 extends Demo1
{
public static void main(String args[])
{
Demo1 d=new Demo1();
d.display();

}
}
Output:
Cannot inherit from final Demo1

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 16 Unit- II

Polymorphism
Polymorphism came from the two Greek words ‘poly’ means many and morphos means forms.
If the same method has ability to take more than one form to perform several tasks then it is
called polymorphism.
It is of two types: Dynamic polymorphism and Static polymorphism.
Dynamic Polymorphism:
The polymorphism exhibited at run time is called dynamic polymorphism. In this dynamic
polymorphism a method call is linked with method body at the time of execution by JVM. Java
compiler does not know which method is called at the time of compilation. This is also known as
dynamic binding or run time polymorphism.
Method overloading and method overriding are examples of Dynamic Polymorphism in Java.
 Method Overloading: Writing two or more methods with the same name, but with a
difference in the method signatures is called method over loading. Method signature
represents the method name along with the method parameters. In method over loading JVM
understands which method is called depending upon the difference in the method signature.
The difference may be due to the following:
 There is a difference in the no. of parameters.

void add (int a,int b)


void add (int a,int b,int c)
 There is a difference in the data types of parameters.

void add (int a,float b)


void add (double a,double b)
 There is a difference in the sequence of parameters.

void swap (int a,char b)


void swap (char a,int b)
A program to create a class which contains two methods with the same
name but with different signatures.
// overloading of methods --------- Dynamic polymorphism
class Sample
{ void add(int a,int b)
{
System.out.println ("sum of two="+ (a+b));
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 16 Unit- II

void add(int a,int b,int c)


{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{ public static void main(String[] args)
{ Sample s=new Sample ( );
s.add (20, 25);
s.add (20, 25, 30);
}
}
Output: sum of two=45
Sun of three=75

Method Overriding:
Writing two or more methods in super & sub classes with same name and same signatures is called
method overriding. In method overriding JVM executes a method depending on the type of the
object.
Write a program that contains a super and sub class which contains a method
with same name and same method signature, behavior of the method is dynamically decided.
//overriding of methods --------------- Dynamic polymorphism
class Animal
{ void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{ void move()

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 16 Unit- II

{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{ public static void main(String args[])
{ Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
a.move (); // runs the method in Animal class
b.move (); //Runs the method in Dog class
}
}
Output: Animals can move
Dogs can walk and run

Achieving method overloading & method overriding using instance methods is an example of
dynamic polymorphism.
Static Polymorphism: The polymorphism exhibited at compile time is called Static polymorphism.
Here the compiler knows which method is called at the compilation. This is also called compile time
polymorphism or static binding.
Achieving method overloading & method overriding using private, static and final methods is an
example of Static Polymorphism.
Write a program to illustrate static polymorphism.
//Static Polymorphism
class Animal
{ static void move ()
{ System.out.println ("Animals can move");
}
}
class Dog extends Animal
{ static void move ()

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 16 Unit- II

{ System.out.println ("Dogs can walk and run");


}
}
public class StaticPoly
{ public static void main(String args[])
{ Animal.move ();
Dog.move ();
}
}

Output: Animals can move


Dogs can walk and run

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 17 Unit- II

Abstract classes

A method with method body is called concrete method. In general any class will have all
concrete methods. A method without method body is called abstract method. A class that
contains abstract method is called abstract class. It is possible to implement the abstract methods
differently in the subclasses of an abstract class. These different implementations will help the
programmer to perform different tasks depending on the need of the sub classes. Moreover, the common
members of the abstract class are also shared by the sub classes.

 The abstract methods and abstract class should be declared using the keyword abstract.
 We cannot create objects to abstract class because it is having incomplete code. Whenever
an abstract class is created, subclass should be created to it and the abstract methods
should be implemented in the subclasses, then we can create objects to the subclasses.
 An abstract class is a class with zero or more abstract methods
 An abstract class contains instance variables & concrete methods in addition to abstract

methods.

 It is not possible to create objects to abstract class.


 But we can create a reference of abstract class type.
 All the abstract methods of the abstract class should be implemented in its sub classes.
 If any method is not implemented, then that sub class should be declared as ‘abstract’.
 Abstract class reference can be used to refer to the objects of its sub classes.
 Abstract class references cannot refer to the individual methods of sub classes.
 A class cannot be both ‘abstract’ & ‘final’.

e.g.: final abstract class A // invalid

Abstraction refers to the act of representing essential features without including the background details
or explanations. Classes use the concept of abstraction and are defined as a list of attributes and methods
to operate on these attributes. They encapsulate all the essential features of the objects that are to be
created since the classes use the concept of data abstraction they are known as Abstract Data Types.

An essential element of object-oriented programming is abstraction. Humans manage complexity


through abstraction. For example, people do not think of a car as a set of tens of thousands of individual
parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the grocery store without being overwhelmed by the complexity of the
parts that form the car. They can ignore the details of how the engine, transmission, and braking systems
work. Instead they are free to utilize the object as a whole.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 17 Unit- II

A powerful way to manage abstraction is through the use of hierarchical classifications. This allows you
to layer the semantics of complex systems, breaking them into more manageable pieces. From the
outside, the car is a single object. Once inside, you see that the car consists of several subsystems:
steering, brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of these
subsystems is made up of more specialized units.

For instance, the sound system consists of a radio, a CD player, and/or a tape player. The point is that
you manage the complexity of the car (or any other complex system) through the use of hierarchical
abstractions.

Hierarchical abstractions of complex systems can also be applied to computer programs. The data from a
traditional process-oriented program can be transformed by abstraction into its component objects. A
sequence of process steps can become a collection of messages between these objects. Thus, each of
these objects describes its own unique behavior. You can treat these objects as concrete entities that
respond to messages telling them to do something. This is the essence of object-oriented programming.

Object-oriented concepts form the heart of Java just as they form the basis for human understanding. It
is important that you understand how these concepts translate into programs. As you will see, object-
oriented programming is a powerful and natural paradigm for creating programs that survive the
inevitable changes accompanying the life cycle of any major software project, including conception,
growth, and aging. For example, once you have well-defined objects and clean, reliable interfaces to
those objects, you can gracefully decommission or replace parts of an older system without fear.

Abstract class: Any class that contains one or more abstract methods must also be declared abstract.

To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the
beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any
subclass of an abstract class must either implement all of the abstract methods in the super class, or be
itself declared abstract.

There are situations in which you will want to define a super class that declares the structure of a given
abstraction without providing a complete implementation of every method. That is, sometimes you will
want to create a super class that only defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the
methods that the subclasses must implement. One way this situation can occur is when a super class is

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 17 Unit- II

unable to create a meaningful implementation for a method. This is the case with the class Figure used in
the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display
the area of any type of object. As you will see as you create your own class libraries, it is not uncommon
for a method to have no meaningful definition in the context of its super class. You can handle this
situation two ways. One way, as shown in the previous example, is to simply have it report a warning
message. While this approach can be useful in certain situations—such as debugging—it is not usually
appropriate. You may have methods which must be overridden by the subclass in order for the subclass
to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case,
you want some way to ensure that a subclass does, indeed, override all necessary methods. Java’s
solution to this problem is the abstract method.

Abstract method: A method that is declared but not implemented (no body). Abstract methods are used
to ensure that subclasses implement the method.

You can require that certain methods be overridden by subclasses by specifying the abstract type
modifier. These methods are sometimes referred to as subclasses responsibility because they have no
implementation specified in the super class. Thus, a subclass must override them—it cannot simply use
the version defined in the super class. To declare an abstract method, use this general form:

abstract type name(parameter-list);

As you can see, no method body is present.

An abstract class can be sub classed and can’t be instantiated.

Write an example program for abstract class.

// Using abstract methods and classes.

abstract class Figure

{ double dim1;

double dim2;

Figure (double a, double b)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 17 Unit- II

{ dim1 = a;

dim2 = b;

abstract double area (); // area is now an abstract method

class Rectangle extends Figure

{ Rectangle (double a, double b)

{ super (a, b);

double area () // override area for rectangle

{ System.out.println ("Inside Area of Rectangle.");

return dim1 * dim2;

class Triangle extends Figure

{ Triangle (double a, double b)

{ super (a, b);

double area() // override area for right triangle

{ System.out.println ("Inside Area of Triangle.");

return dim1 * dim2 / 2;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 17 Unit- II

class AbstractAreas

{ public static void main(String args[])

{ // Figure f = new Figure(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

System.out.println("Area is " + r.area());

System.out.println("Area is " + t.area());

output:

Inside area for Rectangle.

Area is 45.0

Inside are for Triangle.

Area is 40.0

As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since
it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try
creating a subclass that does not override area( ). You will receive a compile-time error.

Although it is not possible to create an object of type Figure, you can create a reference variable of type
Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer
to an object of any class derived from Figure. As explained, it is through superclass reference variables
that overridden methods are resolved at run time.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 18 Unit- II

Defining , creating and accessing a Package

Packages are containers for classes that are used to keep the class name space compartmentalized.
Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

A package is a container of classes and interfaces. A package represents a directory that contains related
group of classes and interfaces. For example, when we write statemens like:

import java.io.*;

Here we are importing classes of java.io package. Here, java is a directory name and io is another sub
directory within it. The ‘*’ represents all the classes and interfaces of that io sub directory. We can
create our own packages called user-defined packages or extend the available packages. User-defined
packages can also be imported into other classes and used exactly in the same way as the Built-in
packages.

USE: Packages provide reusability.

ADVANTAGES OF PACKAGES:

1. Packages are useful to arrange related classes and interfaces into a group. This makes all the
classes and interfaces performing the same task to put together in the same package. For example
, in Java, all the classes and interfaces which perform input and output operations are stored in
java.io. package.

2. Packages hide the classes and interfaces in a separate sub directory, so that accidental deletion of
classes and interfaces will not take place.

3. The classes and interfaces of a package are isolated from the classes and interfaces of another
package. This means that we can use same names for classes of two different classes. For
example, there is a Date class in java.util package and also there is another Date class in java.sql
package.

4. A group of package called a library. The classes and interfaces of a package are likes books in a
library and can be reused several times. This reusability nature of packages makes programming
easy. Just think, the package in Java are created by JavaSoft people only once, and millions of
programmers all over the world are daily by using them in various programs.

5.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 18 Unit- II

Different Types of Packages:

There are two types of packages in Java. They are:

1 Built-in packages

2 User-defined packages

Built-in packages:

These are the packages which are already available in Java language. These packages provide all most
all necessary classes, interfaces and methods for the programmer to perform any task in his programs.
Since, Java has an extensie library of packages, a programmer need not think about logic for doing any
task. For everything, there is a method available in Java and that method can be used by the programmer
without developing the logic on his own. This makes the programming easy. Here, we introduce some of
the important packages of Java SE:

Java.lang: lang stands for language. This package got primary classes and interfaces essential for
developing a basic Java program. It consists of wrapper classes(Integer, Character, Float etc), which are
useful to convert primitive data types into objects. There are classes like String, SttringBuffer,
StringBuilder classes to handle strings. There is a thread class to create various individual processes.
Runtime and System classes are also present in java.lang package which contain methods to execute an
application and find the total memory and free memory available in JVM.

Java.util: util stands for utility. This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections. There are also classes for
handling Date and Time operations.

Java.io: io stands for input and output. This package contains streams. A stream represents flow of data
from one place to another place. Streams are useful to store data in the form of files and also to perform
input-output related tasks.

Java.awt: awt stands for abstract window toolkit. This helps to develop GUI(Graphical user Interfaces)
where programs with colorful screens, paintings and images etc., can be developed. It consists of an
important sub package, java.awt.event, which is useful to provide action for components like push
buttons, radio buttons, menus etc.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 18 Unit- II

Javax.swing: this package helps to develop GUI like java.awt. The ‘x’ in javax represents that it is an
extended package which means it is a package developed from another package by adding new features
to it. In fact, javax.swing is an extended package of java.awt.

Java.net: net stands for network. Client-Server programming can be done by using this package. Classes
related to obtaining authentication for network, creating sockets at client and server to establish
communication between them are also available in java.net package.

Java.applet: applets are programs which come from a server into a client and get executed on the client
machine on a network. Applet class of this package is useful to create and use applets.

Java.text: this package has two important classes, DateFormat to format dates and times, and
NumberFormat which is useful to format numeric values.

Java.sql: sql stands structured query language. This package helps to connect to databases like Oracle or
Sybase, retrieve the data from them and use it in a Java program.

User-Defined packages:

Just like the built in packages shown earlier, the users of the Java language can also create their own
packages. They are called user-defined packages. User-defined packages can also be imported into other
classes and used exactly in the same way as the Built-in packages.

CREATING AND IMPORTING PACKAGES

package packagename; //to create a package

package packagename.subpackagename;//to create a sub package within a package.

e.g.: package pack;

3 The first statement in the program must be package statement while creating a package.

4 While creating a package except instance variables, declare all the members and the class
itself as public then only the public members are available outside the package to other
programs.

Program 1: Write a program to create a package pack with Addition class.

//creating a package

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 18 Unit- II

package pack;

public class Addition

{ private double d1,d2;

public Addition(double a,double b)

{ d1 = a;

d2 = b;

public void sum()

{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );

Program 2: Write a program to use the Addition class of package pack.

//Using the package pack

import pack.Addition;

class Use

{ public static void main(String args[])

{ Addition ob1 = new Addition(10,20);

ob1.sum();

Program 3: Write a program to add one more class Subtraction to the same package pack.

//Adding one more class to package pack:

package pack;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 18 Unit- II

public class Subtraction

{ private double d1,d2;

public Subtraction(double a, double b)

{ d1 = a;

d2 = b;

public void difference()

{ System.out.println ("Sum of two given numbers is : " + (d1 - d2) );

Program 4: Write a program to access all the classes in the package pack.

//To import all the classes and interfaces in a class using import pack.*;

import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
}
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs will not exist in
the current directory. Delete them from the current directory as they cause confusion for the Java
compiler. The compiler looks for byte code in Addition.java and Subtraction.java files and there it gets
no byte code and hence it flags some errors.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 19 Unit- II

UNDERSTANDING CLASSPATH

If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in the
classpath.

The CLASSPATH is an environment variable that tells the Java compiler where to look for class files
to import.

If our package exists in e:\sub then we need to set class path as follows:

We are setting the classpath to e:\sub directory and current directory (.) an %CLASSPATH%
means retain the already available classpath as it is.

Creating Sub package in a package: We can create sub package in a package in the format:

package packagename.subpackagename;

e.g.: package pack1.pack2;

Here, we are creating pack2 subpackage which is created inside pack1 package. To use the
classes and interfaces of pack2, we can write import statement as:

import pack1.pack2;

Program 5: Program to show how to create a subpackage in a package.

//Creating a subpackage in a package

package pack1.pack2;

public class Sample

{ public void show ()

System.out.println ("Hello Java Learners");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 20 Unit- II

Member Access Rules


Access Specifier: Specifies the scope of the data members, class and methods.
1 private members of the class are available with in the class only. The scope of private
members of the class is “CLASS SCOPE”.
2 public members of the class are available anywhere . The scope of public members of the class
is "GLOBAL SCOPE".
3 default members of the class are available with in the class, outside the class and in its sub class
of same package. It is not available outside the package. So the scope of default
members of the class is "PACKAGE SCOPE".
4 protected members of the class are available with in the class, outside the class and in its sub
class of same package and also available to subclasses in different package also.

Write a program to create class A with different access specifiers.


//create a package same
package same;
public class A
{ private int a=1;
public int b = 2;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 20 Unit- II

protected int c = 3;
int d = 4;
}
Write a program for creating class B in the same package.
//class B of same package
package same;
import same.A;
public class B
{
public static void main(String args[])
{
A obj = new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Write a program for creating class C of another package.
package another;
import same.A;
public class C extends A
{ public static void main(String args[])
{ C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

Interface: Definition, Implementation

 A programmer uses an abstract class when there are some common features shared by all
the objects. A programmer writes an interface when all the features have different
implementations for different objects.
 Interfaces are written when the programmer wants to leave the implementation to third
party vendors. An interface is a specification of method prototypes. All the methods in an
interface are abstract methods.

1 An interface is a specification of method prototypes.

2 An interface contains zero or more abstract methods.

3 All the methods of interface are public, abstract by default.

4 An interface may contain variables which are by default public static final.

5 Once an interface is written any third party vendor can implement it.

6 All the methods of the interface should be implemented in its implementation classes.

7 If any one of the method is not implemented, then that implementation class should be
declared as abstract.

8 We cannot create an object to an interface.

9 We can create a reference variable to an interface.

10 An interface cannot implement another interface.

11 An interface can extend another interface.

12 A class can implement multiple interfaces.

13 Abstractions

14 Multiple Inheritance

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

An interface is defined much like a class. This is the general form of an interface:

access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods defined by the
interface. The general form of a class that includes the implements clause looks like this:

class classname [extends superclass] [implements interface [,interface...]] {

// class-body

If a class implements more than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same method will be used by clients of
either interface. The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature specified in the interface
definition.

Partial Implementations

If a class includes an interface but does not fully implement the methods defined by that

interface, then that class must be declared as abstract. For example:

abstract class Incomplete implements Callback {

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

int a, b;

void show() {

System.out.println(a + " " + b);

// ...

Here, the class Incomplete does not implement callback( ) and must be declared as abstract.

Any class that inherits Incomplete must implement callback( ) or be declared abstract itself.

Nested Interfaces

An interface can be declared a member of a class or another interface. Such an interface is

called a member interface or a nested interface. Anested interface can be declared as public,

private, or protected. This differs from a top-level interface, which must either be declared

as public or use the default access level, as previously described. When a nested interface is

used outside of its enclosing scope, it must be qualified by the name of the class or interface

of which it is a member. Thus, outside of the class or interface in which a nested interface is

declared, its name must be fully qualified.

Here is an example that demonstrates a nested interface:

// A nested interface example.


// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

// B implements the nested interface.


class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
Notice that A defines a member interface called NestedIF and that it is declared public. Next, B
implements the nested interface by specifying implements

A.NestedIF

Notice that the name is fully qualified by the enclosing class’ name. Inside the main( ) method, an
A.NestedIF reference called nif is created, and it is assigned a reference to a B object. Because B
implements A.NestedIF, this is legal.

Program 1: Write an example program for interface


interface Shape
{ void area ();
void volume ();
double pi = 3.14;
}
class Circle implements Shape
{ double r;
Circle (double radius)
{ r = radius;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

}
public void area ()
{ System.out.println ("Area of a circle is : " + pi*r*r );
}
public void volume ()
{ System.out.println ("Volume of a circle is : " + 2*pi*r);
}
}
class Rectangle implements Shape
{ double l,b;
Rectangle (double length, double breadth)
{ l = length;
b = breadth;
}
public void area ()
{ System.out.println ("Area of a Rectangle is : " + l*b );
}
public void volume ()
{ System.out.println ("Volume of a Rectangle is : " + 2*(l+b));
}
}
class InterfaceDemo
{ public static void main (String args[])
{ Circle ob1 = new Circle (10.2);
ob1.area ();
ob1.volume ();
Rectangle ob2 = new Rectangle (12.6, 23.55);
ob2.area ();
ob2.volume (); } }

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

APPLYING INTERFACES

 To understand the power of interfaces, let’s look at a more practical example. In earlier chapters,
you developed a class called Stack that implemented a simple fixed-size stack. However, there
are many ways to implement a stack.
 For example, the stack can be of a fixed size or it can be “growable.” The stack can also be held
in an array, a linked list, a binary tree, and so on. No matter how the stack is implemented, the
interface to the stack remains the same.
 That is, the methods push( ) and pop( ) define the interface to the stack independently of the
details of the implementation. Because the interface to a stack is separate from its
implementation, it is easy to define a stack interface, leaving it to each implementation to define
the specifics. Let’s look at two examples.

First, here is the interface that defines an integer stack. Put this in a file called IntStack.java.

This interface will be used by both stack implementations.

// Define an integer stack interface.

interface IntStack {

void push(int item); // store an item

int pop(); // retrieve an item

VARIABLES IN INTERFACES:

You can use interfaces to import shared constants into multiple classes by simply declaring an interface
that contains variables that are initialized to the desired values. When you include that interface in a
class (that is, when you “implement” the interface), all of those variable names will be in scope as
constants. (This is similar to using a header file in C/C++ to create a large number of #defined constants
or const declarations.) If an interface contains no methods, then any class that includes such an interface
doesn’t actually implement anything.

It is as if that class were importing the constant fields into the class name space as final variables. The
next example uses this technique to implement an automated “decision maker”:

import java.util.Random;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
return NO; // 30%
else if (prob < 60)
return YES; // 30%
else if (prob < 75)
return LATER; // 15%
else if (prob < 98)
return SOON; // 13%
else
return NEVER; // 2%
}
}
class AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 21 Unit- II

System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Notice that this program makes use of one of Java’s standard classes: Random. This class provides
pseudorandom numbers. It contains several methods that allow you to obtain random numbers in the
form required by your program. In this example, the method nextDouble( ) is used. It returns random
numbers in the range 0.0 to 1.0.

In this sample program, the two classes, Question and AskMe, both implement the SharedConstants
interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined. Inside each class, the
code refers to these constants as if each class had defined or inherited them directly. Here is the output of
a sample run of this program. Note that the results are different each time it is run.

Later
Soon
No
Yes

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 22 Unit- II

Extending Interfaces & Differences b/w classes and interfaces

Extending Interfaces

 One interface can inherit another by use of the keyword extends. The syntax is the same as

for inheriting classes.

 When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
 Following is an example:

// One interface can extend one or more interfaces..

interface A {

void meth1();

void meth2();

// B now includes meth1() and meth2() -- it adds meth3().

interface B extends A {

void meth3();

// This class must implement all of A and B

class MyClass implements B {

public void meth1() {

System.out.println("Implement meth1().");

public void meth2() {

System.out.println("Implement meth2().");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 22 Unit- II

public void meth3() {

System.out.println("Implement meth3().");

class IFExtend {

public static void main(String arg[]) {

MyClass ob = new MyClass();

ob.meth1();

ob.meth2();

ob.meth3();

As an experiment, you might want to try removing the implementation for meth1( ) in MyClass. This
will cause a compile-time error. As stated earlier, any class that implements an interface must implement
all methods defined by that interface, including any that are inherited from other interfaces.

Although the examples we’ve included in this book do not make frequent use of packages or interfaces,
both of these tools are an important part of the Java programming environment.

Virtually all real programs that you write in Java will be contained within packages. A number will
probably implement interfaces as well. It is important, therefore, that you be comfortable with their
usage.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes - 22 Unit- II

Differences b/w classes and interfaces

Classes Interfaces

 Classes have instances as variables and  Interfaces have instances as abstract methods
methods with body and final constants variables.

 Inheritance goes with extends keyword  Inheritance goes with implements keywords.

 The variables can have any acess specifier.  The Variables should be public, static, final

 Multiple inheritance is not possible  It is possible

 Classes are created by putting the keyword  Interfaces are created by putting the keyword
class prior to classname. interface prior to interfacename(super class).

 Classes contain any type of methods.  Interfaces contain mustly abstract methods.
Classes may or may not provide the Interfaces are exhibit the fully abstractions
abstractions.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 23 Unit- III

Concepts & Benefits of Exception Handling

Concepts of Exception Handling

 Exception is an abnormal condition that arises during the execution of a program that disrupts
the normal flow of execution.
 Error: When a dynamic linking failure or some other “hard” failure in the virtual machine occurs,
the virtual machine throws an Error.
 Java exception handling is managed via by five keywords: try, catch, throw, throws, finally.
 Try: The try block is said to govern the statements enclosed within it and defines the scope of
any exception associated with it. It detects the exceptions.
 Catch: The catch block contains a series of legal Java statements. These statements are executed
if and when the exception handler is invoked. It holds an exception.
 Throw: To manually throw an exception ,use the keyword throw.
 Throws: Any exception that is thrown out of a method must be specified as such by a throws
clause.
 Finally: Any code that absolutely must be executed after a try block completes is put in a finally
block. After the exception handler has run, the runtime system passes control to the finally block.
 General form of an exception handling:

try

//block of code to monitor for errors

catch(ExceptionType exOb)

//exception handler for ExceptionType

//...

finally

{ //block of code to be executed after try block ends }

Example:

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 23 Unit- III
public class ExceptionDemo
{
public static void main(String args[])throws IOException
{
int subject[]={12,23,34,21};
try
{
System.out.println(subject[2]);
System.out.println("not okay");
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("i caught the exception:"+e);
throw e;
}
finally
{
System.out.println("okay");
}
}
}
Output:
34
Not Okay
Okay
Benefits of Exception Handling:

 First, it allows you to fix the error.


 Second, it prevents the program from automatically terminating.
 Third, it adopts the robustness to program.

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 24 Unit- III

Exception Hierarchy

library
java

lang
Package

object Super Class

Throwable
Super Class

class
Excepion
Error

User-Defined Exceptions Built-in Exceptions


Exception

Checked Exception UnChecked Exception

Virtual Machine Error Compile time Logical Error Linkage Error

Java: JAVA API is a library contains the packages. These were developed by the JavaSoft people of Sun
MicroSystems Inc. used to import the classes in developing the programs.

Lang: lang is a package included in java library. And it is considered as a default package named as
language. Implicitly it is imported into every java programs.

Object: Object is a super class of all classes(user defined, pre-defined classes) directly or indirectly.
Because it is included in the lang package.

Throwable: Throwable is super class of errors and exceptions in java. Throwable is deriving from the
object class.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 24 Unit- III
Error: Error is a class. This is not handled. We known the error in program after the compilation
denoted by the java compiler. Always these were detected at compile time.

An error in a program is called bug. Removing errors from program is called debugging. There are
basically three types of errors in the Java program:

 Compile time errors: Errors which occur due to syntax or format is called compile time
errors. These errors are detected by java compiler at compilation time. Desk checking is
solution for compile-time errors.

Example:
import java.io.*;
class Compile
{
static public void main(String args[])
{
System.out.println("hello")
}
}
Output:
Compile.java:16 ’;’ expected
System.out.println("hello")^
1 error

 Logical errors: These are the errors that occur due to bad logic in the program. These errors are
rectified by comparing the outputs of the program manually.

Example:
class Salary
{
public static void main(String args[])
{
double sal=5000.00;
sal=sal*15/100; //use:sal+=sal*15/100;

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 24 Unit- III
System.out.println("incremented salary:"+sal);
}
}
Output: java Salary
Incremented salary:750.0
Exception: An abnormal event in a program is called Exception.

 Exception may occur at compile time or at runtime.


 Exceptions which occur at compile time are called Checked exceptions.

Checked Exceptions:
 A checked exception is any subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses.
 You should compulsorily handle the checked exceptions in your code, otherwise your code will
not be compiled. i.e you should put the code which may cause checked exception in try block.
"checked" means they will be checked at compiletime itself.
 There are two ways to handle checked exceptions. You may declare the exception using a throws
clause or you may use the try..catch block.
 The most perfect example of Checked Exceptions is IOException which should be handled in
your code Compulsorily or else your Code will throw a Compilation Error.

e.g.: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc

import java.io.*;
class Sample
{
void accept( ) throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.print ("enter ur name: ");
String name=br.readLine ( );
System.out.println ("Hai "+name);
}
}
class ExceptionNotHandle

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 24 Unit- III
{
public static void main (String args[])
{
Sample s=new Sample ( );
s.accept ( );
}
}
Output: javac ExceptionNotHandle.java
ExceptionNotHandle.java:16: unreported exception java.io.IOException must be caught or declared to
be thrown
s.accept();^
1 error
 Exceptions which occur at run time are called Unchecked exceptions.

Unchecked Exceptions :
 Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its
subclasses also are unchecked.
 Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in
your program's logic and cannot be reasonably recovered from at run time.
 With an unchecked exception, however, compiler doesn't force client programmers either to
catch the exception or declare it in a throws clause.
 The most Common examples are ArrayIndexOutOfBoundException,
NUllPointerException ,ClassCastException

eg: ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException etc.

Example:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 24 Unit- III
public class V
{
static public void main(String args[])
{
int d[]={1,2};
d[3]=99;
int a=5,b=0,c;
c=a/b;
System.out.println("c is:"+c);
System.out.println("okay");
}
}
Output:
Exception in thread “main” java.lang.ArrayInde xOutOfBoundsException: 3
At V.main (V.java:6)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III

Usage of try, catch

 To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
 Notice that the call to println( ) inside the try block is never executed. Once an exceptionis
thrown, program control transfers out of the try block into the catch block. Put differently, catch
is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This
will not be printed.” is not displayed. Once the catch statement has executed, program control
continues with the next line in the program following the entire try/catch mechanism.
 A try and its catch statement form a unit. The scope of the catch clause is restricted to those
statements specified by the immediately preceding try statement. A catch statement cannot catch
an exception thrown by another try statement (except in the case of nested try statements,
described shortly).

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
 The goal of most well-constructed catch clauses should be to resolve the exceptional condition
and then continue on as if the error had never happened. For example, in the next program each
iteration of the for loop obtains two random integers. Those two integers are divided by each
other, and the result is used to divide the value 12345. The final result is put into a. If either
division operation causes a divide-by-zero error, it is caught, the value of a is set to zero, and the
program continues.

// Handle an exception and move on.


import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Displaying a Description of an Exception

 Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception. You can display this description in a println( )
statement by simply passing the exception as an argument. For example, the catch block in the
preceding program can be rewritten like this:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
 When this version is substituted in the program, and the program is run, each divide-by-zero
error displays the following message:
 Exception: java.lang.ArithmeticException: / by zero
 While it is of no particular value in this context, the ability to display a description of an
exception is valuable in other circumstances—particularly when you are experimenting with
exceptions or when you are debugging.

Multiple catch Clauses

 In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block. The following
example traps two different exception types:

// Demonstrate multiple catch statements.


class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
System.out.println("After try/catch blocks.");
}
}
 This program will cause a division-by-zero exception if it is started with no command-line
arguments, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].

Here is the output generated by running it both ways:


C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
 When you use multiple catch statements, it is important to remember that exception subclasses
must come before any of their superclasses. This is because a catch statement that uses a
superclass will catch exceptions of that type plus any of its subclasses.
 Thus, a subclass would never be reached if it came after its superclass. Further, in Java,
unreachable code is an error. For example, consider the following program:

/* This program contains an error. A subclass must come before its superclass in a series of catch
statements. If not, unreachable code will be created and a compile-time error will result.*/
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
 If you try to compile this program, you will receive an error message stating that the second
catch statement is unreachable because the exception has already been caught. Since
ArithmeticException is a subclass of Exception, the first catch statement will handle all
Exception-based errors, including ArithmeticException. This means that the second catch
statement will never execute. To fix the problem, reverse the order of the catch statements.

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack. If an inner try
statement does not have a catch handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. This continues until one of the catch statements
succeeds, or until all of the nested try statements are exhausted.

If no catch statement matches, then the Java run-time system will handle the exception. Here is an
example that uses nested try statements:

// An example of nested try statements.

class NestTry {

public static void main(String args[]) {

try {

int a = args.length;

/* If no command-line args are present,

the following statement will generate

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
a divide-by-zero exception. */

int b = 42 / a;

System.out.println("a = " + a);

try { // nested try block

/* If one command-line arg is used,

then a divide-by-zero exception

will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero

/* If two command-line args are used,

then generate an out-of-bounds exception. */

if(a==2) {

int c[] = { 1 };

c[42] = 99; // generate an out-of-bounds exception

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);

} catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);

As you can see, this program nests one try block within another. The program works as follows.When
you execute the program with no command-line arguments, a divide-by-zero exception is generated by

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
the outer try block. Execution of the program with one command-line argument generates a divide-by-
zero exception from within the nested try block. Since the inner block does not catch this exception, it is
passed on to the outer try block, where it is handled. If you execute the program with two command-line
arguments, an array boundary exception is generated from within the inner try block. Here are sample
runs that illustrate each case:

C:\>java NestTry

Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One

a=1

Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One Two

a=2

Array index out-of-bounds:

java.lang.ArrayIndexOutOfBoundsException:42

Nesting of try statements can occur in less obvious ways when method calls are involved.

For example, you can enclose a call to a method within a try block. Inside that method is another try
statement. In this case, the try within the method is still nested inside the outer try block, which calls the
method. Here is the previous program recoded so that the nested try block is moved inside the method
nesttry( ):

/* Try statements can be implicitly nested via

calls to methods. */

class MethNestTry {

static void nesttry(int a) {

try { // nested try block

/* If one command-line arg is used,

then a divide-by-zero exception

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero

/* If two command-line args are used,

then generate an out-of-bounds exception. */

if(a==2) {

int c[] = { 1 };

c[42] = 99; // generate an out-of-bounds exception

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds: " + e);

public static void main(String args[]) {

try {

int a = args.length;

/* If no command-line args are present,

the following statement will generate

a divide-by-zero exception. */

int b = 42 / a;

System.out.println("a = " + a);

nesttry(a);

} catch(ArithmeticException e) {

System.out.println("Divide by 0: " + e);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 25 Unit- III
}

The output of this program is identical to that of the preceding example.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

Usage of throw, throws,finally

throw

So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it
is possible for your program to throw an exception explicitly, using the throw statement. The general
form of throw is shown here:

throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive


types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as
exceptions.

There are two ways you can obtain a Throwable object:

 using a parameter in a catch clause,


 or creating one with the new operator.

The flow of execution stops immediately after the throw statement; any subsequent statements are not
executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the
type of exception. If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception
handler halts the program and prints the stack trace.

Here is a sample program that creates and throws an exception. The handler that catches the exception
rethrows it to the outer handler.

// Demonstrate throw.

class ThrowDemo {

static void demoproc() {

try {

throw new NullPointerException("demo");

} catch(NullPointerException e) {

System.out.println("Caught inside demoproc.");

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

throw e; // rethrow the exception

public static void main(String args[]) {

try {

demoproc();

} catch(NullPointerException e) {

System.out.println("Recaught: " + e);

This program gets two chances to deal with the same error. First, main( ) sets up an exception context
and then calls demoproc( ). The demoproc( )method then sets up another exception-handling context and
immediately throws a new instance of NullPointerException, which is caught on the next line. The
exception is then rethrown. Here is the resulting output:

Caught inside demoproc.

Recaught: java.lang.NullPointerException: demo

The program also illustrates how to create one of Java’s standard exception objects. Pay close attention
to this line:

throw new NullPointerException("demo");

Here, new is used to construct an instance of NullPointerException. Many of Java’s built- in run-time
exceptions have at least two constructors: one with no parameter and one that takes a string parameter.
When the second form is used, the argument specifies a string that describes the exception. This string is
displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call
to getMessage( ), which is defined by Throwable.

throws

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

If a method is capable of causing an exception that it does not handle, it must specify this behavior so
that callers of the method can guard themselves against that exception. You do this by including a throws
clause in the method’s declaration. A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of
their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If
they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

// body of method

Here, exception-list is a comma-separated list of the exceptions that a method can throw. Following is an
example of an incorrect program that tries to throw an exception that it does not catch. Because the
program does not specify a throws clause to declare this fact, the program will not compile.

// This program contains an error and will not compile.

class ThrowsDemo {

static void throwOne() {

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

public static void main(String args[]) {

throwOne();

To make this example compile, you need to make two changes.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

 First, you need to declare that throwOne( ) throws IllegalAccessException.


 Second, main( ) must define a try/catch statement that catches this exception.

The corrected example is shown here:

// This is now correct.

class ThrowsDemo {

static void throwOne() throws IllegalAccessException {

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

public static void main(String args[]) {

try {

throwOne();

} catch (IllegalAccessException e) {

System.out.println("Caught " + e);

Here is the output generated by running this example program:

inside throwOne

caught java.lang.IllegalAccessException: demo

finally

When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a problem in some methods. For

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. The finally keyword is designed to
address this contingency.

 finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block.
 The finally block will execute whether or not an exception is thrown. If an exception is thrown,
the finally block will execute even if no catch statement matches the exception.
 Any time a method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the
method returns.
 This can be useful for closing file handles and freeing up any other resources that might have
been allocated at the beginning of a method with the intent of disposing of them before returning.
 The finally clause is optional. However, each try statement requires at least one catch or a finally
clause.

Here is an example program that shows three methods that exit in various ways, none without executing
their finally clauses:

// Demonstrate finally.

class FinallyDemo {

// Through an exception out of the method.

static void procA() {

try {

System.out.println("inside procA");

throw new RuntimeException("demo");

} finally {

System.out.println("procA's finally");

// Return from within a try block.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

static void procB() {

try {

System.out.println("inside procB");

return;

} finally {

System.out.println("procB's finally");

// Execute a try block normally.

static void procC() {

try {

System.out.println("inside procC");

} finally {

System.out.println("procC's finally");

public static void main(String args[]) {

try {

procA();

} catch (Exception e) {

System.out.println("Exception caught");

procB();

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 26 Unit- III

procC();

 In this example, procA( ) prematurely breaks out of the try by throwing an exception.
 The finally clause is executed on the way out. procB( )’s try statement is exited via a return
statement.
 The finally clause is executed before procB( ) returns. In procC( ), the try statementexecutes
normally, without error. However, the finally block is still executed.

Here is the output generated by the preceding program:

inside procA

procA’s finally

Exception caught

inside procB

procB’s finally

inside procC

procC’s finally

NOTE: If a finally block is associated with a try, the finally block will be executed upon conclusion of
the try.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 27 Unit- III

Built-in Exceptions

Built-in Exceptions

Creating own Exception Sub Classes:

Although Java’s built-in exceptions handle most common errors, you will probably want to create your
own exception types to handle situations specific to your applications. This is quite easy to do: just
define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 27 Unit- III
need to actually implement anything—it is their existence in the type system that allows you to use them
as exceptions.

The Exception class does not define any methods of its own. It does, of course, inherit those methods
provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined
by Throwable available to them. They are shown in Table 10-3.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 27 Unit- III
You may also wish to override one or more of these methods in exception classes that you create.

Exception defines four constructors. Two were added by JDK 1.4 to support chained exceptions,
described in the next section. The other two are shown here:

Exception( )

Exception(String msg)

The first form creates an exception that has no description. The second form lets you specify a
description of the exception. Although specifying a description when an exception is created is often
useful, sometimes it is better to override toString( ). Here’s why: The version of toString( ) defined by
Throwable (and inherited by Exception) first displays the name of the exception followed by a colon,
which is then followed by your description. By overriding toString( ), you can prevent the exception
name and colon from being displayed. This makes for a cleaner output, which is desirable in some cases.

The following example declares a new subclass of Exception and then uses that subclass to signal an
error condition in a method. It overrides the toString( ) method, allowing a carefully tailored description
of the exception to be displayed.

// This program creates a custom exception type.


class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 27 Unit- III
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
This example defines a subclass of Exception called MyException. This subclass is quite simple: it has
only a constructor plus an overloaded toString( ) method that displays the value of the exception. The
ExceptionDemo class defines a method named compute( ) that throws a MyException object. The
exception is thrown when compute( )’s integer parameter is greater than 10. The main( ) method sets up
an exception handler for MyException, then calls compute( ) with a legal value (less than 10) and an
illegal one to show both paths through the code. Here is the result:

Called compute(1)

Normal exit

Called compute(20)

Caught MyException[20]

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 29 Unit- III

User defined Exceptions

Creating User defined Exception Sub Classes:

Although Java’s built-in exceptions handle most common errors, you will probably want to create your
own exception types to handle situations specific to your applications. This is quite easy to do: just
define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t
need to actually implement anything—it is their existence in the type system that allows you to use them
as exceptions.

The Exception class does not define any methods of its own. It does, of course, inherit those methods
provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined
by Throwable available to them. They are shown in Table 10-3.

You may also wish to override one or more of these methods in exception classes that you create.

Exception defines four constructors. Two were added by JDK 1.4 to support chained exceptions,
described in the next section. The other two are shown here:

Exception( )

Exception(String msg)

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 29 Unit- III

The first form creates an exception that has no description. The second form lets you specify a
description of the exception. Although specifying a description when an exception is created is often
useful, sometimes it is better to override toString( ). Here’s why: The version of toString( ) defined by
Throwable (and inherited by Exception) first displays the name of the exception followed by a colon,

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 29 Unit- III
which is then followed by your description. By overriding toString( ), you can prevent the exception
name and colon from being displayed. This makes for a cleaner output, which is desirable in some cases.

The following example declares a new subclass of Exception and then uses that subclass to signal an
error condition in a method. It overrides the toString( ) method, allowing a carefully tailored description
of the exception to be displayed.

// This program creates a custom exception type.


class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 29 Unit- III
}
This example defines a subclass of Exception called MyException. This subclass is quite simple: it has
only a constructor plus an overloaded toString( ) method that displays the value of the exception. The
ExceptionDemo class defines a method named compute( ) that throws a MyException object. The
exception is thrown when compute( )’s integer parameter is greater than 10. The main( ) method sets up
an exception handler for MyException, then calls compute( ) with a legal value (less than 10) and an
illegal one to show both paths through the code. Here is the result:

Called compute(1)

Normal exit

Called compute(20)

Caught MyException[20]

S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 30 Unit- III

Definition of Thread & Life Cycle

Differences b/w Muti threading and Multithreading

Thread: A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares
a common memory area.

MULTI THREADING MULTI TASKING


1). More than one thread running 1). More than one process running
simultaneously simultaneously
2). Its part of a program 2). Its a program.
3).it is a light-weight process. 3). It is a heavy-weight process.
4). Threads are divided into sub threads 4). Process is divided into threads.
5). Within the process threads are 5). Inter process communication is difficulty
communicated.
6). Context switching between threads is 6). Context switching between process is
cheaper. costly
7). It is controlled by Java(JVM) 7). It is controlled by operating System.
8).It is a specialized form of multi tasking 8). It is a generalized form of multi threading.
9). Example: java’s automatic garbage 8). Program compilation at command prompt
collector. window and preparing documentation at MS-
Office.

Thread Life Cycle

Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states. At any time
the thread falls into any one of the states.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 30 Unit- III

Fig: Thread Life Cycle

 The thread that was just created is in the born state.


 The thread remains in this state until the threads start method is called. This causes the thread to
enter the ready state.
 The highest priority ready thread enters the running state when system assigns a processor to the
thread i.e., the thread begins executing.
 When a running thread calls wait the thread enters into a waiting state for the particular
object on which wait was called. Every thread in the waiting state for a given object becomes
ready on a call to notify all by another thread associated with that object.
 When a sleep method is called in a running thread that thread enters into the suspended
(sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A
sleeping thread cannot use a processor even if one is available.
 A thread enters the dead state when its run () method completes (or) terminates for any
reason. A dead thread is eventually be disposed of by the system.
 One common way for a running thread to enter the blocked state is when the thread issues an
input or output request. In this case a blocked thread becomes ready when the input or output
waits for completes. A blocked thread can’t use a processor even if one is available.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 31 Unit- III

Thread Life Cycle

Thread Life Cycle

Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states. At any time
the thread falls into any one of the states.

Fig: Thread Life Cycle

 The thread that was just created is in the born state.


 The thread remains in this state until the threads start method is called. This causes the thread to
enter the ready state.
 The highest priority ready thread enters the running state when system assigns a processor to the
thread i.e., the thread begins executing.
 When a running thread calls wait the thread enters into a waiting state for the particular
object on which wait was called. Every thread in the waiting state for a given object becomes
ready on a call to notify all by another thread associated with that object.
 When a sleep method is called in a running thread that thread enters into the suspended
(sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A
sleeping thread cannot use a processor even if one is available.
 A thread enters the dead state when its run () method completes (or) terminates for any
reason. A dead thread is eventually be disposed of by the system.
 One common way for a running thread to enter the blocked state is when the thread issues an
input or output request. In this case a blocked thread becomes ready when the input or output
waits for completes. A blocked thread can’t use a processor even if one is available.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 32 Unit- III

Thread Creation
We know that in every java program, there is a main thread available already. Apart from this main
thread, we can also create our owen threads in a program. The following steps should be used.

 Write a class that extends Thread class or implements Runnable interface this is available in lang
package.
Class Myclass extends Thread (or)
Class Myclass implements Runnable
 Write public void run () method in that class. This is the method by default executed by any
thread.
Public void run()
{
Statements;
}
 Create an object to my class, so that the run() method is available for execution.
Myclass obj=new Myclass();
 Create a thread and attach it to the object.
Thread t=new Thread(obj);
or

To create a Thread, we can use the following forms:

Thread t1 = new Thread ();


Thread t2 = new Thread (obj);
Thread t3 = new Thread (obj, "thread-name");
 Start running the threads.
t.start();

Syntactical code for creating and running the thread:

Class Myclass extends Thread (or)


Class Myclass implements Runnable
{
Public void run()
{
Statements;
}

}
Class Demo
{
Public static void main(String args[])throws InterruptedException
{
Myclass obj=new Myclass();
Thread t=new Thread(obj);
t.start();

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 32 Unit- III
}
}

Thread Class Methods:

 To know the currently running thread: Thread t = Thread.currentThread ();


 To start a thread: t.start ();
 To stop execution of a thread for a specific time: Thread.sleep (milliseconds);
 To get the name of the thread: String name = t.getName ();
 To set the new name to the thread: t.setName ("New Name");
 To get the priority of the thread: int priority = t.getPriority();
 To set the priority of the thread: t.setPriority (int priority);
 Thread priorities can change from 1 to 10. We can also use the following constants to represent
priorities: Thread.MAX_PRIORITY value is 10

Thread.MIN_PRIORITY value is 1

Thread.NORM_PRIORITY value is 5

 To test if a thread is still alive: t.isAlive () returns true/false


 To wait till a thread dies: t.join ();
 To send a notification to a waiting thread: obj.notify ();
 To send notification to all waiting threads: obj.notifyAll ();
 To wait till the obj is released (till notification is sent): obj.wait ();

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 32 Unit- III

Program : Write a program to create and run a Thread.


//creating and running a Thread
class MyThread extends Thread
{ public void run ()
{ for (int i = 0;i<100;i++)
{
System.out.print (i + "\t");
}
}
}
class TDemo
{ public static void main(String args[])

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 32 Unit- III
{ MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();
}
}
Output:

As a result, the numbers will be displayed starting from 1 to 99 using a for loop. If u want to terminate
the program in the middle, u can press Ctrl+C from the keyboard. This leads to abnormal program
termination. It means the entire program is terminated, not just the thread.

If we want to terminate only the thread that is running the code inside run() method, we should devise
our own mechanism.if we press Ctrl+C, we are abnormally terminating the program. This is dangerous.
Abnormal program termination may cause loss of data and lead to unreliable results. So,we should
terminate the thread only, not the program.hown can we terminate the thread smoothly is the question
now.

Terminating the thread:

A thread will terminate automatically when it comes out of run() method. To terminate the thread on
our own logic. For the following steps can be used

1.Create the Boolean type variable and initialize it to false.

Boolean stop=false;

3.Let us assume that we want to terminate the thread when the user presses <Enter> key. So, when the
user presses that button, make the Boolean type variable as true.

Stop=true;

3.Check this variable in run() method and when it is true, make the thread return from the run() method.

Public void run()

{ If(stop==true) return; }

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 32 Unit- III
Program to showing how to terminate the thread by pressing the enter button
import java.io.*;
class MyThread implements Runnable
{
boolean stop=false;
public void run ()
{
for (int i = 0;i<=100000;i++)
{
System.out.print (i + "\t");
if(stop==true) return; //come out of run
}
}
}
class TDemo
{
public static void main(String args[]) throws IOException
{
MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();//stop the thread when enter key is pressed
System.in.read();
obj.stop=true;
}
}
Output:
0 1 2…..
100 101 102….
Press <Enter> to stop the thread at any time.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 33 Unit- III

Synchronizing threads

 When a thread is acting on an object preventing other threads from acting on the same
object is called Thread Synchronization or Thread Safe. The object on which the threads are
synchronized is called ‘synchronized object’.
 The Object on which the Threads are synchronized is called synchronized object or
Mutex (Mutually Exclusive Lock).Synchronized object is like a locked object, locked on a
thread. It is like a room with only one door. A person has entered the room and locked form it
from behind. The second person who wants to enter the room should wait till the first person
comes out. In this way, a thread also locks the object after entering it. Then the next thread
cannot enter it till the first thread comes out. This means the object is locked mutually on threads.
So, this object is called ‘mutex’.

Thread synchronization is done in two ways:

 Using synchronized block we can synchronize a block of statements.

e.g.: synchronized (obj)


{
statements;
}
Here, object represents the object to be locked or synchronized. The statements inside the synchronized
block are all available to only one thread at a time. They are not available to more than one thread
simultaneously.

 To synchronize an entire method code we can use synchronized word before method name

e.g.: synchronized void method ()


{
Stmts;
}
Now the statements inside the method are not available to more than one thread at a time. This method
code is synchronized.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 33 Unit- III
Write a program to thread synchronization by using synchronized block.
//Thread synchronization- Two threads acting on same object
//Multiple Threads acting on single object
class Reserve implements Runnable
{ int available = 1;
int wanted;
Reserve (int i)
{ wanted = i;
}
public void run()
{ synchronized (this)
{ System.out.println ("Number of berths available: " + available);
if ( available >= wanted)
{ String name = Thread.currentThread ().getName ();
System.out.println (wanted + " berths alloted to: " + name);
try
{ Thread.sleep (2000); // wait for priniting the ticket
available = available - wanted;
}
catch (InterruptedException ie)
{ ie.printStackTrace (); }
}
else
{ System.out.println ("Sorry, no berths available");
}
}
}
}
class Safe
{ public static void main(String args[])

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 33 Unit- III
{ Reserve obj = new Reserve (1);
Thread t1 =new Thread (obj);
Thread t2 = new Thread (obj);
t1.setName ("First Person");
t2.setName ("Second Person");
t1.start ();
t2.start ();
}
}
Output:

InterThread Communication:

 Thread Communication: In some cases two or more threads should communicate with each
other. One thread output may be send as input to other thread. For example, a consumer thread is
waiting for a Producer to produce the data (or some goods). When the Producer thread completes
production of data, then the Consumer thread should take that data and use it.
 In producer class we take a StringBuffer object to store data, in this case; we take some numbers
from 1 to 5. These numbers are added to StringBuffer object. Until producer completes placing
the data into StringBuffer the consumer has to wait. Producer sends a notification immediately
after the data production is over.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 33 Unit- III
/** Write a Java program that correctly implements producer consumer problem using the concept of
interthread communication.*/

//java program for producer and consumer--inter thread communication


class Producer implements Runnable
{
Thread1 t;
Producer(Thread1 t)
{
this.t=t;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while (true)
{
t.put(i++);
}
}
}
class Consumer implements Runnable
{
Thread1 t;
Consumer(Thread1 t)
{
this.t=t;
new Thread(this,"Consumer").start();
}
public void run()
{
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes- 33 Unit- III
int i=0;
while (true)
{
t.get();
}
}
}
class ProducerConsumer
{
public static void main(String[] args)
{
Thread1 t=new Thread1();
System.out.println("Press Control+c to exit");
new Producer(t);
new Consumer(t);

}
}
Output:
Press Control+C to exit
Put:0
Get:0
Put:1
Get1

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 34 Unit- III

Daemon Threads

Deamon Threads:

Daemon threads are sometimes called "service" threads that normally run at a low priority and provide a
basic service to a program or programs when activity on a machine is reduced. An example of a daemon
thread that is continuously running is the garbage collector thread. This thread, provided by the JVM,
will scan programs for variables that will never be accessed again and free up their resources back to the
system. A thread can set the daemon flag by passing a true boolean value to the setDaemon() method. If
a false boolean value is passed, the thread will become a user thread. However, this must occur before
the thread has been started.

A deamon thread is a thread that executes continuously. Daemon threads are service providers for other
threads or objects. It generally provides a background processing.

 To make a thread t as a deamon thread, we can use setDeamon() method as:

t.setDeamon(true);

 To know if a thread is deamon or not, isDeamon is useful.

boolean x=t.isDaemon().

Write a example program for setting a thread as a daemon thread

public class DaemonDemo extends Thread

public void run()

for(int i=0;i<5;i++)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 34 Unit- III
System.out.println(this.getName()+" :"+i);

public static void main(String args[])

DaemonDemo d1=new DaemonDemo();

DaemonDemo d2=new DaemonDemo();

d1.setName("Daemon thread");

d2.setName("Normal thread");

d1.setDaemon(true);

d1.setPriority(Thread.MIN_PRIORITY);

d1.start();

d2.start();

Output:

Daemon thread:0

Normal thread:0

………….

Daemon thread:4

Normal thread:4

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 35 Unit- IV

Concepts of Applets

 Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and run as part of a Web document.

 After an applet arrives on the client, it has limited access to resources, so that it can produce an
arbitrary multimedia user interface and run complex computations without introducing the risk of
viruses or breaching data integrity.

 Applets – Java program that runs within a Java-enabled browser, invoked through a ―applet‖
reference on a web page, dynamically downloaded to the client computer
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}

 There are two ways to run an applet:

1. Executing the applet within a Java-compatible


Web browser, such as NetscapeNavigator.
2. Using an applet viewer, such as the standard JDK tool, appletviewer.
 An appletviewer executes your applet in a window. This is generally the fastest and easiest way
to test an applet.

 To execute an applet in a Web browser, you need to write a short HTML text file that contains
the appropriate APPLET tag.

<applet code="SimpleApplet" width=200 height=60>


</applet>

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 36 Unit- IV

Life cycle of an applet


 Applets life cycle includes the following methods
1.init( )

2.start( )

3.paint( )

4.stop( )

5.destroy( )

 When an applet begins, the AWT calls the following methods, in this sequence:

init( )
start( )
paint( )
 When an applet is terminated, the following sequence of method calls takes place:

stop( )
destroy( )

 init( ): The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 36 Unit- IV
 start( ): The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called
each time an applet's HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).

 paint( ): The paint( ) method is called each time applet's output must be redrawn. paint( ) is also
called when the applet begins execution. Whatever the cause, whenever the applet must redraw
its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This
parameter will contain the graphics context, which describes the graphics environment in which
the applet is running. This context is used whenever output to the applet is required.
 stop( ): The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called, the
applet is probably running. Applet uses stop( ) to suspend threads that don't need to run when the
applet is not visible. To restart start( ) is called if the user returns to the page.

 destroy( ): The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory. The stop( ) method is always called before
destroy( ).
Types of applets

 Applets are two types

1.Simple applets

2.JApplets

 Simple applets can be created by extending Applet class

 JApplets can be created by extending JApplet class of javax.swing.JApplet package

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV
Creating Applets
The steps involved in developing and testing an applet are:

1. Build an applet code (“.java” file).


2. Create an executable applet (“.class” file).
3. Design a web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APPLET> into the web page.
6. Creating HTML file.
7. Testing the applet.

Building applet code:

 The applet code uses the service of 2 classes.

Applet

Graphics

 Applet class is contained in "java.applet" package


 Graphics class is contained in "java.awt" package
 The Applet class provides life and behavior to the applet through its methods init(), start(), paint()
 The paint() of the applet class when called displays result of the applet code on the screen.
 The paint() takes Graphics object as an argument.

Syntax:

Public void paint (Graphics g)

Ex: The appletDemo Applet.

import java.awt.*;

import java.applet.*;

public class AppletDemo extends Applet

public void paint(Graphics g)

g.drawString("My First Applet Progrm",20,15);

In the drawstring(), 20 and 15 denotes position in pixels.

Chain of classes inherited by Applet class:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV

Designing a Webpage:

<HTML>

<BODY>

<APPLET CODE="AppletDemo.class" WIDTH=300 HEIGHT=400>

</APPLET>

</BODY>

</HTML>

Save the HTML file. In HTML file we have to include <APPLET> and </APPLET> tags in the <BODY> section

The <APPLET> contains or supplies the name of the applet to be loaded and tells the browser how much space
the applet requires.

Ex:

<APPLET CODE=AppletDemo.class WIDTH=300 HEIGHT=400>

</APPLET>

Note: The <APPLET> specifies

Name of the Applet

Width of the Applet (in pixels)

Height of the Applet (in pixels)

Adding Applet to HTML file:

<HTML>

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV
<BODY>

<APPLET CODE="AppletDemo.class" WIDTH=300 HEIGHT=400>

</APPLET>

</BODY>

</HTML>

Running the Applet:

To run the applet we must have the following files in our current directory

1.AppletDemo.java

2.AppletDemo.class

3.AppletTest.html

To run an applet we require one of the following tools

Java enabled Web browser (Ex: NetScape, Google Chrome, etc)

Using 'appletviewer'

appletviewer: appletviewer is not a full-fledged web browser and therefore it ignores all the html tags except the
part pertaining to the running of the applet.

Example

import java.awt.*;

import java.applet.*;

public class AppLifeDemo extends Applet

public void init()

System.out.println("init method called");

public void start()

System.out.println("start method called");

public void stop()

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV
System.out.println("stop method called");

public void destroy()

System.out.println("destroy method called");

public void paint(Graphics g)

g.drawString("LIFE CYCLE DEMO",10,20);

<HTML>

<BODY>

<APPLET CODE="AppLifeDemo.class" WIDTH=300 HEIGHT=350>

</APPLET>

</BODY>

</HTML>

Passing Parameters to Applets


 APPLET tag in HTML allows you to pass parameters to applet.

 To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified
parameter in the form of a String object.
 Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the
opening and closing APPLET tags. Inside the applet, you read the values passed through
the PARAM tags with the getParameter() method of the java.applet.Applet class.
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV
<param name=accountEnabled value=true>
</applet>
*/

public class ParamDemo extends Applet{


String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");

try {
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 37 Unit- IV
active = Boolean.valueOf(param).booleanValue();
}
// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -38 Unit-IV

AWT classes

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavyweight i.e. its components uses the resources of system.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.

Fig 1: The hierarchy of Java AWT classes

Method Description
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -38 Unit-IV

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -39 Unit-IV

Event(S)& Delegation Event Model


 For the user to interact with a GUI, the underlying operating system must support event handling.
1) operating systems constantly monitor events such as keystrokes, mouse clicks, voice command, etc.
2) operating systems sort out these events and report them to the appropriate application programs
3) each application program then decides what to do in response to these events
Events
 An event is an object that describes a state change in a source.
 It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
 Some of the activities that cause events to be generated are pressing a button, entering a character via
the keyboard, selecting an item in a list, and clicking the mouse.
 Events may also occur that are not directly caused by interactions with a user interface.
 For example, an event may be generated when a timer expires, a counter exceeds a value, a software or
hardware failure occurs, or an operation is completed.
 Events can be defined as needed and appropriate by application.

Listener
 A listener is an object that is notified when an event occurs.
 Event has two major requirements.
1.It must have been registered with one or more sources to receive notifications about specific types of
events.
2. It must implement methods to receive and process these notifications.
 The methods that receive and process events are defined in a set of interfaces found in java.awt.event.
 For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.
 Any object may receive and process one or both of these events if it provides an implementation of this
interface.
Delegation event model
 The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events.
 Its concept is quite simple: a source generates an event and sends it to one or more listeners.
 In this scheme, the listener simply waits until it receives an event.
 Once received, the listener processes the event and then returns.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -39 Unit-IV
 The advantage of this design is that the application logic that processes events is cleanly separated from
the user interface logic that generates those events.
 A user interface element is able to "delegate“ the processing of an event to a separate piece of code.
 In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want to
receive them.
 This is a more efficient way to handle events than the design used by the old Java 1.0 approach.
Previously, an event was propagated up the containment hierarchy until it was handled by a component.
 This required components to receive events that they did not process, and it wasted valuable time.The
delegation event model eliminates this overhead.
Note
 Java also allows you to process events without using the delegation event model.
 This can be done by extending an AWT component.
 Delegation event model is a specialized kind of Observer
 description: "An event is propagated from a 'Source' object to a 'Listener' object by invoking a method
on the listener and passing in the instance of the event subclass which defines the event type
generated." (from Sun's Java AWT: Delegation Event Model) called "delegation" event model because
the event source "delegates" the processing of an event to a separate object (the event listener)
 participants (based on Java's implementation):
event source
-registers/unregisters event listener objects
-broadcasts events to listeners (by invoking methods on them)
-pushes an "event object" to listeners (by passing it to the event methods)
-corresponding Observer pattern participant: Observable
event object
-describes the event
-provides methods to access information about the event (e.g., MouseEvent.getX())
-passed to listener by event source
-corresponding Observer pattern participant: Observer.update() method's infoObj
parameter
event listener interface
-defines agreed upon event methods (the event source invokes these on the listener object)
-is implemented by event listener
-corresponding Observer pattern participant: Observer.update() method

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -39 Unit-IV
event listener object
-registers with event source to receive events
-reacts to events broadcast by event source
-implements methods in event listener interface
-corresponding Observer pattern participant: Observer

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -40 Unit-IV

Handling mouse events


 Mouse events can be handled by implementing the MouseListener and the MouseMotionListener
interfaces.
 MouseListener Interface defines five methods. The general forms of these methods are:
1.void mouseClicked(MouseEvent me)

2.void mouseEntered(MouseEvent me)

3.void mouseExited(MouseEvent me)

4.void mousePressed(MouseEvent me)

5.void mouseReleased(MouseEvent me)


 MouseMotionListener Interface. This interface defines two methods. Their general forms are :
1.void mouseDragged(MouseEvent me)

2.void mouseMoved(MouseEvent me)


 Keyboard events, can be handled by implementing the KeyListener interface.
 KeyListner interface defines three methods. The general forms of these methods are :
1.void keyPressed(KeyEvent ke)

2.void keyReleased(KeyEvent ke)

3.void keyTyped(KeyEvent ke)


•To implement keyboard events implementation to the above methods is needed.
Sample Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -40 Unit-IV

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -40 Unit-IV
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
Output:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -40 Unit-IV

Keyboard and Focus Events


Events don't start out as Java objects. Ultimately, events are caused by user actions that are detected by
the computer's operating system. When the user moves the mouse or presses a key, the system has to decide
what to do with the information about the user's action. For a mouse action, the information usually goes to the
visual GUI interface element that contains the mouse cursor. If that interface element happens to be a Java
component, then the information is converted into a Java MouseEvent object, which is in turn sent through
Java's event-handling process. But what about keyboard events? When the user presses a key, where does that
information go?

GUIs use the idea of input focus to determine where information about keyboard events should be sent. At a
given time, exactly one interface element on the screen has the input focus, and that is where all keyboard
events are sent. If the interface element happens to be a Java component, then the information about the
keyboard event becomes a Java object of type KeyEvent.

It's a good idea to give the user some visual feedback about which component has the input focus. For
example, if the component is the typing area of a word-processor, the feedback is usually in the form of a
blinking text cursor. Another common visual clue is to draw a brightly colored border around the edge of a
component when it has the input focus, as I do in the sample applet later on this page.

A component that wants to have the input focus can call the method requestFocus(), which is defined in the
Component class. Calling this method does not absolutely guarantee that the component will actually get the
input focus. Several components might request the focus; only one will get it. This method should only be used
in certain circumstances in any case, since it can be a rude surprise to the user to have the focus suddenly
pulled away from a component that the user is working with. In general, the user can choose to give the focus
to a component by clicking on that component with the mouse. And pressing the tab key will often move the
focus from one component to another.

Some components do not automatically receive the input focus when the user clicks on them. To solve this
problem, a program has to register a mouse listener with the component to detect user clicks. In response to
user clicks, the mousePressed() method should call requestFocus() for the component. Unfortunately, which
types of components require such treatment varies from platform to platform. In Sun Microsystem's
implementation of Java, for example, applet objects and canvas objects must be treated in this way. So if you
create a subclass of Applet or Canvas that is supposed to be able to respond to keyboard events, you should be
sure to set up a mouse listener for your class and call requestFocus() in the mousePressed() method. This is
done in the sample applet example given below.

If a component is to change its appearance when it has the input focus, it needs some way to know when it has
the focus. In Java, objects are notified about changes of input focus by events of type FocusEvent. An object
that wants to be notified of changes in focus can implement the FocusListener interface. This interface declares
two methods:

public void focusGained(FocusEvent evt);


public void focusLost(FocusEvent evt);
Furthermore, the addFocusListener() method must be used to set up a listener for the focus events. When a
component gets the input focus, it calls the focusGained() method of any object that had been registered with

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -40 Unit-IV
that component as a FocusListener. When it loses the focus, it calls the listener's focusLost() method. Often, it
is the component itself that listens for focus events.

public void focusGained(FocusEvent evt) {


// the applet now has the input focus
focussed = true;
repaint(); // redraw with cyan border
}

public void focusLost(FocusEvent evt) {


// the applet has now lost the input focus
focussed = false;
repaint(); // redraw without cyan border
}

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -42 Unit-IV
Adapter & Inner Classes
Adapter classes
 Java provides a special feature, called an adapter class that can simplify the creation
of event handlers.
 An adapter class provides an empty implementation of all methods in an event
listener interface.
 Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
 You can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which you are interested.
 adapter classes in java.awt.event are.

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/** Demonstrate the use of an MouseAdapter. **/
public class AdapterApplet extends JApplet
{
public void init () {
Container content_pane = getContentPane ();

// Create an instance of JPanel


JPanel panel = new JPanel ();

// Add a anonymous MouseAdapter object


// to the panel
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -42 Unit-IV
panel.addMouseListener
(
new MouseAdapter ()
{
public void mouseEntered (MouseEvent e) {
System.out.println (e.toString ());
}
}
);

// And a panel to the JApplet panel.


content_pane.add (panel);

} // ctor

} //class AdapterApplet

Inner classes
 Inner classes, which allow one class to be defined within another.
 An inner class is a non-static nested class. It has access to all of the variables and
methods of its outer class and may refer to them directly in the same way that other
non-static members of the outer class do.
 An inner class is fully within the scope of its enclosing class.
 an inner class has access to all of the members of its enclosing class, but the reverse
is not true.

 Members of the inner class are known only within the scope of the inner class and
may not be used by the outer class

 An anonymous inner class is really a inner class with no name. They can be used
when you only want to make one instance of the class. The use of an anonymous
inner class can be a compact way of implementing an event listener:

JButton equalsButton = new JButton("=");


equalsButton.setActionCommand("=");
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -42 Unit-IV
equalsButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
//the code here is executed when the button is clicked.
}
});

 In the above code a JButton is created and instead of assigning a class which
implements theActionListener interface using theaddActionListener method we
instead write the class itself.

 The class has no need of a name as it only gets called in the one place. The code for
the button click is placed in the actionPerformedmethod which has the advantage of
making it more maintainable because of it's right next to where the button is declared.

 Although the syntax might look a llittle more complicated it really is the same as
implementing the ActionListener interface in another class. It just has the advantage of
being more compact.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes -43 Unit-IV

JAVA AWT CLASS HIERARCHY & Swing

The AWT class hierarchy

 The AWT classes are contained in the java.awt package. It is one of Java's largest
packages. some of the AWT classes.
 AWT Classes
1.AWTEvent:Encapsulates AWT events.
2.AWTEventMulticaster: Dispatches events to multiple listeners.
3.BorderLayout: The border layout manager. Border layouts use five components:
North, South, East, West, and Center.
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -43 Unit-IV
4.Button: Creates a push button control.
5.Canvas: A blank, semantics-free window.
6.CardLayout: The card layout manager. Card layouts emulate index cards. Only the
one on top is showing
7.Checkbox: Creates a check box control.
8.CheckboxGroup: Creates a group of check box controls.
9.CheckboxMenuItem: Creates an on/off menu item.
10.Choice: Creates a pop-up list.
11.Color: Manages colors in a portable, platform-independent fashion.
12.Component: An abstract super class for various AWT components.
13.Container: A subclass of Component that can hold other components.
14.Cursor: Encapsulates a bitmapped cursor.
15.Dialog: Creates a dialog window.
16.Dimension: Specifies the dimensions of an object. The width is stored in width,
and the height is stored in height.
17.Event: Encapsulates events.
18.EventQueue: Queues events.
19.FileDialog: Creates a window from which a file can be selected.
20.FlowLayout: The flow layout manager. Flow layout positions components left to
right, top to bottom.
21.Font: Encapsulates a type font.
22.FontMetrics: Encapsulates various information related to a font. This information
helps you display text in a window.
23.Frame: Creates a standard window that has a title bar, resize corners, and a menubar.
24.Graphics: Encapsulates the graphics context. This context is used by various output
methods to display output in a window.
25.GraphicsDevice: Describes a graphics device such as a screen or printer.
26.GraphicsEnvironment: Describes the collection of available Font and
GraphicsDevice objects.
27.GridBagConstraints: Defines various constraints relating to the GridBagLayout class.
28.GridBagLayout: The grid bag layout manager. Grid bag layout displays components
subject to the constraints specified by GridBagConstraints.
29.GridLayout: The grid layout manager. Grid layout displays components i n a two
dimensional grid.
30.Scrollbar: Creates a scroll bar control.
31.ScrollPane: A container that provides horizontal and/or vertical scrollbars for another
component.
32.SystemColor: Contains the colors of GUI widgets such as windows, scrollbars, text, and
33.TextArea: Creates a multiline edit control.
34.TextComponent: A super class for TextArea and TextField.
35.TextField: Creates a single-line edit control.
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -43 Unit-IV
36.Toolkit: Abstract class implemented by the AWT.
37.Window: Creates a window with no frame, no menu bar, and no title.
Introduction to swings
 Swing is a set of classes that provides more powerful and flexible components than are
possible with the AWT.

 In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.

 Even familiar components such as buttons have more capabilities in Swing.

 For example, a button may have both an image and a text string associated with it. Also, the
image can be changed as the state of the button changes.

 Unlike AWT components, Swing components are not implemented by platform-specific


code.

 Instead, they are written entirely in Java and, therefore, are platform-independent.

 The term lightweight is used to describe such elements.

 The Swing component are defined in javax.swing


1.AbstractButton: Abstract superclass for Swing buttons.

2.ButtonGroup: Encapsulates a mutually exclusive set of buttons.

3.ImageIcon: Encapsulates an icon.

4.JApplet: The Swing version of Applet.

5.JButton: The Swing push button class.

6.JCheckBox: The Swing check box class.

7.JComboBox : Encapsulates a combo box (an combination of a drop-down list and text
field).

8.JLabel: The Swing version of a label.

9.JRadioButton: The Swing version of a radio button.

10.JScrollPane: Encapsulates a scrollable window.

11.JTabbedPane: Encapsulates a tabbed window.

12.JTable: Encapsulates a table-based control.

13.JTextField: The Swing version of a text field.


P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -43 Unit-IV
14.JTree: Encapsulates a tree-based control.

Limitations of AWT
 AWT supports limited number of GUI components.

 AWT components are heavy weight components.

 AWT components are developed by using platform specific code.

 AWT components behaves differently in different operating systems.

 AWT component is converted by the native code of the operating system.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV

User Interface Components


Labels: Creates a label that displays a string.
•A label is an object of type Label, and it contains a string, which it displays.

•Labels are passive controls that do not support any interaction with the user.

•Label defines the following constructors:


1.Label( )

2.Label(String str)

3.Label(String str, int how)


•The first version creates a blank label.

•The second version creates a label that contains the string specified by str. This string is
left-justified.

•The third version creates a label that contains the string specified by str using the alignment
specified by how. The value of how must be one of these three constants: Label.LEFT,
Label.RIGHT, or Label.CENTER. L 5.2
•Set or change the text in a label is done by using the setText( ) method.
•Obtain the current label by calling getText( ).
•These methods are shown here:
void setText(String str)
String getText( )
•For setText( ), str specifies the new label. For getText( ), the current label is returned.
•To set the alignment of the string within the label by calling setAlignment( ).
•To obtain the current alignment, call getAlignment( ).
•The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Label creation: Label one = new Label("One");
Button:
•The most widely used control is the push button.
•A push button is a component that contains a label and that generates an event when it is
pressed.
•Push buttons are objects of type Button. Button defines these two constructors:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
Button( )
Button(String str)
•The first version creates an empty button. The second creates a button that contains str as a
label.
•After a button has been created, you can set its label by calling setLabel( ).
•You can retrieve its label by calling getLabel( ).
•These methods are as follows:

void setLabel(String str)


String getLabel( )
Here, str becomes the new label for the button.
Button creation: Button yes = new Button("Yes");

Canvas :
•It is not part of the hierarchy for applet or frame windows

•Canvas encapsulates a blank window upon which you can draw.

•Canvas creation:
Canvas c = new Canvas();
Image test = c.createImage(200, 100);
•This creates an instance of Canvas and then calls the
createImage( ) method to actually make an Image object.
At this point, the image is blank.

Scrollbars :
•Scrollbar generates adjustment events when the scroll bar is manipulated.

•Scrollbar creates a scroll bar control.

•Scroll bars are used to select continuous values between a specified minimum and
maximum.

•Scroll bars may be oriented horizontally or vertically.

•A scroll bar is actually a composite of several individual parts.

•Each end has an arrow that you can click to move the current value of the scroll bar one
unit in the direction of the arrow.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
•The current value of the scroll bar relative to its minimum and maximum values is
indicated by the slider box (or thumb) for the scroll bar.

•The slider box can be dragged by the user to a new position. The scroll bar will then reflect
this value.
•Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
•The first form creates a vertical scroll bar.

•The second and third forms allow you to specify the orientation of the scroll bar. If style is
Scrollbar.VERTICAL, a vertical scroll bar is created. If style is
Scrollbar.HORIZONTAL, the scroll bar is horizontal.

•In the third form of the constructor, the initial value of the scroll bar is passed in
initialValue.

•The number of units represented by the height of the thumb is passed in thumbSize.

•The minimum and maximum values for the scroll bar are specified by min and max.

•vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);

•horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width);

Text :
•Text is created by Using a TextField class

•The TextField class implements a single-line text-entry area, usually called an edit

•control.

•Text fields allow the user to enter strings and to edit the text using the arrow

•keys, cut and paste keys, and mouse selections.

•TextField is a subclass of TextComponent. TextField defines the following constructors:


TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars) L 5.8
•The first version creates a default text field.

•The second form creates a text field that is numChars characters wide.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
•The third form initializes the text field with the string contained in str.

•The fourth form initializes a text field and sets its width.

•TextField (and its superclass TextComponent) provides several methods that allow you to
utilize a text field.

•To obtain the string currently contained in the text field, call getText().

•To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.

Components :
•At the top of the AWT hierarchy is the Component class.

•Component is an abstract class that encapsulates all of the attributes of a visual


component.

•All user interface elements that are displayed on the screen and that interact with the user
are subclasses of Component.

•It defines public methods that are responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window, and repainting.

•A Component object is responsible for remembering the current foreground and


background colors and the currently selected text font.
•To add components

Component add(Component compObj)


Here, compObj is an instance of the control that you want to add. A reference to compObj is
returned.
Once a control has been added, it will automatically be visible whenever its parent window
is displayed.
•To remove a control from a window when the control is no longer needed call remove( ).

•This method is also defined by Container. It has this general form:

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll()

Check Box:
•A check box is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not.

•There is a label associated with each check box that describes what option the box
represents.

•You can change the state of a check box by clicking on it.

•Check boxes can be used individually or as part of a group.

•Checkboxes are objects of the Checkbox class.


•Checkbox supports these constructors:
1.Checkbox( )

2.Checkbox(String str)

3.Checkbox(String str, boolean on)

4.Checkbox(String str, boolean on, CheckboxGroup cbGroup)

5.Checkbox(String str, CheckboxGroup cbGroup, boolean on)


•The first form creates a check box whose label is initially blank. The state of the check box
is unchecked.

•The second form creates a check box whose label is specified by str. The state of the check
box is unchecked.

•The third form allows you to set the initial state of the check box. If on is true, the check
box is initially checked; otherwise, it is cleared.

•The fourth and fifth forms create a check box whose label is specified by str and whose
group is specified by cbGroup. If this check box is not part of a group, then cbGroup must
be null. (Check box groups are described in the next section.) The value of on determines
the initial state of the check box.
•To retrieve the current state of a check box, call getState( ).

•To set its state, call setState( ).

•To obtain the current label associated with a check box by calling getLabel( ).

•To set the label, call setLabel( ).


P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes- 44 Unit- IV
•These methods are as follows:

boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared.
Checkbox creation:
CheckBox Win98 = new Checkbox("Windows 98", null, true);

Check Box groups


•It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time.
•These check boxes are oftenccalled radio buttons.
•To create a set of mutually exclusive check boxes, you must first define the group to which
they will belong and then specify that group when you construct the check boxes.
•Check box groups are objects of type CheckboxGroup. Only the default constructor is
defined, which creates an empty group.
•To determine which check box in a group is currently selected by calling
getSelectedCheckbox( ).
•To set a check box by calling setSelectedCheckbox( ).
•These methods are as follows:

Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Here, which is the check box that you want to be selected. The previously selected checkbox
will be turned off.
–CheckboxGroup cbg = new CheckboxGroup();

–Win98 = new Checkbox("Windows 98", cbg, true);

–winNT = new Checkbox("Windows NT", cbg, false);

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV

Choices
•The Choice class is used to create a pop-up list of items from which the user may choose.

•A Choice control is a form of menu.

•Choice only defines the default constructor, which creates an empty list.

•To add a selection to the list, call addItem( ) or add( ).


void addItem(String name)
void add(String name)
•Here, name is the name of the item being added.

•Items are added to the list in the order to determine which item is currently selected, you
may call either getSelectedItem( ) or getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )

Lists
•The List class provides a compact, multiple-choice, scrolling selection list.

•List object can be constructed to show any number of choices in the visible window.

•It can also be created to allow multiple selections. List provides these constructors:

List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
•To add a selection to the list, call add( ). It has the following two forms:

void add(String name)


void add(String name, int index)
•Ex: List os = new List(4, true);

Panels
•The Panel class is a concrete subclass of Container.

•It doesn't add any new methods; it simply implements Container.

•A Panel may be thought of as a recursively nestable, concrete screen component. Panel is


the superclass for Applet.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
•When screen output is directed to an applet, it is drawn on the surface of a Panel object.

•Panel is a window that does not contain a title bar, menu bar, or border.

•Components can be added to a Panel object by its add( ) method (inherited from
Container). Once these components have been added, you can position and resize them
manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by
Component.

•Ex: Panel osCards = new Panel();

CardLayout cardLO = new CardLayout();


osCards.setLayout(cardLO); L 7.3 scrollpane
•A scroll pane is a component that presents a rectangular area in which a component may be
viewed.

•Horizontal and/or vertical scroll bars may be provided if necessary.

•constants are defined by the ScrollPaneConstants interface.


1.HORIZONTAL_SCROLLBAR_ALWAYS

2.HORIZONTAL_SCROLLBAR_AS_NEEDED

3.VERTICAL_SCROLLBAR_ALWAYS

4.VERTICAL_SCROLLBAR_AS_NEEDED

Dialogs
•Dialog class creates a dialog window.

•constructors are : Dialog(Frame parentWindow, boolean mode) Dialog(Frame


parentWindow, String title, boolean mode)

•The dialog box allows you to choose a method that should be invoked when the button is
clicked.

•Ex: Font f = new Font("Dialog", Font.PLAIN, 12);

MenuBar
•MenuBar class creates a menu bar.

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
•A top-level window can have a menu bar associated with it. A menu bar displays a list of
top-level menu choices. Each choice is associated with a drop-down menu.

•To create a menu bar, first create an instance of MenuBar.

•This class only defines the default constructor. Next, create instances of Menu that will
define the selections displayed on the bar.

•Following are the constructors for Menu:


Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable) L 8.2
•Once you have created a menu item, you must add the item to a Menu object by using
MenuItem add(MenuItem item)
•Here, item is the item being added. Items are added to a menu in the order in which the
calls to add( ) take place.

•Once you have added all items to a Menu object, you can add that object to the menu bar
by using this version of add( ) defined by MenuBar:

•Menu add(Menu menu)


Graphics
•The AWT supports a rich assortment of graphics methods.

•All graphics are drawn relative to a window.

•A graphics context is encapsulated by the Graphics class

•It is passed to an applet when one of its various methods, such as paint( ) or update( ), is
called.

•It is returned by the getGraphics( ) method of Component.

•The Graphics class defines a number of drawing functions. Each shape can be drawn edge-
only or filled.

•Objects are drawn and filled in the currently selected graphics color, which is black by
default.

•When a graphics object is drawn that exceeds the dimensions of the window, output is
automatically clipped

•Ex:

Public void paint(Graphics g)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 44 Unit- IV
{
G.drawString(“welcome”,20,20); }

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 45 Unit- IV

Layout Managers
 A layout manager automatically arranges your controls within a window by using
some type of algorithm.

 It is very tedious to manually lay out a large number of components and sometimes
the width and height information is not yet available when you need to arrange some
control, because the native toolkit components haven't been realized.

 Each Container object has a layout manager associated with it.

 A layout manager is an instance of any class that implements the LayoutManager


interface.

 The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is


made, then the default layout manager is used.

 Whenever a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.

Layout manager types :


Layout manager class defines the following types of layout managers
 Boarder Layout

 Grid Layout

 Flow Layout

 Card Layout

 Grid Bag Layout

Boarder layout
 The BorderLayout class implements a common layout style for top-level windows.
It has four narrow, fixed-width components at the edges and one large area in the
center.

 The four sides are referred to as north, south, east, and west. The middle area is
called the center.

 The constructors defined by BorderLayout:


BorderLayout( )

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 45 Unit- IV
BorderLayout(int horz, int vert)
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
B orderLayout.SOUTH
BorderLayout.EAST
B orderLayout.WEST
BorderLayout.NORTH
•Components can be added by
void add(Component compObj, Object region);

Grid layout
 GridLayout lays out components in a two-dimensional grid. When you instantiate a

 GridLayout, you define the number of rows and columns. The constructors are
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
 The first form creates a single-column grid layout.

 The second form creates a grid layout with the specified number of rows &columns.

 The third form allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.

 Either numRows or numColumns can be zero. Specifying numRows as zero allows


for unlimited-length columns. Specifying numColumns as zero allows for unlimited-
lengthrows.
Flow layout
 FlowLayout is the default layout manager.

 Components are laid out from the upper-left corner, left to right and top to bottom.
When no more components fit on a line, the next one appears on the next line. A
small space is left between each component, above and below, as well as left and
right.
 The constructors are
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

P.Muralidhar CSE GMRIT


OOPS Through JAVA Lecture Notes- 45 Unit- IV
 The first form creates the default layout, which centers components and leaves five
pixels of space between each component.
 The second form allows to specify how each line is aligned. Valid values for are:

FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
 These values specify left, center, and right alignment, respectively.
 The third form allows to specify the horizontal and vertical space left between
components in horz and vert, respectively
Card layout
 The CardLayout class is unique among the other layout managers in that it stores
several different layouts.
 Each layout can be thought of as being on a separate index card in a deck that can be
shuffled so that any card is on top at a given time.
 CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
 The cards are held in an object of type Panel. This panel must have CardLayout
selected as its layout manager.
 Cards are added to panel using

void add(Component panelObj, Object name);


•methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
GridBag Layout
•The Grid bag layout displays components subject to the constraints specified by
GridBagConstraints.

•GridLayout lays out components in a two-dimensional grid.

•The constructors are


P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes- 45 Unit- IV
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)

P.Muralidhar CSE GMRIT


OOPS THROUGH JAVA
II B.Tech IT
Tutorial Sheet-1
----------------------------------------------------------------------------------------------------------------
1. Write declarations, statements or comments that accomplish each of the following tasks:
a) State that a program will calculate the product of three integers.
b) Create a Scanner called input that reads values from the standard input.
c) Declare the variables x, y, z and result to be of type int.
d) Prompt the user to enter the first integer.
e) Read the first integer from the user and store it in the variable x.
f) Prompt the user to enter the second integer.
g) Read the second integer from the user and store it in the variable y.
h) Prompt the user to enter the third integer.
i) Read the third integer from the user and store it in the variable z.
j) Compute the product of the three integers contained in variables x, y and z, and assign
the result to the variable result.
k) Display the message "Product is" followed by the value of the variable result.
l) Terminate the program and indicate successful termination.
2.
Using the statements you wrote in Exercise 1 a, write a complete program that calculates
and prints the product of three integers.
Answers to Tutorial Sheet-1

1
a) // Calculate the product of three integers
b) int x, y, z, result;
or
int x;
int y;
int z;
int result;
c) String xVal, yVal, zVal;
or
String xVal;
String yVal;
String zVal;
d) xVal = JOptionPane.showInputDialog( "Enter first integer:" );
e) yVal = JOptionPane.showInputDialog( "Enter second integer:" );
f) zVal = JOptionPane.showInputDialog( "Enter third integer:" );
g) x = Integer.parseInt( xVal );
h) y = Integer.parseInt( yVal );
i) z = Integer.parseInt( zVal );
j) result = x * y * z;
k) JOptionPane.showMessageDialog( null, "The product is " + result );
l) System.exit( 0 );

2. Program

import javax.swing.JOptionPane;
public class Product {

public static void main( String args[] )


{
int x; // first number
int y; // second number
int z; // third number
int result; // product of numbers

String xVal; // first string input by user


String yVal; // second string input by user
String zVal; // third string input by user

xVal = JOptionPane.showInputDialog( "Enter first integer:" );


yVal = JOptionPane.showInputDialog( "Enter second integer:" );
zVal = JOptionPane.showInputDialog( "Enter third integer:" );

x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
result = x * y * z;

JOptionPane.showMessageDialog( null, "The product is " + result );

System.exit( 0 );

} // end method main

} // end class Product


OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-2
1. Find and correct the error in each of the following program segments:
a) final int ARRAY_SIZE = 5;
ARRAY_SIZE = 10;
b) Assume int[] b = new int[ 10 ];
for ( int i = 0; i <= b.length; i++ )
b[ i ] = 1;
c) Assume int[][] a = { { 1, 2 }, { 3, 4 } };
a[ 1, 1 ] = 5;

2. Perform the following tasks for an array called fractions:


a) Declare a constant ARRAY_SIZE that’s initialized to 10.
b) Declare an arraywith ARRAY_SIZE elements of type double, and initialize the elements to 0.
c) Name the fourth element of the array.
d) Refer to array element 4.
e) Assign the value 1.667 to array element 9.
f) Assign the value 3.333 to array element 6.
g) Sum all the elements of the array, using a for statement. Declare the integer variable x as a
control variable for the loop.

3. Create a class Rectangle with attributes length and width, each of which defaults to 1.
Provide methods that calculate the rectangle’s perimeter and area. It has set and get methods for
both length and width. The set methods should verify that length and width are each floating-
point numbers larger than 0.0 and less than 20.0.Write a program to test class Rectangle.
Answers to Tutorial Sheet-2

1.

a) final int ARRAY_SIZE = 5;


ARRAY_SIZE = 10;
ANS: Error: Assigning a value to a constant after it has been initialized.
Correction: Assign the correct value to the constant in a final int ARRAY_SIZE declaration
or create another variable.
b) Assume int b[] = new int[ 10 ];
for ( int i = 0; i <= b.length; i++ )
b[ i ] = 1;
ANS: Error: Referencing an array element outside the bounds of the array (b[10]).
Correction: Change the <= operator to <.
c) Assume int a[][] = { { 1, 2 }, { 3, 4 } };
a[ 1, 1 ] = 5;
ANS: Error: Array indexing is performed incorrectly.
Correction: Change the statement to a[ 1 ][ 1 ] = 5;

2.

a) Declare a constant ARRAY_SIZE that is initialized to 10.


ANS: final int ARRAY_SIZE = 10;
b) Declare an array with ARRAY_SIZE elements of type float, and initialize the elements
to 0.
ANS: float fractions[] = new float[ ARRAY_SIZE ];
c) Name the fourth element of the array.
ANS: fractions[ 3 ]
d) Refer to array element four.
ANS: fractions[ 4 ]
e) Assign the value 1.667 to array element nine.
ANS: fractions[ 9 ] = 1.667;
f) Assign the value 3.333 to the seventh element of the array.
ANS: fractions[ 6 ] = 3.333;

g) Sum all the elements of the array, using a for statement. Declare the integer variable x
as a control variable for the loop.
ANS: float total = 0.0;
for ( int x = 0; x < fractions.length; x+
+ ) total += fractions[ x ];

3.
public class Rectangle
{ private double length,
width;
/ constructor without paramters
public Rectangle()
{
setLength( 1.0 );
setWidth( 1.0 );
}
/ constructor with length and width supplied
public Rectangle( double theLength, double theWidth )
{
setLength( theLength );
setWidth( theWidth );
}

// validate and set length


public void setLength( double theLength )
{
length = ( theLength > 0.0 && theLength < 20.0 ? theLength : 1.0 );
}

// validate and set width


public void setWidth( double theWidth )
{
width = ( theWidth > 0 && theWidth < 20.0 ? theWidth : 1.0 );
}

/ get value of length


public double getLength()
{
return length;
}

/ get value of width


public double getWidth()
{
return width;
}

/ calculate rectangle's perimeter


public double perimeter()
{
return 2 * length + 2 * width;
}

/ calculate rectangle's area


public double area()
{
return length * width;
}

/ convert to String
public String toRectangleString ()
{
return ( " Length: " + length + "\n" + " Width: " + width + "\n" +
" Perimeter: " + perimeter() + "\n" + " Area: " + area() );

}
} // end class Rectangle
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial -4
---------------------------------------------------------------------------------------------------------------
1.Write down all the shapes you can think of—both two-dimensional and three-dimensional
and form those shapes into a shape hierarchy. Your hierarchy should have class Shape at the
top. Class TwoDimensionalShape and class ThreeDimensionalShape should extend Shape.
Once you have developed the hierarchy, declare each of the classes in it.

2. Create the classes in the inheritance hierarchy of Fig below. An Employee should have a
first name, last name and social-security number. In addition, a SalariedEmployee should
have a weekly salary; an HourlyEmployee should have a wage and a number of hours
worked; a Commission-Employee should have a commission rate and gross sales; and a
BasePlusCommissionEmployee should have a base salary. Each class should have
appropriate constructors, set methods and get methods.
Write a program that instantiates objects of each of these classes and outputs all the
information associated with each object (including the inherited information).
Answers to Tutorial Sheet-4

1.

2.
4public class Employee { 5
private String firstName; 6
private String lastName;
7 private String socialSecurityNumber;
// constructor
10 public Employee( String first, String last, String ssn )
11 {
12 firstName = first;
13 lastName = last;
14 socialSecurityNumber = ssn;
15 }
16
17 // set first name
18 public void setFirstName( String first )
19 {
20 firstName = first;
21 }
22
23 // return first name
24 public String getFirstName()
25 {
26 return firstName;
27 }
28
29 // set last name
30 public void setLastName( String last )
31 {
32 lastName = last;
33 }
34
35 // return last name
36 public String getLastName()
37 {
38 return lastName;
39 }
// set social security number
42 public void setSocialSecurityNumber( String number )
43 {
44 socialSecurityNumber = number; // should validate
45 }
46
47 // return social security number
48 public String getSocialSecurityNumber()
49 {
50 return socialSecurityNumber;
51 }
52
53 // return String representation of Employee object
54 public String toString()
55 {
56 return getFirstName() + " " + getLastName() +
57 "\nsocial security number: " + getSocialSecurityNumber();
58 }
59
60 } // end class Employee

/ SalariedEmployee class derived from Employee.


34
public class SalariedEmployee extends Employee
{ 5 private double weeklySalary;
67
/ constructor
8 public SalariedEmployee( String first, String last,
9 String socialSecurityNumber, double salary )
10 {
11 super( first, last, socialSecurityNumber );
12 setWeeklySalary( salary );
13 }
14
15 // set salaried employee's salary
16 public void setWeeklySalary( double salary )
17 {
18 weeklySalary = salary < 0.0 ? 0.0 : salary;
19 }
20
21 // return salaried employee's salary
22 public double getWeeklySalary()
23 {
24 return weeklySalary;
25 }
26
27 // return String representation of SalariedEmployee object
28 public String toString()
29 {
30 return "\nSalaried employee: " + super.toString() +
31 "\nWeekly salary: " + getWeeklySalary();
32 }
33
34 } // end class SalariedEmployee

/ HourlyEmployee class derived from


Employee. 34
public class HourlyEmployee extends Employee {
5 private double wage; // wage per hour
6 private double hours; // hours worked for week
78
/ constructor
9 public HourlyEmployee( String first, String last,
10 String socialSecurityNumber, double hourlyWage, double hoursWorked )
11 {
12 super( first, last, socialSecurityNumber );
13 setWage( hourlyWage );
14 setHours( hoursWorked );
15 }
16
17 // set hourly employee's wage
18 public void setWage( double wageAmount )
19 {
20 wage = wageAmount < 0.0 ? 0.0 : wageAmount;
21 }
22
23 // return wage
24 public double getWage()
25 {
26 return wage;
27 }
28
29 // set hourly employee's hours worked
30 public void setHours( double hoursWorked )
31 {
32 hours = ( hoursWorked >= 0.0 && hoursWorked <= 168.0 ) ?
33 hoursWorked : 0.0;
34 }
35
36 // return hours worked
37 public double getHours()
38 {
39 return hours;
40 }
41
42 // return String representation of HourlyEmployee object
43 public String toString()
44 {
45 return "\nHourly employee: " + super.toString() + "\nHours: " +
46 getHours() + "\nWage: " + getWage();
47 }
48
49 } // end class HourlyEmployee

/ CommissionEmployee class derived from Employee.


34
public class CommissionEmployee extends Employee {
5 private double grossSales; // gross weekly sales
6 private double commissionRate; // commission percentage
78
/ constructor
9 public CommissionEmployee( String first, String last,
10 String socialSecurityNumber,
11 double grossWeeklySales, double percent )
12 {
13 super( first, last, socialSecurityNumber );
14 setGrossSales( grossWeeklySales );
15 setCommissionRate( percent );
16 }
17
18 // set commission employee's rate
19 public void setCommissionRate( double rate )
20 {
21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
22 }
23
24 // return commission employee's rate
25 public double getCommissionRate()
26 {
27 return commissionRate;
28 }
29
30 // set commission employee's weekly base salary
31 public void setGrossSales( double sales )
32 {
33 grossSales = sales < 0.0 ? 0.0 : sales;
34 }
35
36 // return commission employee's gross sales amount
37 public double getGrossSales()
38 {
39 return grossSales;
40 }
41
42 // return String representation of CommissionEmployee object
43 public String toString()
44 {
45 return "\nCommission employee: " + super.toString() +
46 "\nCommission rate: " + getCommissionRate() +
47 "\nGross sales: " + getGrossSales();
48 }
49
50 } // end class CommissionEmployee

2 // BasePlusCommissionEmployee class derived from CommissionEmployee.


34
public class BasePlusCommissionEmployee extends CommissionEmployee
{ 5 private double baseSalary; // base salary per week
67
// constructor
8 public BasePlusCommissionEmployee( String first, String last,
9 String socialSecurityNumber, double grossSalesAmount,
10 double rate, double baseSalaryAmount )
11 {
12 super( first, last, socialSecurityNumber, grossSalesAmount, rate );
13 setBaseSalary( baseSalaryAmount );
14 }
15
16 // set base-salaried commission employee's base salary
17 public void setBaseSalary( double salary )
18 {
19 baseSalary = salary < 0.0 ? 0.0 : salary;
20 }
21
22 // return base-salaried commission employee's base
salary 23 public double getBaseSalary()
24 {
25 return baseSalary;
26 }
27
28 // return String representation of BasePlusCommissionEmployee
29 public String toString()
30 {
31 return "\nBase-salaried commission employee: " +
32 super.getFirstName() + " " + super.getLastName() +
33 "\nSocial security number: " + super.getSocialSecurityNumber() +
34 "\nBase salary: " + getBaseSalary() + "\nCommission rate: " +
35 getCommissionRate() + "\nGross sales: " + getGrossSales();
36 }
37
38 } // end class BasePlusCommissionEmployee

2 // Employee hierarchy test program.


3 import java.text.DecimalFormat;
4 import javax.swing.JOptionPane;
56
public class EmployeeTest {
78
public static void main( String[] args )
9{
10 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
11
12 // create Employee array
13 Employee employees[] = new Employee[ 4 ];
// initialize array with Employees
16 employees[ 0 ] = new SalariedEmployee( "John", "Smith",
17 "111-11-1111", 800.00 );
18 employees[ 1 ] = new CommissionEmployee( "Sue", "Jones",
19 "222-22-2222", 10000, .06 );
20 employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis",
21 "333-33-3333", 5000, .04, 300 );
22 employees[ 3 ] = new HourlyEmployee( "Karen", "Price",
23 "444-44-4444", 16.75, 40 );
24
25 String output = "";
26
27 // generically process each element in array employees
28 for ( int i = 0; i < employees.length; i++ )
29 output += employees[ i ].toString() + "\nEmployee " + i +
30 " is a " + employees[ i ].getClass().getName() + "\n";
31
32 JOptionPane.showMessageDialog( null, output ); // display output
33 System.exit( 0 );
34
35 } // end main
36
37 } // end class Empl
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-5
-----------------------------------------------------------------------------------------------------------
1. Create an interface called shape with one method area. Create two classes Triangle
and Rectangle that implements that interface and display area.
2. Examine the following program fragment:
int[] array = { 1, 4, 3, 6, 8, 2, 5};
int what = array[0];
// scan the array
for ( int index=0; index < array.length; index++ )
{
if ( array[ index ] < what )
what = array[ index ];
}
System.out.println( what );
What does the fragment write to the monitor?
a. 1
b. 5
c. 1 4 3 6 8 2 5
d. 8

3. Fill in the blank in the following code fragment so that each element of the array is
assigned twice the value of its index.
int[] array = new int[10];
// scan the array
for ( int index=0; index < array.length; index++ )
{
_______________________
}
a. index = 2*index;
b. array[ 2*index ] = 2*index;
c. array[ index ] = 2*array[ index ];
d. array[ index ] = 2*index;
Answers to Tutorial Sheet-5

1.
interface shape
{
public int area(int x,int y);
}

class Rectangle implements shape


{
public int area(int a,int b)
{
return a*b;
}
}

class Triangle implements shape


{
public int area(int a,int b)
{
return 0.5*a*b;
}
}

class Test
{
public static void main(String ar[])
{
shape s;
Rectangle r=new Rectangle();
Triangle t=new Triangle();
s=r;
System.out.println("Area of Rectangle
"+s.area(10,20)); s=t;
System.out.println("Area of Triangle "+s.area(10,20));
}
}

a. 1

3
d) array[ index ] = 2*index;
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-6
----------------------------------------------------------------------------------------------------------
1.create a student package which contains student information in a separate

directory. Access the package from current working directory.


Answers to Tutorial Sheets-6

1.
// class for student personal details (in a package
FIRST); package first;
public class Studentinfo
{
int age;
char sex;
String name,add,fn,mn;
public Studentinfo(int e,char f,String a,String b,String c,String d)
{
age=e;
sex=f;
name=a;
add=d;
fn=b;
mn=c;
}

public void display()


{
System.out.println("STUDENT PERSONAL DETAILS");
System.out.println("Name of the student is: "+name);
System.out.println("Age="+age);
System.out.println("Student is "+sex);
System.out.println("Address of the student is: "+add);
System.out.println("Father's name: "+fn);
System.out.println("Mother'sname is: "+mn);
}
}
// class for student acedamic details(in package FIRST)
package first;
public class Acedamicinfo
{
int avg,att,rollno;

public Acedamicinfo(int f,int g,int h)


{

avg=f;
att=g;
rollno=h;
}
public void display2()
{
System.out.println("STUDENT EDUCATIONAL DETAILS");
System.out.println("Roll no of the student "+rollno);
System.out.println("Average of Marks of student= "+avg);
System.out.println("Attendance of student ="+att+"%");

}
}
// class for faculty details(in package
second) package second;
public class Teacherinfo
{
String name,des,pos;

public Teacherinfo(String n,String d,String p)


{

name=n;
des=d;
pos=p;
}
public void display()
{

System.out.println("STAFF DETAILS");
System.out.println("Name of the Member "+name);
System.out.println("Designation= "+des);
System.out.println("His Posistion::"+pos);

}
}
// MAIN CLASS
import first.*;
import second.*;

class PackageDemo
{
public static void main(String args[])
{

first.Studentinfo a=new first.Studentinfo(18,'M',"PETER","Mr.


JOHN","Mrs.MARY","VIZAG");
a.display();
first.Acedamicinfo de= new first.Acedamicinfo(499,98,1248);
de.display2();
second.Teacherinfo b=new second.Teacherinfo("DAVID","Faculty","Professor");
b.display();
}
}
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-7
-----------------------------------------------------------------------------------------------------------------
1. Create a user defined exception called NonComputers.create a class that takes student
educational details as input from keyboard. If the branch of the student is other than CSE or
IT (ignore case sensitivity) the method has to throw the exception manually. Write a java
program to accomplish this task.
Answers to Tutorial Sheet-7

1.

import java.util.*;
// class to define exception
class NonComputers extends Exception
{
private String branch;
NonComputers(String s)
{
branch=s;
}
}
class UserExcep
{
// method that checks whether an exception is produced

public static void Check(String a) throws NonComputers


{
if(a.equalsIgnoreCase("IT") || a.equalsIgnoreCase("CSE"))
System.out.println("You Are in Computers");
else
throw new NonComputers(a);
}
// main method
public static void main (String args[])
{
Scanner s=new Scanner(System.in);
String n;
System.out.println("enter
Branch"); n=s.next();
try
{
Check(n);
}
catch(NonComputers f)
{
System.out.println("Exception Occurred Belongs to NONCOMPUTERS.BRANCH IS
"+n);
}
}
}
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-8
1. List five common examples of exceptions.
2. Give several reasons why exception-handling techniques should not be used for
conventional program control.
3. Why are exceptions particularly appropriate for dealing with errors produced by methods
of classes in the Java API?
4. What is a “resource leak”?
5. If no exceptions are thrown in a try block, where does control proceed to when the try
block completes execution?
6. Give a key advantage of using catch( Exception exceptionName ).
7. Should a conventional application catch Error objects? Explain.
8. What happens if no catch handler matches the type of a thrown object?
9. What happens if several catch blocks match the type of the thrown object?
10. Why would a programmer specify a superclass type as the type in a catch block?
11. What is the key reason for using finally blocks?
12. What happens when a catch block throws an Exception?
13. What does the statement throw exceptionReference do in a catch block?
14 .What happens to a local reference in a try block when that block throws an Exception?
ANSWERS

1 Memory exhaustion, array index out of bounds, arithmetic overflow, division by zero,
invalid method parameters.

2 a) Exception handling is designed to handle infrequently occurring situations that often


result in program termination, so compiler writers are not required to implement exception
handling to perform optimally. (b) Flow of control with conventional control structures
is generally clearer and more efficient than with exceptions. (c) Problems can occur because
the stack is unwound when an exception occurs and resources allocated prior to the exception
may not be freed. (d) The “additional” exceptions can get in the way of genuine error-type
exceptions. It becomes more difficult for the programmer to keep track of the larger number
of exception cases.

3 It is unlikely that methods of classes in the Java API could perform error processing
that would meet the unique needs of all users.

4 A “resource leak” occurs when an executing program does not properly release a resource
when the resource is no longer needed. If the program attempts to use the resource
again in the future, the program may not be able to access the resource.

5 The catch clauses for that try statement are skipped, and the program resumes
execution after the last catch clause. If there is a finally clause, it is executed first then the
program resumes execution after the finally clause.

6 The form catch( Exception e ) catches any type of exception thrown in a try
statement. An advantage is that no thrown Exception can slip by without at least being
caught. The programmer can then decide to handle the exception or possibly rethrow the
exception.

7 Errors are usually serious problems with the underlying Java system; most programs
will not want to catch Errors because the program will not be able to recover from such
problems.

8 This causes the search for a match to continue in the next enclosing try statement.

9 The first matching catch clause after the try block is executed.

10 This enables a program to catch related types of exceptions and process them in a uniform
manner. However, it is often useful to process the subclass types individually for more
precise exception handling.

11 The finally clause is the preferred means for preventing resource leaks.

12 The exception will be processed by a catch handler (if one exists) associated with an
enclosing try block (if one exists).

13 It rethrows the exception for processing by an exception handler of an enclosing try


block.
14 The reference goes out of scope, and the reference count for the object is decremented.
If the reference count becomes zero, the object is marked for garbage collection.
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-9
-----------------------------------------------------------------------------------------------------------------
1. Create a user defined exception called NonComputers.create a class that takes student
educational details as input from keyboard. If the branch of the student is other than CSE or
IT (ignore case sensitivity) the method has to throw the exception manually. Write a java
program to accomplish this task.
Answers to Tutorial Sheet-9

1.

import java.util.*;
// class to define exception
class NonComputers extends Exception
{
private String branch;
NonComputers(String s)
{
branch=s;
}
}
class UserExcep
{
// method that checks whether an exception is produced

public static void Check(String a) throws NonComputers


{
if(a.equalsIgnoreCase("IT") || a.equalsIgnoreCase("CSE"))
System.out.println("You Are in Computers");
else
throw new NonComputers(a);
}
// main method
public static void main (String args[])
{
Scanner s=new Scanner(System.in);
String n;
System.out.println("enter
Branch"); n=s.next();
try
{
Check(n);
}
catch(NonComputers f)
{
System.out.println("Exception Occurred Belongs to NONCOMPUTERS.BRANCH IS
"+n);
}
}
}
OOPS THROUGH JAVA
III B.Tech ECE
Tutorial Sheet-10
---------------------------------------------------------------------------------------------------------------
Fill in the blanks in each of the following statements:
a) C and C++ are -----------threaded languages whereas Java is a ------ –threaded language.
b) Three reasons an alive thread might not be Runnable are that it is------ ,----------and------ .
c) A thread enters the Dead state when ----------- .
d) A thread’s priority can be changed with------- method .
e) A thread may give up the processor to a thread of the same priority by calling Thread
-----------method .
f) To pause for a designated number of milliseconds and resume execution, a thread should
call------------ method .
g) ---------- Method moves a single thread in an object’s Waiting state to the Ready state.
h)------------ Method moves every thread in an object’s Waiting state to the Ready state.

State whether each of the following is true or false. If false, explain why.
a) A thread is not Runnable if it is dead.
b) In Java, a higher priority Runnable thread should pre-empt threads of lower priority.
c) Some operating systems use time slicing with threads. Therefore, they can enable threads
to pre-empt threads of the same priority.
d) Threads may yield to threads of lower priority.

2. What is time slicing? Give a fundamental difference in how scheduling is performed on


Java systems that support time slicing vs. scheduling on Java systems that do not support time
slicing. Why would a thread ever want to call yield?
Answers to Tutorial Sheet-10

1.
a. single, multi.
b. Waiting, Sleeping, Blocked for input/output.
c. its run method terminates.
d. setPriority
e. yield
f. sleep
g. notify
h. notifyAll

2.
a. True
b. True
c. False. Timeslicing allows a thread to execute until its timeslice (or quantum) expires.
d. False. Threads can only yield to threads of equal priority.

3.
Time slicing specifies that each thread can use the processor for a limited amount of time.
When a thread’s time slice expires, a thread of equal priority gets a chance to execute.
Systems that do not support time slicing will not pre-empt a thread with the same priority.
The waiting thread cannot execute until the thread in the processor has completed its task or
removes itself from the processor.
OOPS THROUGH JAVA
III B.Tech ECE III B.Tech ECE
Tutorial Sheet-11

Create login page using Applets

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class Loginform extends Frame implements ActionListener

{ Label l1=new Label("user name");

Label l2=new Label("password");

Label l3=new Label(" ");

TextField t1=new TextField();

TextField t2=new TextField();

Button b= new Button("Submit");

public Loginform()

{ add(l1);

add(t1);

add(l2);

add(t2);

add(b);

add(l3);

l1.setBounds(20,45,70,20);

t1.setBounds(180,45,200,20);
l2.setBounds(20,95,70,20);

t2.setBounds(180,95,200,20);

b.setBounds(310,145,70,20);

b.addActionListener(this);

t2.setEchoChar('*');

addWindowListener(new mwa());

public void actionPerformed(ActionEvent e)

{ l3.setText("Welcome "+t1.getText());}

public static void main(String s[])

{ Loginform l=new Loginform();

l.setSize(new Dimension(600,600));

l.setTitle("Login");

l.setVisible(true);

class mwa extends WindowAdapter

{ public mwa(){}

public void windowClosing(WindowEvent e)

{ System.exit(0);

}
Output
OOPS THROUGH JAVA
III B.Tech ECE III B.Tech ECE
Tutorial Sheet-12

Write a Java Program that displays no.of mouse clicks

public class MyFrame extends JFrame implements MouseListener{

/** Number of times the mouse was clicked */


private int clicks = 0;

public MyFrame ()
{
this.addMouseListener(this);
}

public void mouseClicked(MouseEvent e)


{
//Increment click count
clicks++;
}

public void mouseEntered(MouseEvent e) {}


public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e) { }

}
OOPS THROUGH JAVA
III B.Tech ECE III B.Tech ECE
Tutorial Sheet-13

------------------------------------------------------------------------------------------------------------

Questions

1. What listener would you implement to be notified when a particular component has
appeared on screen? What method tells you this information?

2. What listener would you implement to be notified when the user has finished
editing a text field by pressing Enter? What listener would you implement to be
notified as each character is typed into a text field? Note that you should not
implement a general- purpose key listener, but a listener specific to text.

3. What listener would you implement to be notified when a spinner???s value


has changed? How would you get the spinner???s new value?

4. The default behavior for the focus subsystem is to consume the focus traversal
keys, such as Tab and Shift Tab. Say you want to prevent this from happening in one
of your application???s components. How would you accomplish this?
ANSWERS

Question 1: What listener would you implement to be notified when a particular


component has appeared on screen? What method tells you this information?
Answer 1: You would register a ComponentListener on the component.
The componentShown method. This method is called when the window is first displayed
or is deiconified.

Question 2: What listener would you implement to be notified when the user has
finished editing a text field by pressing Enter? What listener would you implement to
be notified as each character is typed into a text field? Note that you should not
implement a general-purpose key listener, but a listener specific to text.
Answer 2: To be notified when the user presses Enter, you would register
an ActionListener on the text field; the actionPerformed method is called when the
user types Enter. Note that the Enter character is not part of the resulting string. To be
notified as each character is typed, you would register a DocumentListener on the text
field's Document. The insertUpdate method is then called as each character is typed.
Note that this is not the correct way to implement input validation. For that behavior
you should check out the Input Verification API section in How to Use the Focus
Subsystem.

Question 3: What listener would you implement to be notified when a spinner???s


value has changed? How would you get the spinner???s new value?
Answer 3: To be notified when the value has changed, you would register
a ChangeListener on the spinner. You would get the new value through the event's
source in the stateChanged method. The following code snippet shows how this could
be done:
public void stateChanged(ChangeEvent e) {
JSpinner mySpinner = (JSpinner)(e.getSource());
SpinnerNumberModel model = (SpinnerNumberModel)(mySpinner.getModel());
Number currentValue = model.getNumber();
...
}

Question 4: The default behavior for the focus subsystem is to consume the focus
traversal keys, such as Tab and Shift Tab. Say you want to prevent this behavior in
one of your application???s components. How would you accomplish this?
Answer 4: You call setFocusTraversalKeysEnabled(false) on that particular
component. Note that you must then handle focus traversal manually. See How to
Write a Key Listener and How to Use the Focus Subsystem for more information.
OOPS THROUGH JAVA
III B.Tech ECE III B.Tech ECE
Tutorial Sheet-15
-----------------------------------------------------------------------------------------------------------
1. Create the following GUI. You do not have to provide any functionality.
Answers to Tutorial Sheet-11

import java.awt.*;
import javax.swing.*;

public class ColorSelect extends JFrame {


private JButton ok, cancel;
private JCheckBox background, foreground;
private JComboBox colorList;
private JPanel panel, panel2;

// create components and add them to applet


public ColorSelect()
{
super( "ColorSelect" );

getContentPane().setLayout( new BorderLayout() );

// north
colorList = new JComboBox();
colorList.addItem( "RED" );
getContentPane().add( colorList, BorderLayout.NORTH );

// center
panel = new JPanel();
background = new JCheckBox( "Background" );
foreground = new JCheckBox( "Foreground" );
panel.add( background );
panel.add( foreground );
getContentPane().add( panel, BorderLayout.CENTER );

// south
ok = new JButton( "Ok" );
cancel = new JButton( "Cancel" );
panel2 = new JPanel();
panel2.add( ok );
panel2.add( cancel );
getContentPane().add( panel2, BorderLayout.SOUTH );

setSize( 300, 125 );


setVisible( true );

} // end constructor

// execute application
public static void main ( String args[] )
{
ColorSelect app = new ColorSelect();
app.setDefaultCloseOperation( EXIT_ON_CLOSE );
}

} // end class ColorSelect