Java - Old Lan
Java - Old Lan
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
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.
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
10 TUTORIAL-2(Arrays, constructors)
19 TUTORIAL-4(Inheritance)
29 TUTORIAL-7(Interfaces)
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
34 TUTORIAL-8(Exceptions)
41 TUTORIAL-10(Threads)
42 To learn about Synchronizing Threads T1Ch.11.292
Synchronization
44 TUTORIAL-11(Synchronizing Threads)
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)
55 TUTORIAL-14(Event handling)
58 Usage of various User Choices, list panels, scroll panes ,Dialogs , T1 Ch.22
interface components menubar 748 752
775 782
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
G. Narasinga Rao
Signature of the Instructor Signature of the course-coordinator
OOPS Through JAVA Lecture Notes-1 Unit- I
Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that 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.
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.
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
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.
The general form of a class definition is shown here:
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 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
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.
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.
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.
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.
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 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
• ByteCode produced on any platform may be executed on any other platform which supports a
VM
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
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.
Because an object is an instance of a class, you will often see the two words object and instance used
interchangeably.
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;
// ...
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.
The Bicycle class uses the following lines of code to define its fields:
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
class Box {
double width;
double height;
double depth;
class BoxDemo2 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
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:
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.
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.
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.
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:
This statement combines the two steps just described. It can be rewritten like this to show each step
more clearly:
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.
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 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.
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 b2 = b1;
// ...
b1 = null;
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:
The first line creates an object of the Point class, and the second and third lines each create an object of
the Rectangle class.
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.
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:
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:
Initializing an Object
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:
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:
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
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;
}
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:
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:
The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a
no-argument constructor:
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.
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:
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:
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:
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:
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:
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:
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.
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
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.
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for
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");
}
}
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;
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++;
}
}
}
Output:
Syntax: do
{
statements;
} while (condition);
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.
· 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:
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;
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
Note: goto statement is not available in java, because it leads to confusion and forms infinite
loops.
Arrays
An array is a group of liked-typed variables referred to by a common name, with individual
variables accessed by their index.
Array Creation
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]
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:
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
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.
Because an object is an instance of a class, you will often see the two words object and instance used
interchangeably.
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;
// ...
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.
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.
The Bicycle class uses the following lines of code to define its fields:
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
class Box {
double width;
double height;
double depth;
class BoxDemo2 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
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:
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.
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.
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.
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:
This statement combines the two steps just described. It can be rewritten like this to show each step
more clearly:
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.
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 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.
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 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:
Initializing an Object
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:
Here's the code for the Rectangle class, which contains four constructors:
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
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;
}
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:
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:
The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a
no-argument constructor:
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.
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:
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:
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:
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:
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:
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:
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.
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
Let’s begin by defining a simple constructor that simply sets the dimensions of each box
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
double volume() {
class BoxDemo6 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
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:
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
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.
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.
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
double volume() {
class BoxDemo7 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Volume is 3000.0
Volume is 162.0
As you can see, each object is initialized as specified in the parameters to its constructor.
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.
What if you simply wanted a box and did not care (or know)
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:
*/
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
Box() {
Box(double len) {
double volume() {
class OverloadCons {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
vol = mycube.volume();
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.
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.
class Test {
i *= 2;
j /= 2;
class CallByValue {
ob.meth(a, b);
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.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
class CallByRef {
ob.meth(ob);
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.
Access Specifiers: An access specifier is a key word that represents how to access a member
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 default: if no access specifier is used then default specifier is used by java compiler.
The access modifiers supported by Java are static, final, abstract, synchronized, native, volatile, transient
and strictfp.
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;
To understand the effects of public and private access, consider the following program:
*/
class Test {
// methods to access c
c = i;
return c;
class AccessTest {
ob.a = 10;
ob.b = 20;
ob.setc(100); // OK
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,
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.
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.*/
// Initialize top-of-stack
Stack() {
tos = -1;
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
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 {
System.out.println("Stack in mystack1:");
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
System.out.println(mystack2.pop());
// 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.
• 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:
class UseStatic {
static int a = 3;
static int b;
static {
b = a * 4;
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,
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.
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 {
class StaticByName {
StaticDemo.callme();
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
–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:
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
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
Program : Write a program to use ‘this’ to refer the current class parameterized constructor
//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
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.
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.
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.
What if you simply wanted a box and did not care (or know)
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:
*/
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
Box() {
Box(double len) {
double volume() {
class OverloadCons {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
vol = mycube.volume();
As you can see, the proper overloaded constructor is called based upon the parameters specified when
new is executed.
Garbage Collection
Garbage collection is a mechanism to remove objects from memory when they are no longer needed.
1) The garbage collector keeps track of how many references an object has.
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.
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.
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();
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:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
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.
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");
}
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;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
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
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.
HIERARCHICAL INHERITANCE
B C
D
MULTIPLE INHERITANCE
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.
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;
}
}
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
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.
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.
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,
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:
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.
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.
}
}
class Rose extends Flower
{
public void smell()
{
System.out.println("rose smell");
Forms of Inheritance
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[])
{
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,
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()
{
}
class B extends A
{
void display()
{
System.out.println("hello");
}
public static void main(String args[])
{
B b=new B();
b.display();
}
}
Output:hello
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.
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
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.
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.
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();
}
}
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.
}
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.
• 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.
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:
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.
Use: Overriden methods allow Java to support Run-time polymorphism. This leads to Robustness by
Reusability.
super can be used to refer super class constructor as: super (values)
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);
}
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
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:
i in superclass: 1
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.
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
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
{
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.
}
}
Output:
Cannot inherit from final Demo1
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.
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()
{
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 ()
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.
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.
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
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:
{ double dim1;
double dim2;
{ dim1 = a;
dim2 = b;
class AbstractAreas
output:
Area is 45.0
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.
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.
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.
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.
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.
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.
//creating a package
package pack;
{ d1 = a;
d2 = b;
import pack.Addition;
class Use
ob1.sum();
Program 3: Write a program to add one more class Subtraction to the same package pack.
package pack;
{ d1 = a;
d2 = b;
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.
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;
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;
package pack1.pack2;
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);
}}
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.
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.
13 Abstractions
14 Multiple Inheritance
An interface is defined much like a class. This is the general form of an interface:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
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-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
int a, b;
void show() {
// ...
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
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
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.
}
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 (); } }
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.
interface IntStack {
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;
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:
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
Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as
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:
interface A {
void meth1();
void meth2();
interface B extends A {
void meth3();
System.out.println("Implement meth1().");
System.out.println("Implement meth2().");
System.out.println("Implement meth3().");
class IFExtend {
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.
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
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.
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
catch(ExceptionType exOb)
//...
finally
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:
S.Vani Kumari,CSE,GMRIT
OOPS Through JAVA Lecture Notes- 24 Unit- III
Exception Hierarchy
library
java
lang
Package
Throwable
Super Class
class
Excepion
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.
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;
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.
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
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
Example:
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).
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:
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:
/* 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.");
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:
class NestTry {
try {
int a = args.length;
int b = 42 / a;
if(a==2) {
int c[] = { 1 };
} catch(ArrayIndexOutOfBoundsException e) {
} catch(ArithmeticException 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
C:\>java NestTry
a=1
a=2
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( ):
calls to methods. */
class MethNestTry {
if(a==2) {
int c[] = { 1 };
} catch(ArrayIndexOutOfBoundsException e) {
try {
int a = args.length;
a divide-by-zero exception. */
int b = 42 / a;
nesttry(a);
} catch(ArithmeticException e) {
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;
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 {
try {
} catch(NullPointerException e) {
try {
demoproc();
} catch(NullPointerException 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:
The program also illustrates how to create one of Java’s standard exception objects. Pay close attention
to this line:
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
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:
// 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.
class ThrowsDemo {
System.out.println("Inside throwOne.");
throwOne();
class ThrowsDemo {
System.out.println("Inside throwOne.");
try {
throwOne();
} catch (IllegalAccessException e) {
inside throwOne
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the
normal flow through the method. Depending upon how the method is coded, it is even possible for an
exception to cause the method to return prematurely. This could be a problem in some methods. For
example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. The finally keyword is designed to
address this contingency.
finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown. If an exception is thrown,
the finally block will execute even if no catch statement matches the exception.
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 {
try {
System.out.println("inside procA");
} finally {
System.out.println("procA's finally");
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
procB();
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.
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.
Built-in Exceptions
Built-in Exceptions
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
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.
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.
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
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.
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
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.
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.
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.
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
}
Class Demo
{
Public static void main(String args[])throws InterruptedException
{
Myclass obj=new Myclass();
Thread t=new Thread(obj);
t.start();
Thread.MIN_PRIORITY value is 1
Thread.NORM_PRIORITY value is 5
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.
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
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.
{ If(stop==true) return; }
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’.
To synchronize an entire method code we can use synchronized word before method name
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.
}
}
Output:
Press Control+C to exit
Put:0
Get:0
Put:1
Get1
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.
t.setDeamon(true);
boolean x=t.isDaemon().
for(int i=0;i<5;i++)
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
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);
}
}
To execute an applet in a Web browser, you need to write a short HTML text file that contains
the appropriate APPLET tag.
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.
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
1.Simple applets
2.JApplets
Applet
Graphics
Syntax:
import java.awt.*;
import java.applet.*;
Designing a Webpage:
<HTML>
<BODY>
</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>
<HTML>
</APPLET>
</BODY>
</HTML>
To run the applet we must have the following files in our current directory
1.AppletDemo.java
2.AppletDemo.class
3.AppletTest.html
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.*;
<HTML>
<BODY>
</APPLET>
</BODY>
</HTML>
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>
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)
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.
Method Description
P.Muralidhar CSE GMRIT
OOPS Through JAVA Lecture Notes -38 Unit-IV
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.
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.
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";
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:
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 ();
} // 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:
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.
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.
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.
Instead, they are written entirely in Java and, therefore, are platform-independent.
7.JComboBox : Encapsulates a combo box (an combination of a drop-down list and text
field).
Limitations of AWT
AWT supports limited number of GUI components.
•Labels are passive controls that do not support any interaction with the user.
2.Label(String str)
•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:
Canvas :
•It is not part of the hierarchy for applet or frame windows
•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.
•Scroll bars are used to select continuous values between a specified minimum and
maximum.
•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.
•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.
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
•The second form creates a text field that is numChars characters wide.
•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.
•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.
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.
2.Checkbox(String str)
•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 obtain the current label associated with a check box by calling getLabel( ).
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);
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();
Choices
•The Choice class is used to create a pop-up list of items from which the user may choose.
•Choice only defines the default constructor, which creates an empty list.
•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:
Panels
•The Panel class is a concrete subclass of Container.
•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.
2.HORIZONTAL_SCROLLBAR_AS_NEEDED
3.VERTICAL_SCROLLBAR_ALWAYS
4.VERTICAL_SCROLLBAR_AS_NEEDED
Dialogs
•Dialog class creates a dialog window.
•The dialog box allows you to choose a method that should be invoked when the button is
clicked.
MenuBar
•MenuBar class creates a menu bar.
•This class only defines the default constructor. Next, create instances of Menu that will
define the selections displayed on the bar.
•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:
•It is passed to an applet when one of its various methods, such as paint( ) or update( ), is
called.
•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:
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.
Whenever a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.
Grid Layout
Flow Layout
Card 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.
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.
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)
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
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 {
x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
result = x * y * z;
System.exit( 0 );
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.
2.
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 );
}
/ 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
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 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
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;
}
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;
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[])
{
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
1 Memory exhaustion, array index out of bounds, arithmetic overflow, division by zero,
invalid method parameters.
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).
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
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.
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
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
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());
{ l3.setText("Welcome "+t1.getText());}
l.setSize(new Dimension(600,600));
l.setTitle("Login");
l.setVisible(true);
{ public mwa(){}
{ System.exit(0);
}
Output
OOPS THROUGH JAVA
III B.Tech ECE III B.Tech ECE
Tutorial Sheet-12
public MyFrame ()
{
this.addMouseListener(this);
}
}
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.
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 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 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.*;
// 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 );
} // end constructor
// execute application
public static void main ( String args[] )
{
ColorSelect app = new ColorSelect();
app.setDefaultCloseOperation( EXIT_ON_CLOSE );
}