Object Oriented Programming Using Java - (CSIT120) R
Object Oriented Programming Using Java - (CSIT120) R
in
nl
O
ty
Object Oriented Programming Using Java
r si
ve
ni
U
ity
m
)A
(c
e
in
© Amity University Press
nl
No parts of this publication may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise
without the prior permission of the publisher.
O
Advisory Committee
ty
Chairman : Ms. Monica Agarwal
Members : Prof. Arun Bisaria
si
Dr. Priya Mary Mathew
Prof. Aindril De
r
Mr. Alok Awtans
ve
Dr. Coral J Barboza
Dr. Monica Rose
Mr. Sachit Paliwal
ni
Published by Amity University Press for exclusive use of Amity Directorate of Distance and Online Education,
Amity University, Noida-201313
Contents
e
Page No.
in
Module – 1 : OOP and Introduction to Java 01
1.1 Introduction to Object Oriented Programming
1.1.1 Fundamentals of object oriented programming:Procedure Oriented Programming Vs. Object
Oriented Programming (OOP)
nl
1.1.2 Concept of Classes and Object
1.1.3 Object reference, Abstraction,Encapsulation
O
1.1.4 Inheritance, Polymorphism
1.2 Introduction to Java
1.2.1 History of Java, Java vs C++.
1.2.2 JDK, JVM and Other tools for Java Application
ty
1.2.3 IDE for developing Java Application
1.2.4 “Constructs used in JAVA :
1.2.5 Variables, types and type declarations”
si
1.2.6 Data types, Functions
1.3 Statements & Operators in Java
1.3.1 Increment and Decrement Operators r
ve
1.3.2 Relational and Logical operators
1.3.3 Conditional Expressions, if then else clause
1.3.4 Input using scanner class and output statement
1.3.5 Loops,Switch case
ni
e
2.3 Throwing Exceptions
2.3.1 Implementation of finally, throw & throws
in
2.3.2 Fundamentals of throwing exceptions
2.3.3 Java’s buit-in Exceptions
nl
2.3.4 Writing Exception Subclasses
2.3.5 Implementation of Exception Handling Mechanism.
O
3.1 Introduction to Packages
3.1.1 Constructors
3.1.2 Object & Object Reference
ty
3.1.3 Types of Constructors
3.1.4 Implementation of Constructors in Inheritance
3.1.5 order of invocation of constructors
si
3.2 Wrapper classes and String class
3.2.1 Introduction to Wrapper Classes
r
3.2.2 Strings and Characters : Fundamentals of Characters and Strings
3.2.3 The String Class , String Operations
ve
3.2.4 Data Conversion using Value Of ( ) Methods
3.3 StringBuffer class
3.3.1 Fundamental Concept of StringBUffer Class
ni
e
4.3.7 Thread Priorities
4.4 Thread Synchronization
in
4.4.1 Introduction to Synchronization
4.4.2 Implementing Synchronization in Thread
nl
4.4.3 Benefits and Loopholes of Synchronization
4.4.4 Resuming and stopping Threads
4.4.5 A code snippet to demonstrate thread with and without synchronization
O
Module - 5 : Applet and Graphics Programming 320
5.1 Introduction to Applet Class
5.1.1 Introduction to applets
ty
5.1.2 Lifecycle of Applet
5.1.3 Methods of Applet class
5.1.4 Applet vs Application
si
5.1.5 Embedding Applet in HTML Page
5.1.6 A code snippet to implement Applet
5.2 Introduction to Graphic class
5.2.1 Introduction to Graphic class
r
ve
5.2.2 Methods in Graphic class
5.2.3 A code snippet to create different shapes.
5.2.4 Using loops in applet
ni
e
Structure:
in
1.1 Introduction to Object Oriented Programming
1.1.1 Fundamentals of object oriented programming:Procedure Oriented
nl
Programming Vs. Object Oriented Programming (OOP)
1.1.2 Concept of Classes and Object
1.1.3 Object reference, Abstraction,Encapsulation
O
1.1.4 Inheritance, Polymorphism
1.2 Introduction to Java
ty
1.2.1 History of Java, Java vs C++.
1.2.2 JDK, JVM and Other tools for Java Application
1.2.3 IDE for developing Java Application
si
1.2.4 “Constructs used in JAVA :
1.2.5 Variables, types and type declarations”
1.2.6 Data types, Functions r
ve
1.3 Statements & Operators in Java
1.3.1 Increment and Decrement Operators
1.3.2 Relational and Logical operators
ni
e
Programming
in
Objectives
At the end of this unit, you will be able to understand:
nl
●● Basics of Object Oriented programming Difference between OOP and procedure
oriented programming
●● Classes and object and their concept
O
●● Understanding concept of Object reference, Abstraction, Encapsulation
●● Understanding concept of Inheritance, Polymorphism
ty
Introduction
In order to unravel a problem, you would like to understand the “method/procedure”
otherwise you got to have the “know-how”. In computer parlance, we call this an
si
algorithm. An algorithm or a program may be a sequence of steps to be followed, which
results in a desired output. The sequence of steps is often called a procedure, and,
in turn, a gaggle of procedures are often termed as a program. For solving an easy
r
problem, a sequence of steps is sufficient, but if the matter is complex, a programming
ve
environment that has well-integrated and cohesive programming elements, constructs
and data structures is required.
been very successful and popular amongst programmers, owing largely to its reusable
components within the sort of procedural calls and its ability to control memory and thus
handle hardware integration.
ity
is one of the most powerful OOP languages that supports together structured as well as
OOP paradigms.
(c
Notes
e
in
nl
O
ty
si
1.1.1 Fundamentals of object oriented programming: Procedure
Oriented Programming Vs. Object Oriented Programming
(OOP)
A variable is simply a memory location (or several locations treated as a unit) that
has been given a reputation in order that it are often easily mentioned and utilized in
U
a program. The programmer only has got to worry about the name; it’s the compiler’s
responsibility to stay track of the memory location. The programmer does got to confine
mind that the name refers to a sort of “box” in memory which will hold data, albeit the
programmer doesn’t need to know where in memory that box is found.
ity
In Java and most other languages, a variable features a type that indicates what
kind of data it can hold. One sort of variable might hold integer numbers like 5, -14,
and 0— while another holds floating point numbers with decimal points like 2.14, -2.7,
or 17.0. There could even be types for individual characters (’Z’, ’;’, etc.), strings (“Hi”,
m
“A string can include many characters”, etc.), and fewer common types like dates, time,
sounds, or the other sort of data that a program might got to store.
Programming languages always have commands for getting data into and
)A
out of variables and for doing computations with data. for instance , the subsequent
“assignment statement,” which could appear during a Java program, tells the pc to
require the amount stored within the variable named “principal”, multiply that number by
0.012, then store the end in the variable named “interest”:
(c
There also are “input commands” for getting data from the user or from files on the
Notes
e
computer’s disks and “output commands” for sending data within the other direction.
These basic commands—for moving data from place to put and for performing
in
computations—are the building blocks for all programs. These building blocks are
combined into complex programs using control structures and subroutines.
nl
Objects and Object-oriented Programming
Programs must be designed. Nobody can just sit down at the pc and compose a
program of any complexity. The discipline called software engineering cares with the
O
development of correct, working, well-written programs. The programmer tends to use
accepted and proven methods for analyzing the matter to be solved and for designing a
program to unravel that problem.
The procedural approach to programming was the de facto approach within the
ty
youth of programming. Here, code is modularized supported a system’s processes.
as an example , in developing a Hotel application system, we might have considered
processes like the checking-in and Check-out of rooms, making reservations of rooms,
si
cataloging of hotels room, and so on. Problem solving would involve the analysis of
those processes in terms of the procedural tasks administered and therefore the
production of a system whose representation is predicated on the procedural flow of the
processes. r
ve
Object-oriented programming, on the opposite hand, models objects and therefore
the interactions within the problem space and the production of a system supported
these objects and their interactions.
During the 1970s and into the 80s, the first software engineering methodology was
structured programming. The structured programming approach to program design was
ity
supported the subsequent advice: to unravel an outsized problem, break the matter
into several pieces and work on each bit separately; to unravel each bit, treat it as a
replacement problem which may itself be weakened into smaller problems; eventually,
you’ll work your way right down to problems which will be solved directly, without further
decomposition. This approach is named top-down programming.
m
There is nothing wrong with top-down programming. It’s a valuable and often-
used approach to problem-solving. However, it’s incomplete. For one thing, it deals
)A
almost entirely with producing the instructions necessary to unravel aissue. But as
time went on, people realized that the planning of the info structures for a program was
as least as important because the design of subroutines and control structures. Top-
down programming doesn’t give adequate consideration to the info that the program
manipulates.
(c
e
bottom-up design, the approach is to start out “at rock bottom ,” with problems that
you simply already skills to unravel (and that you would possibly have already got a
reusable software component at hand). From there, you’ll work upwards towards an
in
answer to the general problem
nl
a component of a bigger system that interacts with the remainder of the system during
a simple, well-defined, straightforward manner. The thought is that a module are often
“plugged into” a system. The small print of what goes on inside the module aren’t
important to the system as an entire, as long because the module fulfills its assigned
O
role correctly. This is often called information hiding, and it’s one among the foremost
important principles of software engineering.
ty
programming languages within the early 1980s. Since then, a more advanced sort of
an equivalent idea has more or less appropriated software engineering. This latest
approach is named object-oriented programming, often abbreviated as OOP.
si
The central concept of object-oriented programming is that the object, which may
be a quite module containing data and subroutines. The point-of-view in OOP is that an
object may be a quite independent entity that has an indoor state (the data it contains)
r
which can answer messages (calls to its subroutines). A list object, for instance,
ve
features a state consisting of an inventory of names and numbers. If you send it a
message telling it to feature a reputation, it’ll respond by modifying its state to reflect the
change. If you send it a message telling it to print itself, it’ll respond by printing out its
list of names and numbers.
ni
The message that Ashok has sent to Mukesh is a takeOrder message. It contains
information such as the type of sofa set (a White leather, Double bed set) and the date
of delivery (next Friday). This information is known as the parameters of the takeOrder
)A
message.
Notes
e
in
nl
Interaction between Ashok and Mukesh. Mukesh was able to respond to Ashok’s
takeOrder message because he understood it and had the means to handle Ashok’s
O
request. Although Mukesh knew how to satisfy Ashok’s request, Ashok did not. In fact,
most of the time, customers do not know how a salesperson has satisfied their orders.
All they get from salespersons are replies such as, “I am sorry, madam, we are unable
to satisfy your request because the sofa you wanted has been sold,” or “Sir, your
ty
request has been satisfied. We will deliver the goods on Friday between 10 am to 11
am to the address indicated. Thank you for your order.”
si
maintains his responsibility by applying a set of operations:
An invalid message, on the other hand, is one that the receiver does not have the
capability to respond to, that is, the receiver does not have a corresponding method to
)A
match the message. For example, if Ashok had requested a discount on the price, his
request would have been rejected because Mukesh, being a salesperson, would not
have the capability (or a corresponding method) to respond to the message.
Notes
e
in
nl
While Ashok may know what Mukesh can do through his methods, he may
O
not know how Mukesh does them. This is an important principle of object-oriented
programming known as information hiding: the sender of a message does not recognize
how a receiver is going to satisfy the request in the message.
ty
Procedural Programming:
“Procedural Programming is a, programming model which is a derivative from
structured programming, based upon the concept of calling procedure. Procedures,
si
also known as routines, subroutines or functions, simply consist of a chain of
computational steps to be carried out. During a program’s execution, any given
procedure might be called at some point, as well as by other procedures or itself.
r
Procedural Programming languages examples are C, ALGOL, COBOL.”
ve
Object Oriented Programming:
Object oriented programming is a programming model which is based on the
concept of objects. Objects contain data in the type of attributes and code in the type
ni
Programming:
Importance is not given to data but Importance is given to the data rather than
to functions as well as sequence of procedures or functions because it works as a
actions to be done real world.
)A
Most function uses Global data for objects can move and communicate with each
Notes
e
sharing that can be accessed freely other through member functions
from function to function in the
in
system
It does not have any proper way for OOP provides an easy way to add new data
hiding data so it is less secure and function.
nl
It does not have any proper way for OOP provides Data Hiding so provides more
hiding data so it is less secure securely
Overloading is not possible In OOP, data cannot move easily from function
to function, it can be kept public or private so
O
we can control the access of data
ty
Class
A class is a user defined design or sample from which objects are created. It
represents the set of properties or methods that are similar to all objects of one type. In
si
general, class declarations can comprise of these components, in order:
r
ve
ni
Object
U
Any entity that has state and behavior is understood as an object. For instance , a
chair, pen, table, keyboard, bike, etc. It is often physical or logical.
)A
(c
e
address and takes up some space in memory. Objects can communicate without
knowing the small print of every other’s data or code. The sole necessary thing is
that the sort of message accepted and therefore the sort of response returned by the
in
objects.
Example: A cat is an object because its states like color, name, moustache, breed,
nl
etc. also as behaviors like wagging the tail, playing, eating, etc.
O
ty
si
Lets understand class and object this way: In Chapter 1, we introduced Ashok.
r
Now, meet Ravi, another customer at Pepperfry. As customers of Pepperfry, Ashok and
Ravi share some similar information. For example, both have a name, phone number,
ve
and a budget—information that is relevant when describing customers. This information
is recognized as object attributes.
For example, Ashok may have a larger budget and thus a larger budget value (say
Rs.20000) than Ravi whose budget may be Rs.10000. together; the values of an
object’s attributes represent the state of the object.
U
Besides attributes, Ashok and Ravi also exhibit some behavior typical of a
customer. For instance, Ashok and Ravi execute a method when making a purchase.
Let us call this method buy(). The method buy() is made up of a set of operations that
Ashok and Ravi would use to send a purchase request to a salesperson.
ity
Ashokas an Object
Attributes:
m
name = Ashok
budget = 20000
Methods:
Ravi as an Object
Attributes:
Notes
e
name = Ravi
in
budget = 10000
Methods:
nl
buy() {send a purchase request to a salesperson}
O
Name, phone number and budget are attributes while buy() and getBudget()
are methods of the two objects. Note that both objects share a common definition
of attributes and methods. In fact, all customers of Pepperfry share the same set of
ty
attribute and method definitions. They all have attributes name, phone number and
budget, and methods buy() and getBudget(). In defining these objects, a common
definition known as class is used.
si
A class is a definition template for organizing and creating objects with the same
attributes and methods. Ashok and Ravi, being customers of Pepperfry, can therefore
be defined by a class called Customer as follows:
Class Customer r
ve
Attributes:
name
phone number
ni
budget
Methods:
U
“One major difference between objects and class is in the means of attributes
and methods are treated in objects and classes. A class is a definition about objects;
the attributes and methods in a class are thus declarations that do not contain values.
However, objects are created instances of a class. Each has its own attributes and
methods. The values of the set of attributes describe the state of the objects.”
m
Let us now examine the salespersons. Salespersons also have attributes and
methods. Mukesh and koyal are two salespersons at Pepperfry. They are capable of
a behavior typical of a salesperson, for example, taking orders from customers. To
)A
fulfill their role as salespersons in a purchase transaction, Mukesh and koyal perform
a method. We shall call this method takeOrder(), and represent Mukesh and koyal as
follows:
Mukesh as an Object
(c
Attributes:
name = “Mukesh”
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 11
Methods:
Notes
e
takeOrder() {
in
check with warehouse on delivery schedule
if ok
nl
then {instruct warehouse to deliver stock(address, date)
return ok}
O
else return not ok
ty
Koyal as an Object
Attributes:
si
name = “Koyal”
Methods:
takeOrder() {
r
ve
check with warehouse on stock availability
if ok
return ok}
}
ity
Being salespersons, Mukesh and Koyal share parallel attributes and methods
as expected. Like the customers, Sales person can be described by a class called
SalesPerson with the following representation:
Class SalesPerson
m
Attributes:
name
)A
Methods:
takeOrder() {
if ok
e
return ok}
in
}
Make sure that the definition of the SalesPerson class is unlike the Customerclass
nl
since customers and salespersons behave differently—customers make ordersand
salespersons take orders.
O
Hierarchical Relationship of Classes
Classes formed can be organized in a hierarchical manner. Based on the position
of a class in the hierarchy, it may be known as a superclass or a subclass of a class.
ty
Earlier, we introduced Mukesh and Koyal as salespersons of Pepperfry. We
also mentioned that Mukesh and Koyal are objects of the SalesPerson class. Let us
introduce two more employees, Simon and Sandeep. Specifically, Simon and Sandeep
si
are reporting managers with properties that are slightly different from Mukesh and
Koyal. We will classify Simon and Sandeep as objects of a different class: Reporting
Manager. All four persons are employees of Pepperfry and objects of another class:
Employee. The relationships of these classes and objects are illustrated in Figure
below. r
ve
Note that Mukesh and Koyal are shown as instances of the SalesPerson class
while Simon and Sandeep are instances of the Reporting Manager class. The enclosing
border of the Employee class over these objects indicates that the objects are also
instances of the Employee class.
ni
U
ity
Mukesh and Koyal therefore belong to two classes: the Employee class and
SalesPerson class. Likewise, Simon and Sandeep belong to the Employee and
Reporting Manager class. This implies that the information about Mukesh and Koyal as
)A
specified. For example, Mukesh takes orders and earns a commission for each sale
since he is a salesperson but this does not apply to Sandeep who is a manager, despite
the fact that both are employees of Pepperfry. Similarly, when we speak of an object as
Notes
e
an employee, we are being general and its differences with objects of other classes are
ignored.
in
The Employee class is said to be a generalized class of SalesPerson and
Reporting Manager. Conversely, SalesPerson and Reporting Manager are said to be
specialized classes of the Employee class. Generalized and specialized classes can be
nl
organized into a class hierarchy with the generalized classes placed toward the top of
the hierarchy and the specialized classes toward the bottom of the hierarchy.
O
class is known as a superclass of a subclass in object-oriented terms. For example,
SalesPerson is a subclass of the Employee class which is also the superclass of
SalesPerson.
ty
A Class Hierarchy Diagram
The hierarchical relationships among classes can be seen in a class hierarchy
diagram in below. A box in the figure below represents a class while a triangle denotes
si
the hierarchical relationship between classes with a superclass positioned at the peak.
Subclasses are placed toward the foot of a class hierarchy diagram.
Generalization
(c
generalized class. For example, the Mammal, Fish, Reptile, and Amphibian classes
Notes
e
introduced earlier, are similar in that all objects from these classes have a backbone.
Based on this similarity, we can refer to them via a new superclass, say Animal-with-
Backbone.
in
Hence, we can refer to Kermit (an object of the Amphibian class) as an object of
the Animal-with-Backbone class too. Similarly, the Mosquito class can be generalized
nl
into an Animal-without-Backbone class since objects from the Insert class are without a
backbone. Flowchart below summarizes the relationships of these classes.
O
ty
si
The Animal-with-Backbone class and Animal-without-Backbone class can be
more generalized by taking into consideration the similarities of objects from these
two classes. Let us call the generalized class, Super Animal. The generalization of
r
properties of Animal with-Backbone class and Animal-without-Backbone class into the
ve
Super Animal class is shown in diagram below.
ni
U
ity
The Super Animal class, being the topmost class in the class hierarchy, is thus the
m
most general class of the entire Super Animal class hierarchy. This means that Swift,
which is an object of the Fish class, is also an object of the Animal-with-Backbone class
and Super Animal class, for example. When we refer to Swift as an object of the Animal
)A
class, we are being general about it and we would be ignoring specific information
about Swift as a Fish in this reference.
Specialization:
On the contrary, specialization is the act of capturing differences among objects
(c
in a class and creating new different subclasses with the differences. In this fashion,
we are specializing information about objects of the superclass into subclasses. For
e
from the Super Animal class, we are distinguishing information about objects with a
backbone from others without a backbone into Animal-with-Backbone and Animal-
without Backbone classes.
in
Eventually, only objects with a backbone would be classified into the Animal-
with-Backbone class and the others into the Animal-without-Backbone class. Similarly,
nl
objects from the Animal-with-Backbone class can be further classified into the Mammal,
Fish, Reptile, or Amphibian classes depending on their properties definition.
O
1.1.3 Object reference, Abstraction, Encapsulation
ty
r si
ve
Primitive Types
ni
“Java has 8 built-in data types and is called primitive types. These data types
signify the building blocks for Java objects as all Java objects are just a complex
collection of these primitive data types.”
U
In Java, variables did not contain objects, but only the references to objects.
The objects are made and assigned in memory independently from the
declarations of variables. Specifically:
Objects denoted by a literal (such as literals of type String, int e.g., “Hi” “Hello”, 1, 2
(c
All other objects must be constructed and assigned through an explicit statement.
Notes
e
A variable whose type is a class have a reference to an object of the class (i.e., the
address of the memory location where the object is allocated).
in
Example:
String a;
nl
a = “xyz;
The first statement declares a variable a of type String. Such a variable is not
initialized yet. The second statement assigns to such a variable the reference to the
O
object denoted by “xyz”.
Notice that two variables may have a reference to the same object.
ty
Example:
String a, b;
a = “xyz”;
si
b = c;
After these two statements, both a and b contain a reference to the object denoted
by “xyz”. r
ve
Variables of type object reference may have also an unusual value, namely null.
Such value defines that the variable does not represent any object. Do not get confuse
by the fact that, variables whose value is null with variables that are not initialized. A
variable which is not initialized does not have any value, not even null.
ni
Abstraction:
Abstraction inobject-oriented programming “shows” only necessary things and
U
access on an object is limited to a set of widely available methods. While the client is
conscious of the existence of the methods, it does not know how the processes are
internally structured. In this way, information hiding enables the separation of the what
from the how of object definition.
(c
Notes
e
in
nl
O
For creating a hotel application we don’t need all the information provided by the
customer.So we only select he useful information for our hotel application from that
pool. Fields like Name, Address, Favorite food, contact number which make sense for
ty
a hotel application which is an Abstraction example in OOPs.
Since we have selected the necessary information and removed the unnecessary
information from a bigger pool, the process is referred as Abstraction in OOPs.
si
Nevertheless, the same information once extracted can be re-used for a wide
range of applications. For instance, you can use the same data for Job application,
r
hospitalportal application, a bankingdatabase, etc. with some modification. Hence, it
becomes your Master Data.
ve
ni
U
Consider a real life example of encapsulation, in a PSU there are different sections
like the accounts section, finance section, HR section etc. The finance section handles
all the financial activity and keep records of all the data related to finance. Similarly
the HR section handles all the HR related activities and keep records of all the HR
m
activity. Now there may be circumstances when for some reason an official from HR
section needs all the data about finance in a particular month. In this case, HR team
member is not allowed to directly access the data of finance section. He/she will first
)A
have to contact some other officer in the finance section and then request him to give
the particular data. This is what encapsulation is. Here the data of finance section and
the employees that can manipulate them are wrapped under a single name “finance
section”.
hides the data. In the above example the data of any of the section like HR, finance or
accounts is hidden from any other section.
In C++ encapsulation can be implemented using Class and access modifiers. Look
Notes
e
at the following example:
in
class Encapsulate {
nl
private String DemoName;
O
private int Demoage;
ty
public String getName() { return DemoName; }
si
public int getRoll() { return DemoRoll; }
DemoName = newName;
}
ni
}
U
obj.setName(“Amit”);
obj.setAge(20);
obj.setRoll(01);
(c
e
System.out.println(“Demo’s age: “ + obj.getAge());
in
}
nl
Output
O
Demo’s Age: 20
D3mo’s Roll: 01
ty
In the above program the variable a is made private. This variable can be used and
manipulated only using the functions get() and set() which are there inside the class.
Thus we can assume that, the variable a and the functions get() and set() are clubbed
together which is nothing but encapsulation.
r si
ve
ni
Inheritance
From a software reuse standpoint, generalized properties defined in superclasses
should be made available to subclasses without having to declare them explicitly in the
ity
the subclasses in a class hierarchy, and makes the properties accessible as part of the
subclasses’ definition. These properties are supposed to be inherited (or taken on) by
the subclasses. Using inheritance, the SalesPerson class of Figure below can now be
)A
Notes
e
in
nl
O
ty
Common properties in classes.
si
Using inheritance, the SalesPerson class of Figure above can now be defined by
acombination of properties from:
Class Person {
Attributes :
U
name
Methods :
}
m
)A
(c
e
The Employee class is reduced to (with inherited properties highlighted in bold in
above figure):
in
Class Employee {
nl
Attributes :
O
employee number
Methods :
ty
getEmployeeNumber(){return employee number}
si
The SalesPerson class with inherited properties simplified into (highlighted in bold
in above figure) r
ve
Class SalesPerson {
Attributes :
ni
commission
Methods :
ity
if ok
to address on date
)A
return ok}
}
(c
e
getCommission() {return commission}
in
Attributes name and employee name, and methods getName( ) and
getEmployeeNumber () of the SalesPerson class are not clearly defined in the
nl
SalesPerson class but are propagated downward from the superclasses through
inheritance.
O
allowable. There is no uphill propagation of properties in object-oriented programming.
Therefore, information specific to subclasses are inimitable to subclasses and are
not propagated to superclasses. Consequently, attribute commission and method
getCommission() of the SalesPerson class do not form part of the Employee class
ty
description.
Implementing Inheritance
si
Let us now extend the Person class hierarchy to include a new class, Recruiter.
Figure below shows the adapted class hierarchy with inherited properties highlighted
in bold. The information in the extended hierarchy suggests that all employees have
r
a basic salary except managers and salespersons, which are paid an allowance and
ve
commission, respectively.
ni
U
ity
m
)A
For example, the following code fragment suggests that Employee is an extension
Notes
e
of the Person class; Manager, SalesPerson and Recruiter, being subclasses, are
extensions of the Employee class:
in
class Employee extends Person {
...
nl
}
O
...
ty
class SalesPerson extends Employee {
...
si
}
...
r
ve
}
Code 1 is the code implementing the Person hierarchy. Code execution begins with
the Employee class because it is the only class that contains static void main( ). To
execute main( ), type the following at the command prompt line:
ni
$ java Employee
The output suggests that some information was made available from the
superclasses in deriving the manager’s and Recruiter’s salary. Objects instantiated from
the Manager or Recruiter class were able to respond to requests for their basicSalary
m
because they have inherited from the Employee class the attribute basicSalary and
method getBasicSalary().
Let us examine main(). The code begins with the instantiation of two objects, a
)A
manager and a Recruiter. The manager object is referenced by variable m while the
Recruiter object is referenced by variable s:
Notes
e
in
nl
O
State of Manager and Recruiter object.
ty
class Person {
si
Person(String aName) {name=aName;}
}
r
ve
class Employee extends Person {
float aBasicSalary) {
U
super(aName);
employeeNumber = aEmployeeNumber;
basicSalary = aBasicSalary;
ity
e
System.out.println(“ also has an allowance of “ +m.getAllowance());
in
}
nl
private float allowance;
O
float aBasicSalary, float aAllowanceAmt) {
ty
allowance = aAllowanceAmt;
si
return allowance;
}
r
ve
class Recruiter extends Employee {
float aBasicSalary) {
The remainder of main() are output statements. Some methods from various
ity
classes, invoked in producing the outputs, for example, getName() from the Person
class, and getEmployeeNumber() and getBasicSalary() from the Employee class,
are propagated through the inheritance mechanism to the subclasses, Manager and
Recruiter.
m
Code Reuse
By allowing information of a superclass to be used by subclasses, the information
is said to be reused at the subclass level. All newly created instances of the subclasses
)A
would have as part of their description the inherited information. employee number,
basic salary, and getEmployeeNumber() of the Employee class and name and
getName() of the Person class are said to be reused by the Manager and Recuiter
class.
(c
e
discussed:
in
◌◌ Change in property definition for some subclasses.
◌◌ Adding/deleting a class.
nl
1. Change in Property Definition for All Subclasses
Suppose a change in representational scheme of the employee number in Figure
(Including the Recuriter class). is required. This change will impact not only the
O
attribute employee number but also the method getEmployeeNumber() and possibly
other classes that inherit employee number.
ty
◌◌ inheritance is not available;
◌◌ inheritance is available.
Inheritance Is Not Available: In situations where inheritance is not available,
si
the attribute employee number and method getEmployeeNumber() would have to be
defined in all the relevant classes, for example, Employee, Manager, SalesPerson
and Recruiter. The change in representational scheme of employee number would
r
therefore have to be effected individually on these classes. The redundancy coming
ve
from the multiple definition of employee number and getEmployeeNumber() may lead to
inconsistency in description if the change is not carried out properly.
class and let subclasses Manager, SalesPerson and Recruiter inherit these definitions
from Employee class. The necessary change in representational scheme for attribute
employee number would be limited to the Employee class. The change would be
U
propagated to the subclasses via inheritance. In this way, the change is thus restricted
to the superclass, enabling a uniform and constant property description for all
subclasses. Besides, redundancy in property description at the subclass level can be
minimized and software maintenance enhanced.
ity
2. Change in Property:
Description for Some Subclasses In some situations, a change in property
description at the superclass level may not necessarily apply to all subclasses. The
m
above solution would therefore not apply in these situations. To illustrate, let us extend
the Person class hierarchy further to include two more employee classes: Engineer and
Clerk. Let us assume the following for a Pepperfry employee:
)A
◌◌ a clerk—basic salary.
At the Employee class, a getPay() method is defined to return the monthly pay of
an employee given that the method applies to all classes of employee. The description
Notes
e
of the Person class remains the same as before:
class Person {
in
private String name;
nl
public String getName() { return name; }
O
Employee extends Person as follows:
ty
class Employee extends Person {
si
private String employeeNumber;
float aBasicSalary) { r
ve
super(aName);
employeeNumber = aEmployeeNumber;
basicSalary = aBasicSalary;
ni
}
U
e
“ (employee number “+s.getEmployeeNumber()+”)”);
in
System.out.print(“The Engineer “+t.getName()+
nl
“ (employee number “+t.getEmployeeNumber()+”)”);
O
System.out.print(“The Clerk “+c.getName()+
ty
System.out.println(“ has a pay of “+c.getPay());
si
As before, main() is defined in the Employee class with additional code for
Engineer and Clerk class highlighted in bold. There is no change in class definition
r
for Manager and Recruiter. Engineer and Clerk extend Employee, since they are
subclasses of Employee:
ve
class Engineer extends Employee {
float aBasicSalary) {
}
U
float aBasicSalary) {
}
)A
e
The Engineer Terrence (employee number 42356T) has a pay of 2000
in
A brief examination of the output reveals a mistake in the manager’s pay: an
omission of allowance amounting to 2200. What has gone wrong?
nl
O
ty
r si
ve
Extended Employee class hierarchy.
◌◌ Remove the getPay() method from the Employee class and define it
ni
has to be repeated in all the subclasses. This is highly unproductive and can be difficult
to maintain especially in cases where the number of subclasses is large.
In the second approach, the definition of the getPay() method is maintained at the
Employee class but redefined in the Manager class. This ensures that the getPay()
m
Notes
e
in
nl
O
ty
Redefining getPay() method of Manager.
The getPay() method of the Manager class is said to redefine the getPay() method
of the Employee class. Note that a redefined method has the same method name and
si
parameter definition of a redefining method. While a redefining method has the same
method signature with the redefined method, the execution of the methods may differ.
In this situation, the getPay() method of the Manager class includes an additional
r
calculation of the allowance component.
ve
Code 2: Redefining the getPay() method.
class Person {
...
ni
...
...
}
m
allowance = aAllowanceAmt;
}
Notes
e
public float getAllowance() {
return allowance;
in
}
nl
return (basicSalary + allowance);
O
}
ty
...
si
...
}
ni
Judging from the outcome of the two solutions, both approaches are correct:
However, the second approach is better than the first approach as it enhances
software reuse and reduces the effect of change on other classes.
3. Adding/Deleting a Class
m
Adding a class into an existing class hierarchy can be unfavorable to the stability
of the hierarchy. It is always suggested that the addition of a new class be created as a
subclass in the class hierarchy. The description of existing classes will not be adversely
)A
The attribute name and method getName() are defined as properties of Shape.
Circle and Traiangle, being subclasses of Shape, inherit these properties (highlighted in
Amity Directorate of Distance & Online Education
32 Object Oriented Programming Using Java
e
in
nl
O
Class hierarchy of Shape, Circle and Traiangle
ty
class Shape {
si
Shape(String aName) {name=aName;}
r
public float calculateArea() {return 0.0f;}
ve
public static void main(String argv[]) {
}
ity
The attribute name is declared as private in the Shape class. To make it known to
m
other objects, a getName() method is defined in the Shape class to return the value of
attribute name.
Circle and Traiangle extend Shape and have the following description:
)A
Circle(String aName) {
(c
super(aName);
radius = 3;
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 33
}
Notes
e
public float calculateArea() {
float area;
in
area = (float) (3.14 * radius * radius);
return area;
nl
}
O
class Traiangle extends Shape {
ty
Traiangle(String aName) {
super(aName);
side = 3;
si
height = 5;
return area;
}
U
As usual, program execution begins with main() and the following output is
produced when main() is executed:
ity
Two objects are created in main()—a Circle object referenced by the variable c and
a Traiangle object referenced by the variable s. The creation of a Circle object involves
m
a call to the Circle class constructor method via the new keyword. A name parameter
is required to activate the Circle constructor method. For Circle, the name parameter is
the string “Circle C”.
)A
A call is made to the Circle’s superclass constructor method via the statement:
super(aName);
The call assigns the value of the parameter (“Circle C”) to the Circle object’s
(c
attribute name. When the assignment is done, control returns to the Circle class’s
constructor method. Subsequently, the radius attribute of the Circle object is assigned
the value 3 via the statement:
radius = 3;
Notes
e
Likewise, the Traiangle object is created and its attributes updated in the execution.
By now, the Circle and Traiangle objects have a state as illustrated in Figure below.
in
nl
O
ty
State of Circle and Traiangle object.
si
and s are assigned to the array elements. Iterating through the array (via the forloop),
the area of the respective shape is produced by the statement
class Shape {
...
U
}
(c
...
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 35
}
Notes
e
class Traingle extends Shape {
...
in
}
nl
private int side;
Square(String aName) {
O
super(aName);
side = 4;
ty
}
si
return area;
}
r
ve
To add the new Square class, the following is involved:
2. Add a statement to include the newly created square into shapeArray in main().
3. Create a new square class as a subclass of Shape.
It is clear that subclassing the new Square class into the class hierarchy does not
U
affect the description of the other three classes. Subclassing is specialization and is
thus a desired design practice in object-oriented software engineering because it has
less impact on software maintenance.
ity
Thus, the deletion of subclasses that are not superclasses to other classes has a
less impact on software maintenance.
Polymorphism
m
The word polymorphism means having many forms. In simple words, we can
describe polymorphism as the capability of a message to be displayed in more than one
form.
)A
Real life example of polymorphism: A person at the same time can have different
characteristic. Like a woman at the same time is a mother, a wife, an employee.
So the same person posses different behavior in diverse situations. This is called
polymorphism.
(c
Notes
e
in
Types of Polymorphism in Oops
nl
In Object-Oriented Programming (OOPS) language, there are two types of
polymorphism as below:
O
◌◌ Static Binding (or Compile time) Polymorphism, e.g., Method Overloading
◌◌ Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding
ty
r si
ve
ni
◌◌ As all of this information is out there during the compile time, the compiler
selects the acceptable function.
)A
Program
class A // base class
(c
int a;
Notes
e
public:
void display()
in
{
cout<< “Class A “;
nl
}
};
O
class B: public A // derived class
ty
{
int b;
public:
si
void display()
cout<<“Class B”;
r
ve
}
};
ni
Polymorphism. during this process, the overriding is completed through pointers and
virtual functions.
ity
Program
)A
class ABC
(c
void m1()
{
Notes
e
System.out.println(“Inside ABC’s m1 method”);
in
}
nl
class XYZ extends ABC
O
// overriding m1()
void m1()
ty
{
si
}
// overriding m1()
ni
void m1()
{
U
}
ity
// Driver class
class Dispatch
m
e
// object of type MNO
in
MNO c = new MNO();
nl
ABCref;
O
ref = a;
ref.m1();
ty
ref = b;
si
ref.m1();
ref.m1();
U
}
ity
◌◌ In the Run time polymorphism, the object’s method is invoked at the run time
rather than compile time.
◌◌ It is formed possible by method overriding, which is additionally coined as
)A
e
Invoking of The function is invoked at the run The function is invoked at the
Function time compile time.
in
Common It is known as overloading, early It is known as overriding, late
Terms binding, and static binding. binding, and dynamic binding.
Method In Overloading, more than one method In overriding, ore than
nl
Name and has the same name but with a different one method has the same
Parameters number or type of parameters. name, number, and type of
parameters.
O
Carriers It is achieved with function and It is achieved with virtual
operator overloading. functions and pointers.
Execution It executes faster than run-time It executes slower than
Time polymorphism at the compile time. compile-time polymorphism at
ty
the run time.
Flexibility It is less flexible as everthing executes It is more flexible as everthing
at the compile time. executes at the run time.
si
Check your Understanding
1. There are two basic aspects of programming _______________ and __________.
2. r
Object oriented programming is a programming model which is based on the concept
ve
of _________________ .
3. An object contains an address and takes up some space in ______________ .
4. Generalization is the act of capturing ____________ between ___________ and
defining the similarities in a new generalized class.
ni
the ___________________ .
7. A class is a user defined design or sample from which _____________ are created.
8. Variables did not contain objects, but only the _____________________ to objects.
ity
Summary
●● An overview of object-oriented programming concepts and their applicability for
m
modeling and representing real-world entities and their interactions in the problem-
solving process.
●● Object-oriented concepts of object, message, and method.
)A
●● Objects from the same class share the same definition of attributes and methods.
●● Objects from the same class may not have the same attribute values.
●● Objects from different classes do not share the same definition of attributes or
Notes
e
methods.
●● Objects created from the same class share the same definition of attributes and
in
methods but their state may differ.
●● This variable can be used and manipulated only using the functions get() and set()
which are there inside the class
nl
●● Polymorphism in Java is the ability of an object to take many forms. To simply put,
olymorphism in java allows us to perform the same action in many different ways.
O
Activity
1. Create a program for online hotel reservation using inheritance.
ty
1. Define Fundamentals of object oriented programming?
2. What is difference between Procedure Oriented Programming Vs. Object Oriented
si
Programming (OOP)?
3. What is Classes?
4. What is Object?
5. Define object reference?
r
ve
6. Define Abstraction?
7. What do you mean by Encapsulation?
8. Define Inheritance?
ni
Glossary
U
●● Object: An object can be defined as a data field that has unique attributes and
behavior.
●● Object Refrence: A link to an object. Object references can be used exactly like the
linked objects. The concept of object references becomes clear when assigning
m
“shows” only essential attributes and “hides” unnecessary information. The main
purpose of abstraction is hiding the unnecessary details from the users.
●● Encapsulation: Encapsulation is a method of making a complex system easier
to handle for end users. The user need not worry about internal details and
complexities of the system. Encapsulation is a process of wrapping the data and
(c
the code, that operate on the data into a single entity. You can assume it as a
protective wrapper that stops random access of code defined outside that wrapper.
e
another class is called Inheritance.
●● OOP: Object Oriented Programming
in
Further Readings:
1. Object Oriented Programming, Dusty Phillips
nl
2. Object-oriented Software Construction, Bertrand Meyer
3. Object-oriented programming with C++, Raimund K. Ege
O
4. The Object-Oriented Thought Process, Matt A. Weisfeld
ty
1. data and instructions
2. objects
si
3. memory
4. Similarities classes
5. Primitive
r
ve
6. Hierarchy
7. Objects
8. references
ni
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
●● Difference between Java and C++, and a brief history about Java
nl
●● Tools used for Java application: JDK, JRE, JVM
●● Use of IDE for developing Java Application
O
●● Types of variables and declaration
●● Data types and function used in Java application
Introduction
ty
Java languagewas developed by James Gosling at Sun Microsystems in 1991,
later acquired by Oracle Corporation. It’s an easy programming language. Java helps
in writing codes and also makes compiling, and debugging programming easy. It helps
si
programmer to make reusable code and modular programs.
After the name OAK, the team decided to offer a replacement name there to and
ni
therefore the suggested words were Silk, Jolt, revolutionary, DNA, dynamic, etc. These
all names were easy to spell and fun to mention , but all of them wanted the name
to reflect the essence of technology. As per with James Gosling, Java the among the
U
highest names alongside Silk, and since java was a singular name so most of them
preferred it.
Java is that the name of an island in Indonesia where the primary coffee(named
java coffee) was produced. And this name was selected by James Gosling
ity
whilehehaving coffee in his office. Note that Java is simply a reputation, not an
acronym.
importjava.io.*;
)A
// Main class
publicclassGFG {
publicstaticvoidmain(String[] args)
(c
// Print statement
Notes
e
System.out.println(“Welcome to the world of Java”);
in
}
Output
nl
Welcome to the world of Java
O
ty
1.2.1 History of Java, Java v/s C++.
si
Java was first introduced in 1995 as an easy and secure object-oriented
programming language. It’s a singular language therein, being a replacement language
at that point; it had been ready to attract tons of interest from the computing community.
r
Within two years after Java was launched, there have been an estimated 400,000 Java
programmers and over 100 books on Java programming.
ve
There are a couple of possible reasons for the exceptional interest in Java. The
year 1995 saw a maturing of Web technologies, and Java’s multiplatform capability,
which enabled a Java program to execute on any computer, was exceedingly attractive,
ni
especially on an open network just like the Internet. Java is implemented via part
compilation and subsequent execution on an interpreter implemented in software.
Java applications are therefore code portable as long as a Java virtual machine is
U
The popularity of Java is additionally ironically thanks to its similarity with its close
rival C++. Java takes the pain out of learning a replacement language by reusing much
of C and C++. At an equivalent time, safe programming practice in Java and language
ity
facilities for automatic memory management were benefits that were attractive to
programmers on the verge of deserting their C/C++ camps. In reference to the web,
Java applets have given rise to a replacement generation of distributed applications
with low software distribution and maintenance costs. As applets are embedded in
m
an HTML document via <APPLET> tags, its transmission to the client machine for
execution is implicitly handled by the underlying network protocols and thus makes the
standard channels of distribution and installation obsolete.
)A
e
Comparison Index C++ Java
Platform- C++ is platform- Java is platform-independent.
in
independent dependent.
Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used
nl
in Windows-based, web-based,
enterprise, and mobile applications.
Design Goal C++ was designed Java was designed and created
O
for systems and as an interpreter for printing
applications systems but later extended as a
programming. It support network computing. It was
was an extension of designed to be easy to use and
ty
the C programming accessible to a broader audience.
language.
Multiple inheritance C++ supports multiple Java doesn't support multiple
si
inheritance. inheritance through class. It can
be achieved by using interfaces in
java.
Operator
Overloading
C++ supports operator
overloading.
r
Java doesn't support operator
overloading.
ve
Compiler and C++ uses compiler Java uses both compiler and
Interpreter only. C++ is compiled interpreter. Java source code
and run using the is converted into bytecode at
compiler which compilation time. The interpreter
ni
dependent. independent.
Call by Value and C++ supports both call Java supports call by value only.
Call by reference by value and call by There is no call by reference in
reference. java.
ity
Structure and Union C++ supports Java doesn't support structures and
structures and unions. unions.
Thread Support C++ doesn't have built- Java has built-in thread support.
in support for threads.
m
It relies on third-party
libraries for thread
support.
)A
unsigned right shift C++ doesn't support Java supports unsigned right shift
Notes
e
>>> >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
in
positive numbers, it works same
like>> operator.
Virtual Keyword C++ supports virtual Java has no virtual keyword. We
nl
keyword so that we can override all non-static methods
can decide whether by default. In other words, non-
or not to override a static methods are virtual by
function. default.
O
Object-oriented C++ is an object- Java is also an object-oriented
oriented language. language. However, everything
However, in the C (except fundamental types) is
ty
language, a single an object in Java. It is a single
root hierarchy is not root hierarchy as everything gets
possible. derived from java.lang.Object.
Inheritance Tree C++ always creates a Java always uses a single
si
new inheritance tree. inheritance tree because all classes
are the child of the Object class in
Java. The Object class is the root
r of the inheritance tree in java.
ve
Hardware C++ is nearer to Java is not so interactive with
hardware. hardware.
Goto C++ supports the goto Java doesn't support the goto
statement. statement.
ni
programs. One can install more than one JDK version on the same computer.”
●● JDK contains necessary tools to write Java programs, and JRE to execute them.
●● It contains a compiler, Java application launcher, Appletviewer, etc.
●● Compiler turn the code written in Java into byte code.
(c
●● Java application launcher opens a JRE, loads the essential class, and executes its
main process.
Notes
e
in
nl
O
ty
r
JDK Functionality
si
ve
Important component of JDK
●● JDK and JRE: The JDK enables programmers to generate core Java programs
that can be run by the JRE, which consist of JVM and class libraries.
ni
●● Compilers: It is a Java program which accepts text file of developers and compiles
into Java class file. It is the widespread form of productivity given by compiler,
which contains Java byte code. In Java, the primary compiler is JavaC.
●● Debuggers: Debugger is a Java program that helps programmers to test and
ity
In other programming languages, the compiler creates machine code for a specific
(c
system. However, in Java language compiler produces code for a virtual machine which
is called as JVM.
e
●● JVM gives a platform-independent way of executing Java source code.
●● It has abundant of libraries, tools, and frameworks.
in
●● Once you run Java program, you can execute on any platform and save lots of
time.
nl
●● JVM comes with in-built JIT(Just-in-Time) compiler that converts Java source
code into low-level machine language. Hence, it executes faster as a regular
application.
O
ty
r si
ve
ni
U
JVM Functionality
ity
2. Method Area: Java Virtual Machine Method Area stores structure of class similar to
metadata, the code for Java methods, and the constant runtime pool.
3. Heap: All the Arrays, Objects and instance variables are saved in a heap. Heap is
)A
5. PC Registers: PC registers store the location of the Java virtual machine instruction,
Notes
e
which is currently executing. In Java, each thread has its own PC register.
6. Native Method Stacks: Native method stacks hold the information of native code
in
based on the native library. It provides memory on native heaps or uses any type of
stack.
7. Execution Engine: It is used to test software, hardware, or complete systems. The
nl
test execution engine not at all carries any information about the tested product.
8. Native Method interface: The Native Method Interface is a programming structure.
It allows Java code, which is compelling in a JVM to call by libraries and native
O
applications.
9. Native Method Libraries: Native Libraries is a compilation of the Native Libraries (C,
C++), which are required by the Execution Engine.
ty
Java Runtime Environment (JRE)
JRE is a piece of a software which is planned to run other software. It holds the
class libraries, loader class, and JVM. In simple terms, if you want to execute a Java
si
program you need JRE. If you are not a developer, you don’t need to install JDK, but
just JRE to run Java programs. Even if, all JDK versions bundled with Java Runtime
Environment, so you do not need to download and install the JRE separately in your
computer. r
ve
Reasons of using JRE:
●● JRE contains pre-defined class libraries, JVM, and other supporting files. It does
not include any tool for Java development like a debugger, compiler, etc.
ni
●● It uses significant package classes likeswingetc, util, lang, awt, and runtime
libraries.
U
●● If you want to execute Java applets, then JRE must be installed in your system.
ity
m
Functionality of JRE
)A
(c
Notes
e
in
nl
O
ty
Components of JRE r si
ve
●● Class loaders: The class loader loads various classes that are obligatory for
running a Java program. JVM uses three class loaders defined as bootstrap class
loader, extensions class loader, and system class loader.
●● Byte code verifier: Byte code verifier checks the bytecode so that the code doesn’t
ni
platform.
many also provide functionality for other languages,IDEs typically provide a, a compiler
or interpreter, editor and a debugger that the developer accesses through a combined
graphical user interface (GUI). Java IDEs comprises of language-specific component
)A
such as Maven and Ant build tools and TestNG and JUnit testing.
(c
Notes
e
in
nl
O
Best Online Java Programming IDEs & Compilers: There are many IDE available in
markets we have discuss 5 major IDE’s
1. Eclipse: Eclipse is an IDE for writing and compiling Java programs. It highlights the
syntax you have written. This tool enables you to easily debug the program.
ty
si
Features of Eclipse:
r
ve
ni
2. BlueJ: BlueJ is a free Java IDE for beginners. It is one of the best editors for Java
U
which enables a developer to scan code visually much faster. The tool offers many
extensions to expand its functionality.
ity
Features of BlueJ:
m
)A
e
in
nl
O
4. Kite: Kite is IDE for Java that routinely completes multiple line codes. This editor
accepts more than 16 languages. It helps you to code quickly with no problem.
ty
Features of Kite:
r si
ve
5. Apache NetBeans: Apache NetBeans is an integrated development environment for
ni
writing and compiling Java programs. It has a project window that shows a list of all
projects at present exists.
U
Features of NetBeans:
ity
m
)A
◌◌ jGRASP
◌◌ Codota
◌◌ Codenvy
Notes
e
◌◌ Slickedit
◌◌ JBoss Forge
in
◌◌ JDeveloper
◌◌ JEdit
nl
1.2.4 Constructs used in JAVA :Variables, types and type
declarations
The variable is the necessary unit of storage in a Java program. A variable is
O
defined by the combination of an identifier, a type, and an initializer. In addition, all
variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
ty
In Java, all variables must be defined upfront so that they can be used later. A
variable declaration is shown here:
si
data type identifier [ = value];
r
Type is the data type Int in above example. The identifier Age is the name of the
variable. You can initialize the variable by specifying an equal sign and a value 20 as
ve
declared in above statement. We need to make sure that the initialization expression
must result in a value of the compatible or same type as that specified for the variable.
To declare more than one variable of the particular type, use a comma to separate them.
ni
// m and o.
1. Local Variables
m
2. Instance Variables
3. Static Variables
)A
1. Local Variables:A local variable is a variable defined inside a method body, block
or constructor. It means variable is only accessible within the method, block or
constructor that declared it.
Example of Local variable:
(c
int area()
e
int breadth = 5; //local variable
in
return Rarea;
nl
O
ty
si
Program Example of Local Variable
public class Ravi
r
ve
{
age = age + 6;
}
ity
d.AgeSet();
m
}
)A
Output
Ravi age is : 6
Here, age is a local variable. This variable is defined under AgeSet() method and
its scope is limited to this method only:
(c
2. Instance Variable: Instance variables are non-static variables and are defined in a
class outside any method, constructor or block.
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 55
Notes
e
in
nl
O
Program for explainingInstance Variable
public class Record{
ty
public String address;// this instance variable is visible for any child class.
private int phonenumber;// this instance age variable is visible in Record class
si
only.
{ r
ve
address = Recadre;
phonenumber = RecSal;
U
{
ity
r.setphonenumber(123456);
(c
r.printRec();
}
Notes
e
Output:
in
phonenumber :123456
nl
type and can be accessed by any child class because it is public and the second is
Phonenumber variable of integer type and can be accessed in the same class record
because it is private.
O
3. Static variables:These variables also known as Class variables. These variables
are defined similarly as instance variable; the difference is that static variables are
ty
defined using the static keyword inside a class outside any method constructor or
block.
The below program has a class Patient in which we use static variable Hospital.
si
This variable is common to all Patients so we make it static. The Patient information will
be displayed with different Patient no and names but same Hospital. The advantage to
make Hospital variable static is that it save memory as it loads once in a class area at
class loading time: r
ve
class Patient
int rollno;
ni
String name;
Patient(int r,String n)
ity
Patientno= r;
name = n;
m
void display()
)A
e
{
in
Patient s2 = new Patient(102,”Ram”);
nl
s2.display(); // call the display function using the s2 object
O
}
Output:
ty
101 Ravi GGGI
r si
ve
ni
U
ity
Indeed, part of Java’s safety and robustness comes from this fact.
◌◌ Every variable features a type, every expression features a type, and each
type is strictly defined.
)A
1. Integers: This group includes byte, short, int, and long, those are for whole-valued
signed numbers.
2. Floating-point numbers: This group has float and double, which symbolize numbers
Notes
e
with fractional precision.
3. Characters: This group includes char, which symbolize symbols in a character set,
in
like letters and numbers.
4. Boolean:This group has boolean, which is a special type on behalf of true/false
values.
nl
The primitive types represent single values—not complex objects. Although Java
isotherwise completely object-oriented, the primitive types aren’t. They’re analogous
tothe simple types found in most other non–object-oriented languages. The rationale
O
for this is oftenefficiency. Making the primitive types into objects would have degraded
performance an excessive amount of.
Integers:
ty
Java consists of four integer types: byte, short, int, and long. Every one of those
is signed, positive and negative values. Java doesn’t support unsigned, positive-only
integers. There are other computer languages support both signed and unsigned
si
integers. On the other hand, Java’s developer felt that unsigned integers were
unnecessary. Purposely, they felt that the perception of unsigned was used mostly to
identify the behavior of the high-order bit, which shows the sign of an integer value.
r
The width of an integer type shouldn’t be consideration of because the amount
ve
of storage it consumes,but rather because the behavior it defines for variables and
expressions of that type. The Java run-timeenvironment is liberal to use whatever sizes
it wants, as long because the types behave as you declaredthem. The width and ranges
of those integer types vary widely, as shown during this table:
ni
e
class Light {
in
int l;
long d;
nl
long s;
long d;
O
// speed of light in miles per secondapproximately
l = 186000;
ty
d = 1000; // specify number of days here
d = l * s; // compute distance
si
System.out.print(“In “ + days);
System.out.println(distance + “ miles.”);
r
ve
}
}
ni
Clearly, the output cannot have been held in an int variable so we need an other
variable to hold this value.
Floating-Point Types
ity
As we see in previous example that large value cannot be hold be in integer types
for this we required another data type called Floating point number.
such as cube root, or transcendental such as sine cosine, tan result in a value whose
accuracy needs a floating-point type.
◌◌ float
◌◌ double
Name Width In Bits Approximate Range
(c
Notes
e
in
nl
O
// Compute the area of a triangle.
class Area {
ty
public static void main(String args[]) {
double b, h ;
si
b = 2.5; // base of triangle
}
ni
Characters
In Java, the data type is being used to store characters is char. Java uses Unicode
U
to represent characters. Unicode defines a totally international list which will represent
all of the characters found altogether human languages.
It’s a unification of many character sets, like Greek, Arabic, Hebrew, Katakana,
ity
Hangul, and lots of other sets of character. For this purpose, it requires 16 bits. Thus,
in Java char may be a 16-bit type. Thecharrange is 0 to 65,536. There are not any
negative chars. the quality set of characters referred to as ASCII still ranges from 0 to
127 as always, and therefore the extended 8-bit list , ISO-Latin-1, ranges from 0 to 255.
m
class DemoChar {
ca2 = ‘B’;
e
System.out.println(ca1 + “ “ + ca2);
in
}
nl
Output:
ca1 and ca2: AB
In above program you notice that ca1 is assigned the value 15, which is the ASCII
O
(and Unicode) value that corresponds to the letter A. As described, the ASCII character
set occupies the first 127 values in the Unicode character set.
ty
class DemoChar2 {
si
char cha;
ca1 = ‘A’;
}
ni
Output
U
ca1 contains A
ca1 is now B
ity
In the program, ca1 is first given the value X. Next, ca1 is incremented. This results
in ca1 containing B, the next character in the ASCII (and Unicode) sequence.
Booleans
Booleans used for logical values. It can have only had two possible values, either
m
true or false. This is the type returned by all relational operators, as in the case of x <
y. Boolean is also the kind required by the conditional expressions that administer the
control statements such as if and for.
)A
class BoolTest {
(c
booleana;
a = false;
Notes
e
System.out.println(“a is “ + a);
a = true;
in
System.out.println(“a is “ + a);
nl
if(b) System.out.println(“This is executed.”);
b = false;
O
if(b) System.out.println(“This is not executed.”);
ty
System.out.println(“21 > 19 is “ + (21>19));
si
Output
a is false
r
ve
a is true
This is executed.
21>19 is true
ni
______________ .
2. ______________ is an engine that provides a runtime environment to run the Java
Code or applications.
ity
Summary
●● Java language was developed by James Gosling at Sun Microsystems in 1991,
later acquired by Oracle Corporation. It’s an easy programming language. Java
)A
helps in writing codes and also makes compiling, and debugging programming
easy. It helps programmer to make reusable code and modular programs.
●● JDK is a software development environment which is used for creating applets and
Java applications. Java developers can use it on different operating systems like
Windows, macOS, Solaris, and Linux.
(c
●● JDK and JRE: The JDK enables programmers to generate core Java programs
Notes
e
that can be run by the JRE, which consist of JVM and class libraries.
●● Class Libraries: It is a cluster of dynamically loadable libraries that Java program
in
can call at run time.
●● Compilers: It is a Java program which accepts text file of developers and compiles
into Java class file. It is the widespread form of productivity given by compiler,
nl
which contains Java byte code. In Java, the primary compiler is JavaC.
●● Debuggers: Debugger is a Java program that helps programmers to test and
debug Java programs.
O
●● Java Doc: Java Doc is documentation created by Sun Microsystems for the Java.
JavaDoc can be used for creating API documentation in HTML file from the main
program.
ty
●● The variable is the necessary unit of storage in a Java program. A variable is
defined by the combination of an identifier, a type, and an initializer. In addition, all
variables have a scope, which defines their visibility, and a lifetime.
si
Activity
1. Create a program to distribute student in a class based on their percentage using
nested if? r
ve
Questions and exercises
1. What is the difference between java and C++?
2. Define various tools for java application? JDK and JVM
ni
Glossary
ity
Further Readings:
1. Programmer’s Guide to Java SE 8 Oracle Certified Associate (OCA), Mughal/
(c
Rasmussen
2. Deploy, Manage and Update Java Runtime Environment in the Enterprise with
Notes
e
System Center Configuration, Trevor Jones
3. Java Fundamentals, Herbert Schildt (Author), Dale Skrien (Author)
in
4. Programming in Java, Sachin Malhotra, Saurabh Choudhary
nl
Answers
1. James Gosling, 1991
O
2. JVM
3. Static variable
4. Boolean
ty
5. char
r si
ve
ni
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● What are Relational and Logical operators
●● When we can use Conditional Expressions, if then else clause
O
●● Input using scanner class and output statement
●● What is Loops and Switch case
●● What are Arrays and Methods
ty
Introduction
Statements are similar to sentences in the English language. A sentence forms a
si
complete idea which can include one or more clauses. Likewise, a statement in Java
forms a complete command to be executed and can include one or more expressions.
In simpler terms, a Java statement is just an instruction that explains what should
happen. r
ve
Types of Java Statements
Java supports three different types of statements:
ni
a = 42;
b = ++a;
(c
In this case, b is set to 43 as you would expect, because the increment occurs
before a is assigned
e
a= a + 1;
b = a;
in
However, when written like this,
a = 42;
nl
b = x++;
The value of a is obtained before the increment operator is executed, so the value
O
of b is 42.
Of course, in both cases a is set to 43. Here, the line b = a++; is the equivalent of
these two
ty
statements:
b =a;
si
a = a + 1;
r
// Demonstrate ++ Operator.
ve
class IncDec {
int x = 5;
ni
int y = 7;
int z;
U
int u;
z = ++y;
u = x++;
ity
z++;
System.out.println(“x = “ + x);
System.out.println(“y = “ + y);
m
System.out.println(“u = “ + z);
System.out.println(“z = “ + u);
)A
Output:
(c
x=6
y=8
z=9
Notes
e
u=5
in
to decrement the value of a variable in an expression. In the Pre-Decrement, value
is decremented first and then used inside the expression. Whereas in the Post-
Decrement, value is first used inside the expression and then it’s get decremented.
nl
Decrement operator can be repressed as
O
a=a-1;
// Demonstrate -- Operator.
ty
class IncDec {
int x = 5;
si
int y = 7;
int z;
int u;
r
ve
z = --y;
u = x--;
ni
z --;
System.out.println(“x = “ + x);
System.out.println(“y = “ + y);
U
System.out.println(“u = “ + z);
System.out.println(“z = “ + u);
ity
Output:
m
x=4
y=7
)A
z=6
u=5
(c
e
Increment Operators Decrement Operators
Increment Operator adds 1 to the Decrement Operator substrats 1 from the
in
operand. operand.
Postfix increment operator means the Postfix decrement operator means the
expression is evaluated first using the expression is evaluated first using the
nl
original value of the variable and then the original value of the variable and then the
variable is incremented (increased) variable is decremented (decreased)
Prefix increment operator means the Prefix decrement operator means the
O
variable is incremented first and then the variable is decremented first and then
expression is evaluated using the new the expression is evaluted using the new
value of the variable. value of the variable.
Generally, we use this in decision making This is also used in decision making and
ty
and looping. looping.
si
Relational Operator: The relational operators determine the relationship that one
variable has with the other variable. Explicitly, they establish equality and ordering.
The outcome of using any of these operators is a boolean value. These relational
operators are often used in the expressions that control the if statement and the various
loop statements.
ity
int x = 10;
int y = 20;
)A
System.out.println(“x == y = “ + (x == y) );
System.out.println(“x != y = “ + (x != y) );
System.out.println(“y>= x = “ + (y>= x) );
System.out.println(“y<= x = “ + (y<= x) );
Notes
e
}
in
Output:
x == y = false
nl
x != y = true
x > y = false
O
x < y = true
y>= x = true
ty
y<= x = false
Boolean Logical Operators: The Boolean logical operators shown here operate
only on boolean values. All of the binary logical operators combine two boolean values
si
to form a resulting boolean value.
Operator Result
&
I
Logical AND
Logical OR
r
ve
^ Logical XOR (exclusive OR)
II Short-circuit OR
&& Short-circuit AND
ni
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
ity
The logical Boolean operators, &, |, and ^, operate on boolean values in the
same way that they operate on the bits of an integer. The logical ! operator inverts the
Boolean state: !true == false and !false == true. The following table shows the effect of
each logical operation:
m
class BoolLogic {
boolean x = true;
Notes
e
boolean y = false;
boolean z = a | b;
in
boolean s = a &b;
boolean t = a ^ b;
nl
boolean u = (!a& b) | (a & !b);
boolean v= !a;
O
System.out.println(“ x = “ + x);
System.out.println(“ y = “ + y);
ty
System.out.println(“ x|y = “ + z);
si
System.out.println(“!x&y|x&!y = “ + u);
System.out.println(“ !x = “ + v);
}
r
ve
}
Output
ni
x = true
y = false
U
x|y = true
x&y = false
x^y = true
ity
x&y|x&!y = true
!x = false
m
If Statement:
The if statement is Java’s conditional branch declaration. It can be used to set
the course of program execution through two different paths. General form of the if
(c
statement:
Notes
e
in
The Java if statement is the simplest decision-making statement. It is used to
decide whether a certain statement will be executed or not that is if a certain condition
is true then a statement is executed otherwise not.
nl
Flow of information in if statement:
O
ty
r si
ve
ni
Example of if:
class IfDemo {
U
int a = 10;
ity
if (a< 15)
System.out.println(“Outside if-block”);
)A
Output
(c
10 is less than 15
Outside if-block
Amity Directorate of Distance & Online Education
72 Object Oriented Programming Using Java
e
Nested ifs are very general in programming. When you nest ifs, the main thing to
remember is that an else statement at all times targeted to the nearest if statement that
is within the same block as the else and that is not associated with an else.
in
if(y == 10) {
nl
if(z > 100) n = o; // this if is
O
}
ty
As the comments indicate, the final else is not associated with if(x<20) because
it is notin the same block (even though it is the nearest if without an else). Rather, the
final elseis associated with if(y==10). The inner else refers to if(z>100) because it is the
closest ifwithin the same block.
si
The if-else-if Ladder: A frequent programming construct that is based on a
sequence of nested ifs is the if-else-if ladder. It syntax look like this:
if(condition) r
ve
statement;
else if(condition)
statement;
ni
else if(condition)
statement;
U
.
ity
else
statement;
m
The if statements are run from the top to down. If any one of the conditions
controlling the if is right or true, the statement attached to with that if is executed, and
the remaining of the ladder is bypassed. If not a single conditions is true, then the last
else statement will be executed.
)A
class IfElse {
String season;
Notes
e
if(month == 12 || month == 1 || month == 2)
season = “Winter”;
in
else if(month == 3 || month == 4 || month == 5)
season = “Spring”;
nl
else if(month == 6 || month == 7 || month == 8)
season = “Summer”;
O
else if(month == 9 || month == 10 || month == 11)
season = “Autumn”;
ty
else
si
}
}
r
ve
Output
October is in the Autumn.
If month value is 13 then we get the last else statement i.e Bogus Month
ni
primitive types like float, double, etc. and strings from the user. It is the easiest way to
accept input from a user in a Java program; it is not a very efficient way if developers want
an input method for scenarios where time is a constraint like in competitive programming.
ity
m
)A
import java.util.Scanner;
(c
e
{
in
Scanner sc = new Scanner(System.in);
// String input
nl
String name = sc.nextLine();
// Character input
O
char gender = sc.next().charAt(0);
ty
long mobileNo = sc.nextLong();
si
System.out.println(“Name: “+name);
System.out.println(“Gender: “+gender);
r
System.out.println(“Age: “+age);
ve
System.out.println(“Mobile Number: “+mobileNo);
System.out.println(“Percentage: “+percentage);
ni
}
U
M
ity
31
1234567890
78
m
Name: Rituj
)A
Gender: M
Age: 31
Percentage: 78
Sometimes, we have to see if the next value we scan is of a certain type or if the
e
Then, we check if the scanner’s input is of the type we want with the help of has
NextABC() functions where ABC is the type we are concerned with. The function
in
returns true if the scanner has a symbol of that type, otherwise false. For example, in
the below code, we have used has NextFloat(). To check if string is avilable, we use
hasNextLine(). likewise, to check if a single character is avilable, we use has Next().
nl
charAt(0).
Let us look at the code to take input some numbers from console and print their
average.
O
import java.util.Scanner;
ty
{
si
Scanner sc = new Scanner(System.in);
{
ni
addition += num;
count++;
U
System.out.println(“Avaerage: “ + average);
}
m
18
16
25
(c
25.6
18.9
22.5
Notes
e
Output
in
Average: 20.142857142
nl
Switch Case: The switch statement is Java’s multiway branch statement. It gives a
simplest way to dispatch execution to different parts of the developer code based on the
value of an expression. As such, it regularly provides a better option than a large series
O
of if-else-if statements. Syntax for the switch statement:
switch (expression) {
case value1:
ty
break;
case value2:
si
break;
. r
ve
.
case valueN:
break;
ni
default:
}
U
The expression must be a data type like float, double, int: each of the values given
in the case statements must be of a type compatible with the statement.
The switch statement perform like this: The value of the expression is checked
ity
with each of the literal values in the case statements. If the case statement true, the
code following that case is executed. If none of the cases matches the value of the
statement, then the default statement is executed.
class SampleSwitch {
m
switch(a) {
case 0:
System.out.println(“a is zero.”);
(c
break;
case 1:
System.out.println(“a is one.”);
Notes
e
break;
case 2:
in
System.out.println(“a is two.”);
break;
nl
case 3:
System.out.println(“a is three.”);
O
break;
default:
ty
System.out.println(“a is greater than 3.”);
si
}
Output
r
ve
a is zero.
a is one.
a is two.
ni
a is three.
a is greater than 3.
U
As you can see in above program, each time through the loop, the statements
associated with the case constant that matches a are executed. All others are
bypassed. After a is greater than 3, no case statements match, so the default statement
is executed.
ity
◌◌ while
◌◌ do-while
m
◌◌ for
1. while loop: The while loop is Java’s most basic loop declaration. It repeats a statement
or block till its controlling statement is true.
)A
(c
Notes
e
in
nl
O
Flow Chart for while loop
ty
r si
ve
Java program to see how while loop works:
class whileLoopDemo {
int a = 1;
U
while (a< 6) {
System.out.println(“Hello Java”);
a++;
ity
}
m
Output is:
)A
Hello Java
Hello Java
Hello Java
Hello Java
(c
Hello Java
e
then the body of the loop will not be executed at all. However, sometimes developers
want to execute the body of a loop at least once, even if the conditional expression
is false at the starting. There are times when a developer wants to like to test the
in
termination expression at the end of the loop rather than at the starting. Luckily, Java
supplies a loop that does just that what a developer wants: the do-while. The do-
while loop always executes its body at least once, because its conditional expression
nl
is at the end of the loop.
O
ty
Flow of a do while loop r si
ve
ni
U
class dowhileloopDemo {
ity
int a = 7;
m
do {
System.out.println(“Hello Java”);
)A
// update expression
a++;
}
(c
}
Notes
e
}
in
Output
Hello Java
Here we see the first condition was false but the statement is printed once because
nl
the condition statement at the end.
O
3. For loop: Java provides a short way of writing the loop structure. The for statement
contains the initialization, condition statement and increment/decrement operator in
one line thus providing a shorter and simplest way to debug structure of looping.
ty
r si
ve
ni
class forLoopDemo {
int sum = 0;
(c
sum = sum + a;
}
Notes
e
System.out.println(“Sum: “ + sum);
in
}
nl
Output
Sum: 210
O
1.3.6 Arrays, Methods
Arrays: An array is a group of like-typed variables or data types that are referred to
by a common name. Arrays in Java work differently as compared C/C++.
ty
r si
ve
ni
Array comprises of different data types (int, float, etc.) as well as object (or non-
primitive data types) references of a class depending on the definition of the array. In
U
data types, the real values are stored in nearby memory locations.
One-Dimensional Arrays:To define an array we need two components: the type and
the name. Type defines the element type of the array. The element type determines the
ity
class GFG
{
m
int[] arr;
)A
arr[0] = 10;
arr[1] = 20;
(c
arr[2] = 30;
arr[3] = 40;
Amity Directorate of Distance & Online Education
82 Object Oriented Programming Using Java
arr[4] = 50;
Notes
e
for (int xy = 0; xy<arr.length; xy++)
System.out.println(“array contains “ + a +
in
“ : “+ arr[a]);
}
nl
}
Output:
O
Array contains0 : 10
Array contains1 : 20
Array contains 2 : 30
ty
Array contains3 : 40
Array contains4 : 50
r si
ve
Creating Array of objects:
ni
class Student
this.roll_no = roll_no;
this.name = name;
m
}
)A
Student[] arr;
e
arr[0] = new Student(1,”Nandika”);
in
arr[2] = new Student(3,”shikar”);
nl
arr[4] = new Student(5,”mohit”);
O
System.out.println(“Element at “ + a + “ : “ +
arr[xy].roll_no +” “+ arr[xy].name);
ty
}
Output
si
Element at 0 : 1 Nandika
Element at 1 : 2 Ravi
Element at 2 : 3 shikar
r
ve
Element at 3 : 4 Rituj
Element at 4 : 5 mohit
ni
class multiDimensional
U
System.out.print(arr[xy][yz] + “ “);
System.out.println();
}
(c
Output:
Notes
e
2 7 9
3 6 1
in
7 4 2
nl
O
ty
Check your Understanding
si
1. _________________________ is used when a developer needs to increment the
value of a variable in an expression.
2. r
_________________________ determine the relationship that one variable has with
the other variable.
ve
3. Scanner is a predefined class inside __________________ package
4. _________________________ arrays are arrays of arrays with each of element of
the array hold the reference of another array.
ni
Summary
●● The increment operator is used when a developer needs to increment the value
of a variable in an expression. In the Pre-Increment, value is incremented first
ity
and then used inside the expression. But in the Post-Increment, value is first used
inside the expression and then it’s get incremented.
●● The increment and decrement operators are unary operators that add or subtract
one to or from their operand. In most cases, they are implemented in imperative
m
to dispatch execution to different parts of the developer code based on the value
of an expression.
●● The increment and decrement operators are unary operators that add or subtract
one to or from their operand, respectively. They are typically implemented in
imperative programming languages. Each operator in C-like languages has two
(c
e
name. Arrays in Java work differently than they do in C/C++. Following are some
important points about Java arrays.
in
●● In Java, all arrays are dynamically allocated. (discussed below)
●● Since arrays are objects in Java, we can find their length using the object property
length. This is different from C/C++, where we find length using sizeof.
nl
●● A Java array variable can also be declared like other variables with [] after the data
type.
●● The variables in the array are ordered, and each has an index beginning from 0.
O
●● Java array can be also be used as a static field, a local variable, or a method
parameter.
ty
●● The size of an array must be specified by int or short value and not long.
●● The direct superclass of an array type is Object.
●● Every array type implements the interfaces Cloneable and java.io.Serializable.
si
Activity
1. Create a below design using loops?
r
ve
ni
U
Glossary
Operator Result
)A
I= OR assignment
Notes
e
^= XOR assignment
== Equal to
in
!= Not equal to
?: Ternary if-then-else
nl
model, date and time facilities, internationalization, and miscellaneous utility
classes (a string tokenizer, a random-number generator, and a bit array).
O
Further Readings:
1. Programmer’s Guide to Java SE 8 Oracle Certified Associate (OCA), Mughal/
Rasmussen
ty
2. Deploy, Manage and Update Java Runtime Environment in the Enterprise with
System Center Configuration, Trevor Jones
3. Java Fundamentals, Herbert Schildt (Author), Dale Skrien (Author)
si
4. Programming in Java, Sachin Malhotra, Saurabh Choudhary
4. Multidimensional
5. decrement operator
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Define the concept behind overriding
●● What are abstract classes
●● What are final classes
O
Introduction
Inheritance in Java is a instrument in which one object acquires all the properties
ty
and characterstics of a parent object. It is an essential part of OOPs (Object Oriented
programming system).
The thought at the back of mind is that, inheritance in Java is that developer
si
can create new classes that are built upon existing classes. When you inherit from
an accessible class, developer can reuse methods and fields of the parent class.
Moreover, a developer can add new methods and fields in his/her current class as well.
r
ve
ni
U
ity
m
)A
1. Single Inheritance
(c
2. Multilevel Inheritance
3. Hierarchical Inheritance
e
5. Hybrid Inheritance(Through Interfaces)
1. Single Inheritance: “In single inheritance, subclasses inherit the features of one
in
superclass.In the image below, class X serves as a base class for the derived class
Y.”
nl
O
Single Inheritance
ty
Example of Single Inheritance:
// single inheritance
si
import java.io.*;
import java.lang.*;
import java.util.*;
r
ve
class single {
System.out.println(“Welcome”);
}
U
// Driver class
m
g.print_welcome();
(c
g.print_to();
g.print_java();
}
Notes
e
}
in
Output
Welcome
to
nl
java
O
base class as well as the derived class also act as the base class to other class. In
the below image, class X serves as a base class for the derived class Y, which in turn
serves as a base class for the derived class Z.”
ty
r si
ve
Example of Multilevel Inheritance:
// Java program to understand single inheritance
ni
import java.io.*;
import java.lang.*;
U
import java.util.*;
class X {
System.out.println(“Welcome”);
}
m
class Y extends X {
)A
// Driver class
(c
{
Notes
e
two g = new two();
g.print_Welcome();
in
g.print_to();
g.print_Java();
nl
}
O
Output:
Welcome
ty
to
java
si
3. Hierarchical Inheritance: “In Hierarchical Inheritance, one class represent as a
superclass (base class) for more than one subclass. In the below image, class X
serves as a base class for the derived class Y, Z and U.”
r
ve
ni
U
Hierarchical Inheritance
class X {
}
m
class Y extends X {
class Z extends X {
class U extends X {
e
}
in
public static void main(String[] args)
nl
Y obj_Y = new Y();
obj_Y.print_X();
O
obj_Y.print_Y();
ty
Z obj_Z = new Z();
obj_Z.print_X();
obj_Z.print_Z();
si
Uobj_U = new U();
obj_U.print_X();
obj_U.print_U();
r
ve
}
}
ni
Output:
Class X
U
Class Y
Class X
Class Z
ity
Class X
Class U
have more than one superclass and inherit features from all parent classes. Please
note that Java does not support multiple inheritances with classes. In java, we can
achieve multiple inheritances only through Interfaces. In the image below, Class Z is
)A
Notes
e
in
nl
Multiple Inheritances
O
Example of Multiple Inheritances
// Java program to understandtheconcept of Multiple inheritance
ty
import java.io.*;
import java.lang.*;
import java.util.*;
si
interface X {
}
r
ve
interface Y {
interface Z extends X, Y {
System.out.println(“Java”);
m
// Drived class
{
Notes
e
child c = new child();
c.print_Welcome();
in
c.print_To();
c.print_Java();
nl
}
O
Output
Welcome
ty
To
Java
si
5. Hybrid Inheritance(Through Interfaces):“It is a mix of two or more of the above
types of inheritance. Since java doesn’t support multiple inheritances with classes,
hybrid inheritance is also not possible with classes. In java, we can achieve hybrid
inheritance only through Interfaces.”
r
ve
ni
U
ity
Hybrid Inheritances
If subclass (child class) has the similar method as stated in the parent class, it is
known as method overriding in Java. If a subclass provides the specific execution of
the method that has been declared by one of its parent class, it is known as method
)A
overriding.
(c
Notes
e
in
nl
O
ty
Example for method of overriding:
r si
ve
ni
//To show the real scenario of Java Method Overriding where three classes are
overriding the method of a parent class.
U
class Bank{
ity
e
}
class Test2{
in
public static void main(String args[]){
nl
ICICI i=new ICICI();
O
System.out.println(“SBI Rate of Interest: “+s.getRateOfInterest());
ty
System.out.println(“AXIS Rate of Interest: “+a.getRateOfInterest());
si
Output
SBI Rate of Interest: 10
r
ve
ICICI Rate of Interest: 9
Abstract Classes in Java: A class which is declared with the abstract keyword is known
as an abstract class in Java. It can have abstract and non-abstract methods (method with
the body). But in Java we have separate word abstract to make a class abstract.
U
ity
m
Let’s discuss all these observation with the help of Java program
// Class 1
// Abstract class
// Class 2
Notes
e
class Derived extends Race {
void fun()
in
{
nl
}
O
// Class 3
// Main class
ty
class Main {
si
{
r
Race b = new Derived();
ve
b.to();
}
ni
Output
U
Welcome to Java
// Abstract class
// Constructor of class 1
m
Save()
{
)A
// Print statement
}
(c
}
Notes
e
// Class 2
in
// Constructor of class2
Derived()
nl
{
O
}
// Method of class2
ty
void fun()
si
}
// Class 3
r
ve
// Main class
class GFG {
ni
{
U
Output
m
void fun()
{
Notes
e
// Print message if class 1 function is called
System.out.println(
in
“Base class function is called”);
nl
}
// Class 2
O
class Derived extends Base {
ty
// Class 3
class Main {
si
public static void main(String args[])
r
// Creating object of class 2
ve
Derived d = new Derived();
ni
d.fun();
}
ity
Output
Base class function is called
// Class 1
// Abstract class
)A
{
(c
System.out.println(“Welcometo() Java”);
}
Notes
e
// Class 2
in
}
// Class 3
nl
// Main class
class GFG {
O
// Main driver method
ty
{
si
// Calling method on object created above
// inside main()
b.to();
r
ve
}
}
ni
Output:
Welcome to Java
U
// An abstract class
ity
}
(c
e
6. “Similar to the interface we can define static methods in an abstract class”.
in
// Class ABC
// Abstract class
nl
// Abstract method
O
{
// Print statement
ty
System.out.println(“Welcome to Java”);
si
}
// Class xyz
r
// Main class extending Helper class
ve
public class mno extends Helper {
Helper.demofun();
}
ity
Output
Welcome to Java
m
When a variable is declared with final keyword, its value can’t be changed,
essentially, a constant. This also means that you must given a final variable. If the
final variable is a reference, this means that the variable cannot be recoil to reference
another object, but the inner state of the object pointed by that reference variable can
be altered i.e. you can add or subtract elements from the final array or final collection.
(c
Notes
e
in
nl
O
// Main class
ty
class GFG {
si
public static void main(String[] args)
r
// Creating sn object of StringBuilder class
ve
// Final reference variable
System.out.println(sb);
sb.append(“to Java”);
ity
System.out.println(sb);
m
}
)A
Output
Welcome
Welcome to Java
(c
Final Classes: “When a class is declared with final keyword, it is called a final
class. A final class cannot be extended (inherited).”
Notes
e
in
final class A
nl
// methods and fields
O
// The following class is illegal
class B extends A
ty
{
si
Output
When we try to execute is gives us a COMPILE-ERROR! Can’t subclass A
because class has been declared final.
r
ve
Final Methods
ni
“When a method is declared with final keyword, it is called a final method. A final
method cannot be override by other method. The Object class does this—a number of
its methods are final. We must declare methods with the final keyword for which we are
U
required to follow the same implementation throughout all the derived classes.”
class A
{
ity
}
)A
class B extends A
void m1()
(c
System.out.println(“Illegal!”);
Notes
e
}
in
Check your Understanding
1. In ______________________ subclasses inherit the features of one superclass.
nl
2. In ________________________ one class can have more than one superclass and
inherit features from all parent classes.
O
3. If subclass (child class) has the similar method as stated in the parent class, it is
known as _________________________ in Java.
4. When a variable is declared with final keyword, its value can’t be ______________ .
ty
5. When a method is declared with final keyword, it is called a __________________ .
Summary
si
●● Using the inheritance technique, a class can inherit the properties of a superclass.
●● Inheritance refers to a subclass’s capacity to inherit the generic properties of
classes higher up in a class hierarchy.
●●
r
Properties can only be passed from a superclass to a subclass.
ve
●● Inheritance allows for code reuse.
●● Inheritance improves software maintenance.
●● Inheritance allows for class extension via subclassing.
ni
●● Single inheritance refers to a class that inherits properties from only one
superclass.
U
●● Multiple inheritance occurs when a class inherits properties from two or more
superclasses.
●● Because multiple inheritance is not supported in Java, the interface construct,
which is accessed via the interface keyword, is an alternate option for achieving
ity
abstract.
Activity
)A
void x();
(c
void y();
Notes
e
}
class A implements I {
in
A() {}
nl
class B extends A {
B() {}
O
public void y() {
ty
b) z.printLine(2, “Object-Oriented Programming”)
c) z.printLine(“Java”)
si
e) z.printLine(“Object-Oriented Programming”, 3)
System.out.println(“in B.y”);
ni
void z() {
w();
U
x();
A aa = new A();
B bb = new B();
bb.z();
m
bb.y();
}
)A
e
4. What do you mean by Final classes?
in
Glossary
●● OOPs: Object Oriented programming
●● Abstract Class: A class which is declared with the abstract keyword is known as an
nl
abstract class in Java.
●● Hybrid Inheritance: It is a mix of two or more of the above types of inheritance.
O
●● Hierarchical Inheritance: In Hierarchical Inheritance, one class represent as a
superclass (base class) for more than one subclass.
Further Readings:
ty
1. Object-Oriented Data Structures Using Java, Nell Dale, Daniel T. Joyce, Chip
Weems , Jones and Bartlett
2. Effective Java, Joshua Bloch
si
3. Java Performance, Binu John and Charlie Hunt
4. JavaScript: Programming Basics for Absolute Beginners, Nathan CLARK
3. method overriding
4. changed
U
5. final method
ity
m
)A
(c
e
Structure:
in
2.1 Introduction to Packages
2.1.1 Packages : Defining Package, CLASSPATH
nl
2.1.2 Type of Packages
2.1.3 Importing Packages
O
2.1.4 Access Specifiers
2.1.5 Interfaces: Implementing Interfaces
2.1.6 Interfaces vs Abstract Class
ty
2.2 Exception Handing
2.2.1 Introduction to Exceptions
2.2.2 Exception Handling by using Try-Catch
si
2.2.3 Catching Multiple Exceptions
2.2.4 Types of Exceptions
2.2.5 r
final vs finally clause ,throw vs throws
ve
2.3 Throwing Exceptions
2.3.1 Implementation of finally, throw & throws
2.3.2 Fundamentals of throwing exceptions
ni
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Understand different type of Packages in Java
●● How to import a Importing Packages
O
●● What are Access Specifiers
●● What are Interfaces & How to Implement Interfaces
●● Difference between Abstract Class and Interfaces
ty
Introduction
Package in Java is a system to sum up a group of classes, sub packages and
si
interfaces. Packages are used for:
●● To stop naming issue. For example there can be two classes with name Employee
in two packages, Hospital.staff.cse.Employee and Hospital.staff.ee.Employee
●●
r
It is use to make searching/locating easier, usage of classes, interfaces,
ve
enumerations and annotations.
●● To authorize Prescribed access: A protected member can be used by classes
in the same package and its subclasses. A default member (without any access
ni
If you erase the package statement, the class names will automatically be put into
the default package, which has no name. (This is why you haven’t had to worry about
packages before now.) While the default package is ok for short, sample programs, it is
complex for real applications. More often than not, developer will define a package for
m
package pkg;
)A
Java language uses the file system directories to store packages. For example,
the .classxyz files for any classes you defined should be a part of MyPackage must
be stored in a directory called MyPackage. Keep in mind case is significant, and the
directory name is obliged to match the package name exactly.
(c
More than one file can use the similar package statement. The package statement
specifies to which package the classes defined in a file belong. It does not eliminate
other classes in other files from being part of that same package. In most real world
Notes
e
problem packages are spread transversely in many files.
You can create a ladder of packages. To do that a developer need to separate each
in
package name from the one above it by use of a period. General form of the package is
represented as:
nl
package pkg1[.pkg2[.pkg3]]
How packages work: Package names and directory structure are linked to each
other. For example if a package name is Hospital.staff.cse, then there are three
O
directories, Hospital, staff and cse such that cse is present in staff and staff is present
hospital. Also, the directory Hospital is accessible through CLASSPATH variable, i.e.,
path of parent directory of hospital present in CLASSPATH. The idea is to make sure
that classes are easily to trace.
ty
r si
ve
ni
class Statement {
String name;
double bal;
ity
Statement(String n, double b) {
name = n;
bal = b;
m
void show() {
)A
if(bal<0)
System.out.print(“--> “);
System.out.println(name + “: $” + bal);
(c
class Accountstatement {
Notes
e
public static void main(String args[]) {
in
current[0] = new Statement(“Ravi”, 123.23);
nl
current[2] = new Statement (“Suresh”, -12.33);
O
}
ty
Call this file AccountStatement.java and put it in a directory called MyPackdemo.
Next, compile the file. Make sure that the resulting .class file is also in the
MyPackdemo directory. Then, try executing the Accountstatement class, using the
si
following command line:
java MyPackdemo.AccountStatement
r
Remember, you will need to be in the directory above MyPackdemo when you
ve
execute this command. (Developer can use one of the other two options described in
the preceding section to specify the path MyPackdemo.)
java AccountStatement
AccountStatementmust be qualified with its package name.
U
Access Protection: Classes and packages both are used for encapsulating and
containing the name space and scope of variables and methods. Packages role is to
play as containers for classes and other subordinate packages. The class is Java’s
ity
least unit of abstraction. Because of the relationship between classes and packages,
Java addresses four categories of visibility for class members:
m
)A
●● Private
●● Public
(c
●● Protected
Notes
e
Private No Modifier Protected Public
Same class No Yes Yes Yes
in
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
nl
Different package non-subclass No No No Yes
O
While Java’s access control mechanism may seem complex, we can make it
simpler.
ty
●● Anything defined private cannot be seen outside of its class.
●● When a member does not have an explicit access requirement, it is noticeable to
subclasses as well as to other classes in the same package. This is the default access.
si
CLASSPATH: CLASSPATH is an environment variable which is used by Application
ClassLoader to find and load the .class files. The CLASSPATH determine the path,
to find third-party and user-defined classes that are not extensions or part of Java
r
environment. Itincludes all the directories which have .class files and JAR files when
ve
setting the CLASSPATH.
ni
U
The default value of CLASSPATH is a dot (.). It states that the only current
directory searched. The default value of CLASSPATH is changed when you set the
CLASSPATH variable or using the -classpath command (for short -cp). Put a dot (.) in
ity
the new setting if developer want to include the current directory in the search path.
If CLASSPATH finds a class file which is present in the current directory, then it will
load the class from the current directory and use it, without considering the same name
class presents in another directory which is also included in the CLASSPATH.
m
If you want to multiple classpaths, then developer need to put a semicolon (;) after
each CLASSPATH.
)A
You are required to include the directory You are required to include all the directories
which contains .exe files. which contain .class and JAR files.
PATH environment variable once set, The CLASSPATH environment variable can
Notes
e
cannot be overridden. be overridden by using the command line
option -cp or -CLASSPATH to both javac and
in
java command.
nl
O
2.1.2 tType of Packages
Packages can be divided in two parts:
ty
2. User Defined Packages
r si
ve
Types of Packages
1. Built in Packages: These packages containa large number of classes which are a
part of Java API. Frequent using built in packages are:
ni
U
ity
m
2. User-defined packages: These are the packages that are created by the developer.
e
name of the package). Then define the MyClassdemo inside the directory with the first
statement being the package names.
in
// Name of the package must be similar to the directory
package myPackagedemo;
nl
public class MyClassdemo
O
{
System.out.println(s);
ty
}
si
Now developer can use the MyClassdemo class in our program.
r
import myPackagedemo.MyClassdemo;
ve
public class PrintName
// with a value
obj.getNames(name);
}
m
static to be incorporate in Java code without specifying the class in which the field is
defined.
e
import static java.lang.System.*;
class StaticImportDemo
in
{
nl
{
O
out.println(“Welcome to Java”);
ty
}
Output
si
Welcome to Java
Handling name conflicts: The only time we need to pay attention to packages is
when we have a name conflict it means we have packages with same name class. For
r
example both, java.util and java.sql packages have a class named called Date. So if we
ve
import both packages in same program it will show a compile error:
import java.util.*;
import java.sql.*;
ni
The compiler will not be able to understand which Date class program want. This
problem can be resolved by using a precise import statement:
U
import java.util.Date;
import java.sql.*;
ity
If a developer wants to use both Date classes then, developer needs to use a full
package name every time as he/she declares a new object of that class.
To import java package into a class, developer need to use java import keyword
this is used to get the right to use package and its classes into the java program.
Use import keyword to access built-in and user-defined packages into your java
source file so that your class can refer to a class that is insomeother package by
(c
There are 3 different ways to refer to any class that is present in a different package:
Notes
e
◌◌ without import the package
◌◌ import package with specified class
in
◌◌ import package with all classes
1. Accessing package without import keyword: If you employ fully qualified name to
import any class into your program, then only that specific class of the package
nl
are going to be accessible in your program, other classes within the same package
won’t be accessible. For this approach, there’s no got to use the import statement.
But developers need to use the fully qualified name whenever you’re accessing the
O
category or the interface. This is often generally used when two packages have
classes with same names. For example: java.util and java.sql packages contain
Date class.
ty
package demopack;
si
System.out.println(“Hello Java”);
}
r
ve
package mypack;
class XYZ {
ni
obj.msg();
}
ity
Output
Hello Java
2. Import the Specific Class: Package can have many classes but sometimes we would
m
like to access only specific class in our program in that case, Java allows us to
specify class name along side the package name. If developer want to use import
packagenamedemo.classnamedemo statement then only the class with name
)A
System.out.println(“Hello Java”);
}
Notes
e
}
package mypackdemo;
in
import demopack.Demo;
class Test {
nl
public static void main(String args[]) {
O
obj.msg();
ty
}
Output
si
Hello Java
package learnjava;
ni
System.out.println(“Hello Java”);
}
ity
package Java;
import learnjava.*;
class Second {
m
obj.msg();
}
(c
Output
Hello Java
e
There is no difference between access specifier and access modifier in Java.
They both mean the same. Access modifier is the new and official term used instead
in
of access specifier. The access modifiers in Java specify the accessibility or scope of a
classes, field methods and constructors.
nl
O
ty
si
Access within within outside package outside
Modifier class package by subclass only package
Private r
Y N N N
ve
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
ni
1. Private: The private access specifier is available only within the class.
// private specifier
U
package p1;
class A
{
ity
System.out.println(“Welcome to Java”);
m
}
)A
class B
e
obj.display();
in
}
nl
Output
error: display() has private access in A obj.display()
2. Default: If developers don’t use any specifier, it is act as default by default. The
O
default specifier is reachable only within package. It cannot be used from outside the
package. It provides more convenience than private. But, it is further restrictive than
protected, and public.
ty
//save by ABC.java
package pack;
class ABC{
si
void msg(){System.out.println(“Hello”);}
}
r
ve
//save by XYZ.java
package mypack;
import pack.*;
ni
class XYZ{
obj.msg();
}
ity
Output
Compile time Error
m
3. Protected: The protected access specifier is available within package and outside
the package but with the help inheritance only. The protected access specifier can
be applied on the data member, method and constructor protected access specifier
)A
package pack;
(c
}
Notes
e
//save by XYZ.java
package mypack;
in
import pack.*;
nl
public static void main(String args[]){
O
obj.msg();
ty
}
Output
si
Welcome to Java
4. Public: The public access specifier is specified using the keyword public. The public
access specifier has the widest scope among all other access specifier. Classes,
r
methods, or data members that are declared as public are reachable from everywhere
ve
in the program. There is no constraint on the scope of public data members.
package demopack;
}
U
package demomypack;
import demopack.*;
class XYZ{
ity
obj.msg();
m
}
)A
Output
Hello Java
Using the keyword interface, you’ll fully abstract a class’ interface from its
implementation. That is, using interface, you’ll specify what a category must do, but not
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 119
how it does it. Interfaces are syntactically almost like classes, but they lack instance
Notes
e
variables, and their methods are declared with none body. In practice, this suggests
that you simply can define interfaces that don’t make assumptions about how they’re
implemented. Once it’s declared, any number of classes can implement an interface.
in
Also, one class can implement any number of interfaces
nl
defined by the interface. However, each class is liberal to determine the small print of its
own implementation. By assigning the interface keyword, Java allows you to completely
utilize the “one interface, multiple methods” aspect of polymorphism
O
Interfaces are designed to support dynamic method resolution at run time.
Normally, so as for a way to be called from one class to a different , both classes got
to be present at compile time therefore the Java compiler can check to make sure that
the tactic signatures are compatible. This condition by itself makes for a static and
ty
nonextensible classing environment.
Certainly throughout a system like this, functionality gets pushed up higher and
better within the class hierarchy in order that the mechanisms are going to be available
si
to more and more subclasses. Interfaces are designed to avoid this problem. They
disconnect the definition of a way or set of methods from the inheritance hierarchy.
Since interfaces are during a different hierarchy from classes, it’s possible for classes
r
that are unrelated in terms of the category hierarchy to implement an equivalent
ve
interface. this is often where the important power of interfaces is realized.
return-type method-demoname1(parameter-list);
return-type method-demoname2(parameter-list);
U
return-type method-demonameN(parameter-list);
ity
When no access specifier is included, then default access results, and therefore
m
the interface is merely available to other members of the package during which it’s
declared. When it’s declared as public, the interfaces are often employed by the other
code. During this case, the interface must be the sole public interface declared within
)A
the file, and therefore the file must have an equivalent name because the interface.
Name is that the name of the interface, and may be any valid identifier. Notice that
the methods that are declared haven’t any bodies. They end with a semicolon after
the parameter list. They are, essentially, abstract methods; there is often no default
implementation of any method specified within an interface. Each class that has an
(c
Variables are often declared inside interface declarations. They’re implicitly final
Notes
e
and static, meaning they can’t be changed by the implementing class. They need to
even be initialized. All methods and variables are implicitly public.
in
Here is an example of an interface definition. It defines a simple interface that
contains one method called callbackdemo( ) that takes a single integer parameter.
interface Callbackdemo {
nl
void callback(int param);
O
Uses of Java Interfaces:
ty
r si
ve
ni
U
ity
m
)A
(c
Implementing Interfaces
Once an interface has been declared, one or many classes can use that interface.
To implement an interface, developers need to include the implements clause in
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 121
a class definition, and then create the methods declared by the interface. Syntax for
Notes
e
implementing interface:
in
class classnamedemo [extends superclass] [implements interface [,interface...]] {
// class-body
nl
}
“If a class implements one or more interface, then the interfaces are separated with
a comma. Ifa class implements two interfaces that declare the same method, then the
O
same method willbe used by clients of either interface. The methods that implement an
interface must bedeclared public. Also, the type signature of the implementing method
must match exactlythe type signature specified in the interface definition.”
ty
class Client implements Demo {
si
public void Demo(int p) {
}
r
ve
}
declare added members of their own. For example, the following version of Client
implementscallbackdemo( ) and adds the method adds the method Demo( ):
Demo( ):
U
}
m
void Demo() {
}
(c
often mentioned by such a variable. Once you call a way through one among these
Notes
e
references, the right version are going to be called supported the particular instance of
the interface being mentioned. This is often one among the key features of interfaces.
The tactic to be executed is searched dynamically at run time, allowing classes to be
in
created later than the code which calls methods on them. The calling code can dispatch
through an interface without having to understand anything about the “callee.”
nl
The following example calls the callbackdemo( ) method via an interface reference
variable:
O
// Implement Callback’s interface
ty
System.out.println(“callback called with “ + p);
class demo {
si
public static void main(String args[]) {
a.callbackdemo(91);
r
ve
}
}
ni
Output
callback called with 91
U
interface declaration. Thus, a could not be used to access demo( ) since it is defined by
Client but not Callbackdemo.
power ofsuch a reference. To sample this usage, first create the second implementation
of Callbackdemo,shown here:
}
Notes
e
}
class demo2 {
in
public static void main(String args[]) {
nl
AnotherClientob = new AnotherClient();
d.callbackdemo(91);
O
d = ob; // d now refers to AnotherClient object
d.callback(91);
ty
}
si
Output
callbackdemo called with 91
Partial Implementations
If a class contains an interface but does not fully implement the methods declared
by that interface, then that class must be declared as an abstract class. For example:
U
int a, b;
ity
void show() {
System.out.println(a + “ “ + b);
}
m
Here, the class Incomplete does not implement callbackdemo( ) and must be
declared as abstract. Any class that inherits Incomplete must implement callbackdemo(
)A
Notes
e
in
nl
Example for Nested Interfaces:
O
class ABC {
ty
public interface NestedIFdemo {
booleanisNotNegative(int y);
si
}
r
// XYZ implements the nested interface.
ve
class XYZ implements ABC.NestedIFdemo {
public booleanisNotNegative(int y) {
}
U
class NestedIFDemo1 {
if(demo.isNotNegative(10))
if(demo.isNotNegative(-12))
Notice that ABC defines a member interface called NestedIFdemo and that it is
(c
implements ABC.NestedIFdemo
Notes
e
The name is fully qualified by the enclosing class’ name. Inside the main( ) method,
an ABC.NestedIFdemo reference called demo is created, and it is assigned a reference
in
to a XYZ object. Because XYZ implements XYZ.NestedIFdemo, this is legal.
nl
One interface can inherit the characteristics another interface by use of the
keyword extends. The declaration is the same as for inheriting classes. When a class
uses an interface that inherits the properties of another interface, it must provide
O
implementations for all other methods declared within the interface inheritance chain.
Example:
ty
interface ABC {
void methX();
si
void methY();
r
// XYZ now includes methX() and methY() -- it adds methZ().
ve
interface XYZ extends ABC {
void methZ();
}
ni
System.out.println(“Implement methX().”);
}
ity
System.out.println(“Implement methY().”);
}
m
System.out.println(“Implement methZ().”);
)A
class IFExtenddemo {
(c
e
ob.methX();
ob.methY();
in
ob.methZ();
nl
}
To try, developer might want to try removing the implementation for methX(
O
) in MyClassdemo. This will show a compile-time error. As told earlier, any class that
implements an interface must implement all methods declared by that interface,
together with any that are inherited from other interfaces.
ty
2.1.6 Interfaces v/s Abstract Class
r si
ve
ni
U
ity
Type of variables The interface has only Abstract class can have final, non-
static and final, static and non-static variables
final variables.
Implementation: Interface can’t provide Abstract class can provide the
the implementation of an implementation of the interface.
(c
abstract class.
e
Abstraction implemented using the using the keyword “extends”
keyword “implements”
in
Multiple An interface can extend Abstract class can extend another
implementations: another Java interface Java class and implement multiple
only Java interfaces.
nl
Accessibility of Members of a Java A Java abstract class can have class
Data Members: interface are public by members like private, protected, etc
default
Inheritance Interface supports multiple public abstract class Shape( public
O
inheritances. abstract void draw();
Example public interface Drawable
( void draw ();
ty
r si
ve
Program to show the concept of abstract class
import java.io.*;
ni
// abstract class
// declare fields
String objectName = “ “;
System.out.println(this.objectName + “ “
)A
+ “ m = “ + m + “ and n = “ + n);
}
(c
e
abstract public void draw();
in
class Rectangle extends Shape {
nl
// constructor
O
{
super(name);
ty
this.length = length;
this.width = width;
si
@Override public void draw()
r
System.out.println(“Rectangle has been drawn “);
ve
}
double pi = 3.14;
int r;
// constructor
m
{
)A
super(name);
this.radius = radius;
}
(c
e
}
in
{
nl
}
O
class GFG {
ty
{
System.out.println(“Area of rectangle: “
si
+ rect.area());
rect.moveTo(1, 2);
System.out.println(“ “);
r
ve
Shape circle = new Circle(2, “Circle”);
System.out.println(“Area of circle: “
ni
+ circle.area());
circle.moveTo(2, 4);
U
Output
ity
Notes
e
in
nl
O
Program to illustrate the concept of interface
import java.io.*;
interface Shape {
ty
// abstract method
void draw();
si
double area();
}
r
class Rectangle implements Shape {
ve
int length, width;
// constructor
this.length = length;
U
this.width = width;
}
ity
}
(c
double pi = 3.14;
Notes
e
int r;
// constructor
in
Circle(int r) { this.r = r; }
nl
{
O
}
ty
{
si
}
class GFG {
System.out.println(“Area of rectangle: “
+ rect.area());
U
System.out.println(“Area of circle: “
+ circle.area());
ity
Output
m
e
1. General form of the package is represented as ______________________ .
2. CLASSPATH is an environment variable which is used by Application ClassLoader
in
to find and load the _____________________ files.
3. The default value of CLASSPATH is a ___________________ .
nl
4. __________________________ are the packages that are created by the developer.
5. Java allows us to specify class name alongside the ___________________ name.
6. Developers don’t use any specifier, it is act as _____________________ by default.
O
Summary
●● The package statement defines a name space in which classes are saved. If you
ty
erase the package statement, the class names will automatically be put into the
default package, which has no name.
●● Classes and packages both are used for encapsulating and containing the name
si
space and scope of variables and methods. Packages role is to play as containers
for classes and other subordinate packages.
●● The CLASSPATH determine the path, to find third-party and user-defined classes
r
that are not extensions or part of Java environment. It includes all the directories
ve
which have .class files and JAR files when setting the CLASSPATH.
●● Built in Packages: These packages contain a large number of classes which are a
part of Java API.
ni
U
ity
●● To import java package into a class, developer need to use java import keyword
m
this is used to get the right to use package and its classes into the java program.
●● Once an interface has been declared, one or many classes can use that interface.
To implement an interface, developers need to include the implements clause in a
)A
class definition, and then create the methods declared by the interface.
●● In the java application there are some related classes that need to share some
lines of code then you can put these lines of code within the abstract class and this
abstract class should be extended by all these related classes.
(c
Activity
1. Create a program using multiple interfaces?
e
1. Define package?
2. What do you mean by CLASSPATH?
in
3. Define different type of packages?
4. How to import packages?
nl
5. What do you mean by access specifiers?
6. What are interfaces?
O
7. How one can implement interfaces?
8. What is the difference between Interfaces and Abstract Class?
Glossary
ty
-cp: Classpath
si
( versions 5 and above ) that permits members ( fields and methods ) defined in a
class as public static to be incorporate in Java code without specifying the class in
which the field is defined.
●● r
Nested Interface: An interface can be defined as member of a class or another
ve
interface such an interface is called a member interface or nested interface.
Further Readings:
1. The Java Programming Language, James Gosling and Ken Arnold
ni
1. package pkg;
2. .class
3. dot (.)
m
4. User-defined packages
5. package
)A
6. default
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● How to handle Exception by using Try-Catch
●● What is Catching Multiple Exceptions
O
●● Different Types of Exceptions
●● Difference between final v/s finally clause andhrow v/s throws
Introduction
ty
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
si
In this unit, we will learn about Java exceptions, it’s types, and the difference
between checked and unchecked exceptions.
execution of a program i.e at run time that disturbed the regular flow of the program’s
instructions.
People often confuse between error and exception. To make this clear, An Error
U
indicates towards the serious issue that a reasonable application should not try to
catch. Exception indicates towards the conditions that a reasonable application might
try to catch.
try {
// ...
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 135
finally {
Notes
e
// block of code to be executed after try block ends
in
Exception Hierarchy
“All exception and errors types are sub classes of class Throwable, which is
nl
base class of hierarchy.One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception. Another branch,Error are used by the Java run-time
O
system(JVM) to indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.”
ty
r si
ve
ni
Whenever inside a program code, if an exception has occurred, the tactic creates
an Object referred to as Exception Object and hands it off to the run-time system (JVM).
“The exception object includes name and definition of the exception, and current state
of the program code where exception has occurred. Creating the Exception Object and
ity
●● If run-time system looks for all the methods on call stack and couldn’t have locate
Notes
e
the acceptable handler then run-time system handover the Exception Object to
default exception handler, which is a module of run-time system. This exception
handler prints the exception details within the following format and ends the
in
program unusually.
// Example to show how exception is thrown.
nl
class ThrowsExecpDemo{
O
String str = null;
System.out.println(str.length());
ty
}
Output
si
Exception in thread “main” java.lang.NullPointerException
at ThrowsExecp.main(File.java:8)
r
ve
ni
U
ity
The call stack and searching the call stack for exception handler.
class ExceptionThrowndemo
{
)A
int i = x/y;
(c
return i;
e
int a =0;
try
in
{
a = divideByZero(x,y);
nl
}
O
catch(NumberFormatException ex)
ty
System.out.println(“NumberFormatException is occured”);
return a;
si
}
int x = 1;
r
ve
int y = 0;
try
{
ni
int i = computeDivision(x,y);
}
U
catch(ArithmeticException ex)
{
ity
System.out.println(ex.getMessage());
}
m
Output
)A
/ by zero.
e
●● Developer code can catch this exception (using catch block) and figure out in
some rational manner.
in
●● System-generated exceptions are mechanically thrown by the Java run-time
system.
●● If a developer wants to manually throw an exception, then he/she must use the
nl
keyword throw.
●● Any exception that is thrown out of a method must be specified as such by a
throws clause.
O
●● Any code that completely must be executed or run after a try block completes is
put in a finally block.
ty
r si
ve
ni
U
To safeguard against and handle a run-time error, simply put that set of code that
you want to monitor inside a try block. Right away following the try block, includes a
catch clause that provides the information of exception type that you wish to catch. To
demonstrate how simply this can be achieved, the following program code includes
a try block and a catch clause that executes the ArithmeticException created by the
(c
division-by-zero error:
class Excdemo {
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 139
e
int x, y;
try {
in
x = 0;
y = 24 / x;
nl
System.out.println(“Error.”);
O
System.out.println(“Division by zero.”);
ty
System.out.println(“After catch statement.”);
si
Output:
Division by zero.
r
ve
If you notice in above program that the call to println( ) inside the try block is never
executed. Once an exception is thrown, program control put it out of the try block to the
catch block.
In other words, catch is not “called,” so execution never “returns” to the try block
ni
from a catch. Thus, the line “Error.” is not displayed. Once the catch statement has
executed, program control continues the execution with the next line in the program to
follow the entire try/catch instrument.
U
ity
m
)A
(c
Notes
e
in
The objective of most of the well-constructed catch clauses is to resolve the
nl
exceptional condition and then continue to execute the program as if the error had
never happened.
O
For example, in the next program each iteration of the for loop obtains two arbitrary
integers. Those two integers are then divided by each other, and the result is used
to divide the value 34567. The final result is put into ABC. If either division operation
causes a divide-by-zero error, it is caught, the value of ABC is set to zero, and the
ty
program continues.
import java.util.Random;
si
class HandleErrorDemo {
try {
y = a.nextInt();
U
z = a.nextInt();
x = 56789 / (y/z);
} catch (ArithmeticException e) {
ity
System.out.println(“Division by zero.”);
}
m
System.out.println(“x: “ + x);
}
)A
e
public static void main(String[] args) {
try
in
{
int data=25/0;
nl
}
O
catch(ArrayIndexOutOfBoundsException e)
ty
System.out.println(e);
si
}
}
r
Exception in thread “main” java.lang.ArithmeticException: / by zero
ve
2.2.3 Catching Multiple Exceptions
There are cases where one can found more than one exception could be raised by
ni
a single piece of code. To tackle this, developer can specify two or more catch clauses,
each catching a type of exception which is raised. When an exception is thrown, each
catch statement is inspected in order, and whichever the first one whose type matches
U
that of the resulting exception is get executed. After one of the catch statements gets
executes, the others are automatically bypassed, and execution continues will run after
the try/catch block.
class MultiCatchdemo {
try {
int x = args.length;
)A
System.out.println(“x = “ + x);
int y = 42 / x;
int z[] = { 1 };
(c
z[52] = 99;
} catch(ArithmeticException e) {
System.out.println(“Divide by 0: “ + e);
Notes
e
} catch(ArrayIndexOutOfBoundsException e) {
in
}
nl
}
O
This code will cause a division-by-zero exception if it is initiated with no command
line arguments, since x will equal zero. It will endure the division if you give a
command-line argument, setting x to something more than zero. But it will cause an
ty
ArrayIndexOutOfBoundsException, since the int array z has a length of 1, yet the
program attempts to assign a value to z[42].
si
C:\>java MultiCatch
x=0
r
Divide by 0: java.lang.ArithmeticException: / by zero
ve
After try/catch blocks.
C:\>java MultiCatchTestArg
ni
x=1
When a developer use more than one catch statements, it is vital to keep in mind
that exception subclasses must come before any of their superclasses. It is because a
ity
catch statement that uses a superclass will grasp exceptions of that type plus any of its
subclasses. Thus, a subclass would never be executes if it is came after superclass.
additional, in Javalanguage,a unreachable code is lead to an error.
For example:
m
class SuperSubCatch {
try {
int x = 0;
int y = 42 / a;
(c
} catch(Exception e) {
}
Notes
e
/*ArithmeticException is a subclass of Exception that’s why this catch never get
executed */
in
catch(ArithmeticException e) { // ERROR - unreachable
nl
}
O
}
ty
r si
ve
ni
U
ity
m
Java also allows a developer to define and create their own exceptions. In java
exceptions are majorly categorized into two types:
◌◌ Built-In Exception
◌◌ User Defined Exception
(c
Notes
e
in
nl
O
ty
1. Built-in Exceptions: Built-in exceptions are the pre-defined exceptions which are
already exist in Java libraries
si
Some of important built-in exceptions in Java listed below:
r
ve
ni
U
ity
m
Nullpointerexception:
//Program for NullPointerException
class NullPointer_Demo
(c
{
Notes
e
try {
in
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
nl
System.out.println(“NullPointerException..”);
O
}
ty
Output
NullPointerException..
si
StringIndexOutOfBound Exception
// programforStringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo r
ve
{
{
ni
try {
char c = x.charAt(24); //
System.out.println(c);
}
ity
catch(StringIndexOutOfBoundsException e) {
System.out.println(“StringIndexOutOfBoundsException”);
}
m
}
)A
Output
StringIndexOutOfBoundsException
(c
FileNotFound Exception
//Program forFileNotFoundException
import java.io.File;
Notes
e
import java.io.FileNotFoundException;
import java.io.FileReader;
in
class File_notFound_Demo {
nl
try {
O
FileReaderfr = new FileReader(file);
} catch (FileNotFoundException e) {
ty
System.out.println(“File does not exist”);
si
}
Output
r
ve
File does not exist
2. User-Defined Exception: There are situation where the built-in exceptions in Java
are not able to describe a certain issues. In those cases, developer needs to create
exceptions which are called ‘user-defined Exceptions’.
ni
U
ity
m
e
private static double bal[] =
in
MyException() { }
nl
// write main()
O
{
try {
ty
// display the Table heading
si
// display the actual account information
{ r
ve
System.out.println(accno[i] + “\t” + name[i] +”\t” + bal[i]);
1000”);
throw me;
}
ity
} //end of try
m
catch (MyException e) {
e.printStackTrace();
)A
}
(c
Output:
RunTime Error
Amity Directorate of Distance & Online Education
148 Object Oriented Programming Using Java
e
at MyException.main(fileProperty.java:36)
in
101 Nisha 20000.0
nl
103 Sushant 4600.0
O
Another example for User defined exception
import java.util.*;
ty
class UserDefinedExceptiondemo{
try{
si
throw new NewException(5);
}
r
catch(NewException ex){
ve
System.out.println(ex) ;
}
ni
}
U
int x;
NewException(int y) {
ity
x=y;
}
)A
Output:
(c
Notes
e
in
nl
2.2.5 throw v/s throws and final v/s finally clause
O
Difference between throw v/s throws
Throw Throws
ty
Java throw keyword is used throw Java throws keyword is used in the method
an exception explicitly in the code, signature to declare an exception which might
inside the function or the block of be thrown by the function while the execution
code. of the code.
si
Using throw keyword, we can only Using throws keyword, we can declare both
propagate unchecked exception ke, checked and unchecked exceptions. However,
the checked exception cannot be the throws keyword can be used to propagate
propagated using throw only. r
checked exceptions only
ve
The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.
throw is used within the method. throws is used with the method signature.
ni
We are allowed to throw only one We can declare multiple exceptions using
exception at a time ie, we cannot throws keyword that can be thrown by
throw multiple exceptions. the method. For example, main() throws
U
IOException, SQLException.
Final Finally
ity
final is the keyword and access finally is the block in Java Exception Handling
modifier which is used to apply to execute the important code whether the
restrictions on a class, method or exception occurs or not.
variable.
m
Final keyword is used with the Finally block is always related to the try and
classes, methods and variables. catch block in exception handling.
Once declared final variable finally block runs the important code even if
)A
e
1. The Exception Handling in Java is one of the powerful mechanism to handle the
_____________________ .
in
2. There could be the list of the tactics that had been called to urge to the method
where exception was occurred. This ordered list of the methods is named Call
________________________ .
nl
3. There are cases where one can found more than one exception could be raised by
a single piece of code is called catching _________________________ .
4. Java _________________________ is used to throw an exception explicitly in the
O
code, inside the function or block of code.
Summary
ty
●● The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error.
●● All exception and errors types are sub classes of class Throwable, which is base
si
class of hierarchy. One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
●● The run-time system searches the decision stack for the tactic that contains
r
the block of code that will handle the thrown exception. The code block is titled
ve
Exception handler.
●● The run-time system begins by looking at the method in which the exception
occurred and proceeds through the call stack in the reverse order in which the
methods were called.
ni
●● If the run-time system searches all methods on the call stack and cannot find
an acceptable handler, the Exception Object is passed to the run-time system’s
default exception handler, which is a module. This exception handler prints the
ity
exception details in the format shown below and terminates the programme in an
unusual way.
●● When a developer use more than one catch statements, it is vital to keep in
mind that exception subclasses must come before any of their superclasses. It is
m
because a catch statement that uses a superclass will grasp exceptions of that
type plus any of its subclasses.
●● The throw keyword in Java is used to explicitly throw an exception from a method
)A
or any block of code. We can throw either checked or unchecked exception. The
throw keyword is mainly used to throw custom exceptions.
Activity
1. Create a program to handle exception using try catch block?
(c
e
1. What do you understand from the word Exceptions?
2. How ro handle Exception using Try-Catch
in
3. How to catch Multiple Exceptions
4. Define various types of Exceptions
nl
5. What are the difference between final vs finally clause?
6. What are the difference between throw vs throws?
O
Glossary
●● JVM: Java virtual Machine
●● Built-in Exceptions: Built-in exceptions are the pre-defined exceptions which are
ty
already exist in Java libraries.
●● ArithmeticException: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
si
●● ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or
equal to the size of the array.
●●
r
ClassNotFoundException: This Exception is raised when we try to access a class
ve
whose definition is not found
●● FileNotFoundException: This Exception is raised when a file is not accessible or
does not open.
ni
●● NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
●● NoSuchMethodException: It is thrown when accessing a method which is not
ity
found.
●● NullPointerException: This exception is raised when referring to the members of a
null object. Null represents nothing
m
Further Readings:
Notes
e
1. JavaScript: Programming Basics for Absolute Beginners, Nathan Clark
2. Java: A Beginner’s Guide, Eighth Edition, Herbert Schildt
in
3. The Java Programming Language, James Gosling and Ken Arnold
4. Java Performance, Binu John and Charlie Hunt
nl
Check Your Understanding:
Answers
O
1. runtime errors
2. Stack
3. multiple exceptions
ty
4. throw keyword
r si
ve
ni
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Basics of throwing exceptions
●● Explain Java’s built-in Exceptions
O
●● How to write Exception Subclasses
●● How to Implement of Exception Handling Mechanism.
Introduction
ty
In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom exceptions
making the code recovery and debugging easier.
si
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some
r
message with it that provides the error description. These exceptions may be related to
ve
user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. We will discuss custom exceptions later in this section.
ni
throws
U
If a method is able of causing an exception that it does not able to handle, it must
told this behavior so that callers of the method can protect themselves against that
type of exception. Developer does this by including a throws clause in the method’s
ity
definition. A throws clause lists the all the types of exceptions that a method can throw.
This is essential for all the exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a method can
caused must be defined in the throws clause. If they are not defined, then a compile-
m
// body of method
}
(c
Exception list contains all the possible exception that a program can throw and
separated by commas.
Example
Notes
e
class ThrowsDemo {
in
System.out.println(“Inside throwOnedemo.”);
nl
}
O
throwOne();
ty
}
This particular code does not provide a throws clause hence the program will not
compile.
si
To make the above code to executes developer need to make two changes
r
2. Main( ) must declared try catch statement
ve
Correct code will look like this:
class ThrowsDemo {
System.out.println(“Inside throwOnedemo.”);
try {
throwOnedemo();
} catch (IllegalAccessException e) {
m
System.out.println(“Caught “ + e);
}
)A
Output:
inside throwOnedemo
(c
Finally
Notes
e
When exceptions are thrown, execution in a method takes a rather unexpected and
nonlinear way that changes flow through the method. Depending upon how the method
in
is coded by developer, it is also possible for an exception to root the method to return
ahead of time. This could be an issue in methods. For example, if a method opens a
file in starting and closes it upon the end, then developer will not want the code that
nl
closes the file to be through by the exception-handling mechanism. The finally keyword
is designed to address this issue.
O
ty
Flowchart of finally block
r si
ve
ni
U
ity
m
Usage of Finally:
)A
try{
(c
int data=30/6;
System.out.println(data);
Notes
e
}
catch(NullPointerException e){
in
System.out.println(e);
nl
//executed regardless of exception occurred or not
finally {
O
System.out.println(“finally executed”);
ty
System.out.println(“remaining code...”);
si
Output
5
r
ve
finally block executed
remaining code
try {
int data=35/0;
ity
System.out.println(data);
catch(NullPointerException e){
m
System.out.println(e);
}
)A
System.out.println(“remaining code...”);
(c
}
Notes
e
Output
in
Inside Try Block
nl
TestfinallyBlockdemo.main(testfinallyblockdemo.java:9)
O
public class TestFinallyBlockdemo{
try {
ty
System.out.println(“Inside try block”);
int data=35/0;
si
System.out.println(data);
catch(ArithmeticException e){ r
ve
System.out.println(“Exception handled”);
System.out.println(e);
}
ni
finally {
System.out.println(“remaining code”);
ity
Output
m
Exception handled
)A
Remaining code
(c
Throw
Till know, we have only been catching exceptions which are thrown by the Java
e
explicitly, using the throw statement. The syntax of throw:
in
nl
The flow of program execution stops as soon as the throw statement; any further
O
code statements are not executed. The adjoining try block is checked to see if it has
any catch statement that matches the type of exception defined by user. If it does find
a match, control is transferred to that statement. If not, then the next enclosing try
statement is checked, and so on. If no similar catch is found, then the default exception
ty
handler stops the program and prints the stack trace.
si
class ThrowDemo {
try { r
ve
throw new NullPointerException(“demo”);
} catch(NullPointerException e) {
}
U
try {
ity
demoprocthrow();
} catch(NullPointerException e) {
System.out.println(“Recaught: “ + e);
m
}
)A
This program will get 2 chances to deal with the same issue. First, main( ) sets up
an exception context and then calls demoprocthrow( ). The demoprocthrow( ) method
then sets up another exceptionhandling context and instantly throws a new instance of
(c
Output
Notes
e
Caught inside demoprocthrow. Recaught: java.lang.NullPointerException: demo
in
2.3.2 Fundamentals of throwing exceptions
A Java exception is an object that describes an exceptional state that has occurred
while running a piece of program code. When an exceptional situation arises, an
nl
object which represents that exception is made and thrown within the method that
has caused the issue or error. That method may prefer to handle the exception itself,
or pass it on. At some point, the exception will be caught and processed. Exceptions
O
are often generated by the Java run-time system, or they will be manually generated
by developer code. Exceptions thrown by Java language relate to basic errors that
violate the principles of the Java language or the constraints of the Java development
environment. Manually generated exceptions are typically wont to report some error
ty
condition to the caller of a way.
Java exception handling is handled with the help 5 keywords: try, catch, throw,
throws, and finally. Briefly, here is how they work.
r si
ve
ni
unchecked exception.
need to check the exception upfront else it show the compiler error.
Exception Meaning
Class Not Found Exception Class not found.
Clone Not Supported Attempt to clone an object that does not
Exception implement the Cloneable interface.
Illegal Access Exception Access to a class is denied.
(c
e
thread.
No Such Field Exception A requested field does not exists.
in
No Such Method Exception A requested method does not exists.
Example for checked exception:
import java.io.*;
nl
class CheckedExceptionExample {
O
FileInputStreamdeomfile_data = null;
ty
int a;
si
System.out.print((char)m);
file_data.close(); r
ve
}
}
ni
Output:
U
ity
In the above code, we are trying to read the welcome to java.txt file and display the
m
content of file on the screen. Following are the exception throw by the code:
1. The exceptions occur in the main method. We can remove these compilation errors
by defining the exception in the main method using the throws keywords. We only
need to declare the IOException, not FileNotFoundException, because of the
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 161
e
child class ofIOException, so this exception will cover by IOException. Developer
need to define in following way
in
class Exception{
nl
public static void main(String args[]) throws IOException {
...
...
O
}
ty
2. We can also tackle these exception using try-catch method.
import java.io.*;
si
class Exceptiondemo{
FileInputStreamfile_data = null;
r
ve
try{
}catch(FileNotFoundExceptionfnfe){
ni
}
U
int m;
try{
ity
System.out.print((char)m);
}
m
file_data.close();
}catch(IOExceptionioe){
)A
}
(c
}
Notes
e
As per the code if file is not in the location we will get proper error message “File
Not Found”
in
Output
nl
O
Unchecked Exceptions: The unchecked exceptions are contradictory to checked
ty
exceptions. The exceptions will not be checked at compile time by the compiler. If a
program shows an unchecked exception, and even if the developer didn’t handle or
define it, the code will not give a compilation error. Typically, it occurs when the user
si
gives wrong data through the interaction with the program.
Exception Meaning
Arithmetic Exception
Array Index Out Of Bounds
r Arithmetic error, such as divide-by-zero.
Array index is out-of-bounds.
ve
Exception
Array Store Exception Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
ni
Illegal Thread State Exception Requested operation not compatible with current
thread state.
Index Out Of Bounds Some type of index is out-of-bounds.
Exception
Negative Array Size Exception Array created with a negative size
m
Exception
class UncheckedExceptiondemo {
Notes
e
public static void main(String args[])
in
int a = 35;
int zero = 0;
nl
int result = a/zero;
O
System.out.println(result);
ty
}
Output
si
We have divided a by 0 but at the time of compilation it didn’t throw any exception
but at the run time it will show arithmeticexception.
r
ve
ni
class UncheckedException1 {
{
ity
System.out.println(num[7]);
}
m
In this example we try to get the item which is on 7th position, but the giver=n array
)A
has length of 6. This program will not show any compilation error but at the runt time it
will showArrayIndexOutOfBoundsException.
Output:
(c
Notes
e
in
nl
2.3.4 Writing Exception Subclasses
O
As we know Java’s built-in exceptions handle most of the common errors,
but sometimes developer will probably want to create his/her own exception types
to handle situations specific to his/her applications. This is very simple to do in java
developer just needs to declare a subclass of Exception (which is, of course, a subclass
ty
of Throwable). Your subclasses don’t need to do anything—it’s existence in the type
system is permits developer to utilize them as exceptions.
The Exception class does not declare any methods by themselves. It only inherit
si
those methods given by Throwable. Therefore, all exceptions including those that a
developer states have the methods declared by Throwable available to them. Some
common methods defined by throwable are below in table.
Method
r Description
ve
Throwable fill in Stack Trace() Returns a Throwable object that contains a
completed stack trace. This object can be
rethrown.
ni
Throwable get Cause() Returns the exception that underlies the current
exception. If there is no underlying exception, null
is returned.
String get Localized Message() Returns a localized description of the exception.
U
void print Stack Trace (Print Sends the stack trace to the specified stream.
Notes
e
Writer stream)
in
void set Stack Trace (Stack Sets the stack trace to the elements passed
Trace Element in elements[]) elements. This method is for
specialized applications not normal use.
nl
String to String() Returns a String object containing a description
of the exception This method is called by printin()
when outputting a Throwable object.
Developer want to override one or more of these methods in exception classes that
O
he/she creates.
Exception defines 4 constructors. Two were added by JDK 1.4 to support chained
exceptions.The other two are:
ty
Exception( )
Exception(String msg)
si
The first form represents an exception that has no explanation. The second form
lets developer specify an explanation of the exception.
r
Even though explaining a description when an exception is created is frequently
helpful, from time to time it is better to override toString( ). The version of toString( )
ve
defined by Throwable (and incorporatedby Exception) first shows the name of the
exception and follows by a colon, which is then followed by developers explanation. By
overriding toString( ), developer can stop prevent the exception name and colon from
being displayed. This will make a code for a cleaner output, which is pleasing in some
ni
cases.
MyExceptiondemo(int a) {
ity
detail = a;
}
)A
class ExceptionDemo1 {
e
System.out.println(“Normal exit”);
in
public static void main(String args[]) {
try {
nl
calculate(2);
calculate(22);
O
} catch (MyExceptiondemo e) {
System.out.println(“Caught “ + e);
ty
}
Output
r si
ve
Called calculate(2)
Normal exit
Called calculate(22)
ni
Caught MyException[22]
the exception. The ExceptionDemo1 class declares a method named calculate( ) that
throws a MyExceptiondemo object. The exception is thrown when calculate( )’s integer
parameter is greater than 10. The main( ) method sets up an exception handler for
ity
MyExceptiondemo, then calls calaculate( ) with a legal value (less than 10) and an
illegal one to show both paths through the code.
Chained Exceptions
Starting with Java Development Kit 1.4, a new characteristic has been put into
m
the exception subsystem: chained exceptions. The chained exception attribute allows
developer to attach another exception with an exception. This second exception defines
the reason of the first exception.
)A
developer might also want to let the calling code know that the fundamental cause was
an I/O error. Chained exceptions enable developer to handle this, and any other cases
in which layers of exceptions presents.
e
Throwable directory. Those are:
Throwable getCause( )
in
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that is within the present
nl
exception. If there is no within exception, null is returned. The initCause( ) technique
acquaintances causeExc with the invokngexception and returns a reference to the other
exception. Thus, a developer can link a cause with an exception after the exception has
been shaped. However, it can be set only once. Thus, developer can call initCause( )
O
only one time for each exception object.
ty
class ChainExceptionsDemo {
si
NullPointerException e =
// add a cause
r
ve
e.initCause(new ArithmeticException(“Reason”));
throw e;
}
ni
try {
U
demoexception();
} catch(NullPointerException e) {
System.out.println(“Caught: “ + e);
System.out.println(“Original cause: “ +
m
e.getCause());
}
)A
Output
(c
e
a cause exception, ArithmeticException. When the exception is thrown out of
demoexception( ), it is caught by main( ). There, the top-level exception is showed,
followed by the within exception, which is obtained by calling getCause( ).
in
nl
O
ty
2.3.5 Implementation of Exception Handling Mechanism.
Exception handling provides developer a powerful mechanism for scheming
complex programs that have many vibrant run-time properties. It is significant to
si
think of try, throw, and catch as unsoiled ways to tackle errors and unusual boundary
conditions in developers program’s logic. In other languages in which error return codes
are used to specify failure, Java language uses exceptions. Thus, when a method
r
cannot execute or compile, it throw an exception. This is a nice way to tackle any failure
modes.
ve
One last thing to remember Java’s exception-handling statements should not be
measured as universal mechanism for nonlocal branching. If developers do so, it will
get developer code more confusing and make it hard to maintain.
ni
Summary
)A
is made and thrown within the method that has caused the issue or error. That
method may prefer to handle the exception itself, or pass it on.
e
exceptions will not be checked at compile time by the compiler. If a program shows
an unchecked exception, and even if the developer didn’t handle or define it, the
code will not give a compilation error. Typically, it occurs when the user gives
in
wrong data through the interaction with the program.
●● Java’s exception-handling statements should not be measured as universal
nl
mechanism for nonlocal branching. If developers do so, it will get developer code
more confusing and make it hard to maintain.
Activity
O
1. Create a program using java built in exception?
ty
1. How to implement finally, throw & throws?
2. Define the fundamentals of throwing exceptions?
3. What are Java’s built-in Exceptions? And define the various types?
si
4. How a developer can write Exception Subclasses?
5. Define implementation of Exception Handling Mechanism?
Glossary
r
ve
●● JDK: Java Development Kit
Exception Meaning
Class Not Found Exception Class not found.
ni
thread.
No Such Field Exception A requested field does not exists.
No Such Method Exception A requested method does not exists.
Exception Meaning
m
e
unlocked thread.
Illegal State Exception Environment or application is in incorrect state.
in
Illegal Thread State Exception Requested operation not compatible with current
thread state.
Index Out Of Bounds Some type of index is out-of-bounds.
nl
Exception
Negative Array Size Exception Array created with a negative size
Null Pointer Exception Invalid use of a null reference.
O
Number Format Exception Invalid conversion of a string to a numeric
format.
Security Exception Attempt to violate security.
String Index Out Of Bounds Attempt to index outside the bounds of a string.
ty
Type Not Present Exception Type not found.
Unsupported Operation An unsupported operation was encountered.
Exception
si
Further Readings:
1. JavaScript: Programming Basics for Absolute Beginners, Nathan Clark
2.
r
Java: A Beginner’s Guide, Eighth Edition, Herbert Schildt
ve
3. The Java Programming Language, James Gosling and Ken Arnold
4. Java Performance, Binu John and Charlie Hunt
ni
2. compile-time
3. chained exception
ity
e
Structure:
in
3.1 Introduction to Packages
3.1.1 Constructors
nl
3.1.2 Object & Object Reference
3.1.3 Types of Constructors
O
3.1.4 Implementation of Constructors in Inheritance
3.1.5 order of invocation of constructors
3.2 Wrapper classes and String class
ty
3.2.1 Introduction to Wrapper Classes
3.2.2 Strings and Characters : Fundamentals of Characters and Strings
3.2.3 The String Class , String Operations
si
3.2.4 Data Conversion using Value Of ( ) Methods
3.3 StringBuffer class
3.3.1 r
Fundamental Concept of StringBUffer Class
ve
3.3.2 Properties of StringBuffer Class
3.3.3 Methods of StringBuffer class
3.3.4 Code snippet showing the difference between String and StringBuffer
ni
Class
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Description of Object & Object Reference
●● Different types of Constructors in Java
O
●● How to Implement Constructors in Inheritance
●● Order of invocation of constructors
Introduction
ty
It can be tedious task to initialize all of the variables in a class each time when
a developer creates an instance. Even when developer add convenience functions
like setDim( ), it would be easier and more precise to have all of the arrangement
si
done at the time the object creation. Because the specification for initialization is so
regular, Java language permits objects to initialize themselves when they are created.
This automatic initialization is done with help of the use of a constructor. A constructor
r
initializes an object instantly ahead of creation. It has the similar name as the class in
ve
which it stays and is syntactically same 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 different because they don’t have any return type,
not even the void because the inherent return type of a class’ constructor is always the
ni
3.1.1 Constructors
U
As the name indicates it is a terminology which has been use construct something
in our programs. So basically if we look deeper we forever were defining variables and
later on the code we initializing them. Java language being object-oriented developer’s
goal is to bring code closer to real-world where developer can create objects now
ity
somebody is needed to inspect the construction of these objects to get to how they are
within working.
Now here Lion is an object and developer cannot set it to 0 or null just not likely
int, char, float, etc so essentially we need to initialize these objects as per specification.
Developers can have multiple types of constructors.
)A
(c
Now you must be thinking that they were unaware of this idea still they were
Notes
e
successfully able to execute programs. The answer is simple as there is always a
default constructor which have an empty body which is automatically been called, if
there were no constructor is written that is the reason behind the successful initialization
in
of objects at the backend. Now you must be wondering if this constructor is calling itself
accordingly then why there is the requirement for multiple constructors.
nl
Let’s look an example to understand it more:
Dimensions of a Table.
O
*/
class Table {
ty
double width;
double height;
si
double depth;
Table() {
r
ve
System.out.println(“Constructing Table”);
width = 10;
height = 10;
ni
depth = 10;
}
U
double volume() {
class TableDemo {
m
double vol;
vol = myTable1.volume();
System.out.println(“Volume is “ + vol);
e
vol = myTable2.volume();
System.out.println(“Volume is “ + vol);
in
}
nl
When this program is run, it generates the following results:
Constructing Table
O
Constructing Table
Volume is 1000.0
ty
Volume is 1000.0
As you can see, both myTable1 and myTable2 were initialized by the Table( )
constructor when they were created. Since the constructor gives all Tables the same
si
dimensions, 10 by 10 by 10, both myTable1 and myTable2 will have the same volume.
The println( ) statement inside Table( ) is for the sake of understanding only. Most of the
constructors will not show anything. They will only create an object.
r
ve
ni
U
Developers can utilize this type to define objects of that type. On the other hand, getting
objects of a class is a two-step process.
1. Developer must define a variable of the class type. This variable not able to declare
an object. in its place, it is only a variable that can be used to refer to an object.
m
2. Developer must obtain an actual, physical copy of the object and allocate it to that
variable. Developer is able to do this using the new operator.
The new operator animatedly assigns (that is, allocates at run time) memory for
)A
an object and transfers a reference to it. This reference is, more or less, the location in
memory of the object assigned by new. After this reference is stored in the variable. In
Java language all class objects must be dynamically assigned.
This statement shows the two steps just described. It can also be written as :
Notes
e
table mytable;
in
The first line declares myTable as a reference to an object of type Table. After this
line executes, myTable contains the value null, which indicates that it does not yet point
nl
to an actual object. Any attempt to use myTable at this point will result in a compile-time
error. The next line allocates an actual object and assigns a reference to it to myTable.
After the second line executes, you can use myTable as if it were a Table object. But in
reality, myTable simply holds the memory address of the actual Table object.
O
ty
r si
ve
A Closer Look at new
As just explained, the new operator dynamically assigns memory for an object. It
has this universal form:
ni
In this, class-var is a variable of the class type being formed. The classsection
U
is the name of the class that is being instantiated. The class name followed by
parentheses defines the constructor for the class.
Now, you might be thinking why you don’t need to use new for data types like
ity
integers or characters. Because Java’s primitive data types are not carry out as objects.
Somewhat, they are carry out as “normal” variables. It increases the efficiency of code.
Objects have different characteristics and attribute that need Java language to treat
them in a different way than it used to treats the primitive data types. By not giving the
similar transparency to the primitive types of data that applies to objects, Java language
m
many or as few objects as it requires during the run time of developer program. Though,
since memory is limited, it is likely that new will not be able to assign location for an
object because inadequate memory exists. If this happens, a run-time exception will
occur. For the sample codes in this book, you won’t need to think about running out of
memory, but it is important to consider this possibility in real-world programs that you
(c
write.
e
Object reference variables act in a different way than you might expect when a
project takes place. For example, what do you think the following statement does?
in
Table a1 = new Table();
Table a2 = a1;
nl
You might think that a2 is being assigned a reference to a copy of the object
referred to by a1. That is, you might think that a1 and a2 refer to separate objects. But,
this would be wrong. In its place, after this statement executes, a1 and a2 will both refer
O
to the same object. The assignment of a1 to a2 did not assign any location copy any
part of the original object. It simply makes a2 refer to the same object as a1. So, any
changes made to the object through a2 will automatically affect the object to which a1 is
referring, since they are the same object. The circumstance is depicted here:
ty
r si
Though a1 and a2 both suggest to the same object, they are not connected in any
ve
other way. For example, a subsequent task to a1 will simply unhook a1 from the original
object without upsetting the object or upsetting a2. For example:
Table a2 = a1;
// ...
U
a1 = null;
Here, a1 has been set to null, but a2 still shows to the original object.
ity
m
)A
(c
e
Parameter of Object Reference
Comparison
in
Basic definition It is the instance of a class A simply memory reference
and all the elements it that points to where the
contains are based on the object is stored in memory
nl
blueprint of the class. slot.
Format for creation There is a simple format The memory reference is
for creation of an object created alongside object.
O
ClassName It is used in the format for
reference_variable = object creation and is given
new ClassName(with a variable name
parameter),
ty
Elements It contains methods and It contains a sequence of
variables based on the bits that store the address
class. of the object.
si
Mutable Objects have states and The reference variable
behaviors that can be value cannot be changed.
changed, i.e., the state of It can only remain as
the object can be changed. the data type that it was
r declared as.
ve
Virtual meaning It is a real world entity It is nothing but a variable
that holds some form of name, which has no real
memory or data meaning. It is like the
name of a person that
ni
1. Parameterized Constructors
A constructor that has parameters in it is called as parameterized constructor.
(c
While the Table( ) constructor in the previous example does initialize a Table object,
it will be not very useful if all Tables have the different dimensions. What is needed is
a way to construct Table objects of various dimensions. The simple way out is to add
Notes
e
parameters to the constructor.
in
that sets the dimensions of a Table as specified by those parameters.
nl
*/
class Table {
double width;
O
double height;
double depth;
ty
// This is the constructor for Table.
si
width = w;
height = h;
depth = d;
r
ve
}
double volume() {
ni
}
U
class TableDemo7 {
double vol;
m
vol = myTable1.volume();
)A
System.out.println(“Volume is “ + vol);
vol = myTable2.volume();
(c
System.out.println(“Volume is “ + vol);
}
Notes
e
The output from this program is shown here:
Volume is 1500.0
in
Volume is 216.0
As you can see in previous code, each object is initialized as specified in the
nl
parameters to its constructor. For example,
O
The values 5, 20, and 15 are passed to the Table( ) constructor when new creates
the object. Thus, myTable1’s copy of width, height, and depth will contain the values 5,
20, and 15, respectively.
ty
Another example for understanding Parameterized Constructors using string:
import java.io.*;
class Demo {
si
// data members of the class.
String name;
int id;
r
ve
Demo(String name, int id)
{
ni
this.name = name;
this.id = id;
}
U
// Class 2
ity
class Demo1 {
System.out.println(“DemoName :” + Demo1.name
}
(c
Output
Notes
e
Rituj and Demoid: 5
in
2. Default Constructor
A constructor that has no parameter in it is known as the default constructor or No-
argument constructor. Default constructor gives the default values to the object which
nl
are 0, null, etc. based on their type.
O
import java.io.*;
class demo
ty
int num;
String name;
si
demo()
r
System.out.println(“Constructor called”);
ve
}
}
ni
Class demo1
{
U
System.out.println(Demo1.name);
System.out.println(Demo1.num);
m
}
)A
Output
Contructor called
Null
(c
e
There are times when a method will require referring to the object that invoked it.
To permits this, Java language declares the ‘this’ keyword. ‘this’ can be used anywhere
in
inside any method to symbolize to the current object. Specifically, ‘this’keyword is
always a reference to the object on which the method was called. Developer can use
‘this’ keyword anywhere a reference to an object of the current class type is acceptable.
nl
To better understand what ‘this’ keyword refers to, consider the following version of
Table( ):
O
Table(double w, double h, double d) {
this.width = w;
ty
this.height = h;
this.depth = d;
si
}
This version of Table( ) operates exactly like the earlier version. The use of ‘this’
keyword is redundant,but perfectly correct. Inside Table( ), ‘this’ keyword will always
r
refer to the invoking object. While it isredundant in this case, ‘this’ keyword is useful in
ve
other contexts, one of which is explained in the nextsection.
the similar name insidethe same or enclosing scopes. Fascinatingly, developers can
have local variables, including formal parameters to methods, which can be related with
the names of the class’ instance variables. Still,when a local variable has the similar
U
name as of an instance variable, the local variable hides theinstance variable. This is
because in previous example of table width, height, and depth were not used as the
names of the parameters to the Table( ) constructor inside the Table class. If they
had been, then width wouldhave referred to the formal parameter, hiding the instance
ity
variable width. It is usually to easier use different name, there is another solution to this
situation. Because this lets developer to refer directly to the object, developer can use
this to resolve any name space complication that may arise between instance variables
and local variables.
m
For example, here is another version of Table( ), which uses width, height, and
depth for parameter names and then usesthis to access the instance variables by the
similar name:
)A
this.width = width;
this.height = height;
(c
this.depth = depth;
The use of ‘this’ keyword in such a case can sometimes be confusing, and some
Notes
e
developers are careful not to use any local variables and formal parameter names
thathide instance variables. Certainly, other developers believe the contrary—that it
is a goodconvention to use the same names for clarity, and use this to overcome the
in
instance variable hiding. It is a matter of choice which approach a developer adopts.
Garbage Collection
nl
Since objects are dynamically assigned by using the new operator, you might
be intersted how such objects are destroyed and their memory released for further
allocation. In some languages, such as C++, dynamically assigned objects must be
O
manually free by use of a delete operator.
ty
executes like this: when there no references to an object, that object is considered as
that it will no longer required, and the memory engaged by the object can be assigned
to someone else.
si
There is no explicit want to destroy objects as a developer required in C++.
Garbage collection only occurs sporadically (if at all) during the execution of a
developer program. It will not occur when one or more objects exist that are no longer
r
used by developer. In addition, different Java run-time implementations will take
different approaches to garbage collection, but for the most part, developer should not
ve
have to consider about it while writing his/her codes.
While implementing inheritance in a Java program, every class should have its own
constructor. Hence the execution of the constructors initiate after the object initialization.
It follows a certain series according to the class hierarchy. There can be diverse orders
U
FatherClass()
{
m
}
)A
/* Son Class */
/* Constructor */
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 183
SonClass()
Notes
e
{
in
}
nl
public class OrderofExecution1
O
/* Driver Code */
ty
{
si
new SonClass();
}
r
ve
Output
ni
class Hospital
/* Constructor */
m
Hospital()
{
)A
}
(c
{
Notes
e
/* Constructor */
Department()
in
{
nl
}
O
class Patient extends Department
ty
/* Constructor */
Patient()
si
System.out.println(“Patient constructor executed”);
}
r
ve
public class OrderofExecution2
{
ni
/* Driver Code */
new Patient();
}
m
)A
In the above code, an instance of Student class is created and it invokes the
constructors of Hospital, Department and Patient accordingly.
(c
{
Notes
e
/* Default constructor */
OrderofExecution3()
in
{
this(“CallParam”);
nl
System.out.println(“Default constructor executed.”);
O
/* Parameterized constructor */
OrderofExecution3(String str)
ty
{
si
/* Driver Code */
{
r
ve
/* Create instance of the class */
}
U
Output
ity
A child class constructor or method can use the base class constructor or method
by using the ‘super’ keyword.
)A
/* Parent Class */
class ParentClass
int a;
(c
ParentClass(int x)
{
Notes
e
a = x;
in
}
/* Child Class */
nl
class ChildClass extends ParentClass
O
int b;
ChildClass(int x, int y)
ty
{
super(x);
si
b = y;
}
r
/* Method to show value of a and b */
ve
void Show()
{
ni
}
U
{
ity
/* Driver Code */
{
m
d.Show();
}
(c
Output
Notes
e
in
In the above program, the ChildClass calls the ParentClass constructor using a
nl
‘super’ keyword that decides the order of execution of constructors.
O
When a class hierarchy is constructed, in which order are the constructors for
the classes that create up the hierarchy called. For example, given a subclass called
B and a superclass called A, is A’s constructor called before B’s, or vice versa? The
answer is that in a class hierarchy, constructors are invoked in order of derivation,
ty
from superclass to subclass. Further, since super( ) must be the first expression to
get executed in a subclass’ constructor, this order is the similar whether or not super(
) is utilized. If super( ) is not utilized, then the default or parameter less constructor of
si
every superclass will be executed. The below code exemplify when constructors are
executed:
class ABC {
ABC() {
r
ve
System.out.println(“Inside ABC’s constructor.”);
}
ni
XYZ() {
}
ity
MNO() {
m
}
)A
class CallingCons {
}
Notes
e
Output
in
Inside ABC’s constructor
nl
As we can see, the constructors are invoked in order of derivation.
If you think about it, it creates sense that constructors are executed in order
O
of derivation. Because a superclass has no information about any subclass, any
initialization it requires to carry out separate from and possibly prerequisite to any
initialization performed by the subclass. Hence, it have to be executed first.
ty
Check your Understanding
1. When developers create a class, developers are creating a new ______________ .
si
2. The new operator dynamically assigns ______________________ for an object.
3. A constructor that has parameters in it is called as __________________________
constructor.
4. r
A constructor that has no parameter in it is known as the ____________________ .
ve
5. While implementing __________________________ in a Java program, every class
should have its own constructor.
Summary
ni
giving the similar transparency to the primitive types of data that applies to objects,
Java language can carry out the primitive types of data more efficiently.
●● There are times when a method will require referring to the object that invoked
it. To permits this, Java language declares the ‘this’ keyword. ‘this’ can be used
m
anywhere inside any method to symbolize to the current object. Specifically, ‘this’
keyword is always a reference to the object on which the method was called.
Developer can use ‘this’ keyword anywhere a reference to an object of the current
)A
●● While implementing inheritance in a Java program, every class should have its
Notes
e
own constructor. Hence the execution of the constructors initiate after the object
initialization. It follows a certain series according to the class hierarchy.
in
Activity
1. Create a program using constructor inheritance in exception?
nl
Questions and exercises
1. Define Constructors?
O
2. What do you understand by Object & Object Reference?
3. Define various types of Constructors?
4. How to implement constructors in Inheritance?
ty
5. What do you mean by order of invocation of constructors?
Glossary
si
●● JDK: Java Development Kit
●● Object: It is the instance of class and all the elements it contains are based on the
blueprint of the class.
●●
r
Reference: A simple memory reference that points to where the object is stored in
ve
memory slot.
●● Constructor: Constructor is a terminology which has been use construct something
in our programs.
ni
Further Readings:
1. Constructor in Java: Constructor, Bhupendra Singh Mandloi
U
2. memory
3. parameterized
)A
4. default constructor
5. inheritance
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Basics of Characters and Strings
●● How we use string class and operation
O
●● Data Conversion using Value Of ( ) Methods
Introduction
As we know, Java language uses primitive data types (also called simple types),
ty
such as int or float, to grasp the essential data types supported by the java language.
Primitive data types, rather than objects, are utilized for these quantities just for
the sake of performance. Using objects for these values would put in an intolerable
si
overhead to even the easiest of calculations. Thus, the primitive data types are not part
of object hierarchy, and they do not able to inherit Object.
Despite the many performance advantage offered by the primitive data types, there
r
are times when a developer will need an object representation. For example, you can’t
ve
pass a primitive data type by reference to a method. Also, many of the regular data
structures implemented by Java operate on objects, which means that developer can’t
use these data structures to save the primitive data types. To tackle these (and other)
situations, Java provides a solution i.e. type wrappers, which are classes that enclose a
ni
instrument to convert primitive data types into object and object into primitive data type.
m
)A
(c
The eight classes of the java.lang package are recognized as wrapper classes in
Java.
e
Primitive Type Wrapper Class
boolean Boolean
in
char Character
byte Byte
short Short
nl
int Onteger
long Long
float Float
O
double Double
1. Character
ty
Character is a wrapper for a char. The constructor for Character is
Character(char a)
si
At this point, ‘a’ specifies the character that will be wrapped by the Character object
being formed.
To get the char value restricted in a Character object, call charValue( ), shown
here: r
ve
char charValue( )
2. Boolean
ni
Boolean(booleanboolValue)
U
Boolean(String boolString)
booleanbooleanValue( )
methods are :
byte byteValue( )
Amity Directorate of Distance & Online Education
192 Object Oriented Programming Using Java
double doubleValue( )
Notes
e
float floatValue( )
int intValue( )
in
long longValue( )
short shortValue( )
nl
For example, doubleValue( )always returns the value of an object as a double
data type, floatValue( ) always returns the value as a float data type, and so on. These
methods are used by each of the numeric type wrappers.
O
All ofthe numeric type wrappers declare the constructors that permit an object to be
constructedfrom a given assessment, or a string depiction of that value. For example,
here are the constructors declares for Integer data type:
ty
Integer(int a)
Integer(String a)
si
If a does not include an applicable numeric value, then a NumberFormatException
is thrown.
r
Program to demonstrate the numeric type wrapper:
ve
// Demonstrate a type wrapper.
class Wrapdemo {
int x = a.intValue();
U
System.out.println(x + “ “ + a);
}
ity
This program wraps the integer value 30 inside an Integer object called a. The
program then gets this value by calling intValue( ) and stores the result in x.
The procedure of extracting a value from a type wrapper is called unboxing. For
example, the code unboxes the value in ‘a’ with this expression:
int x = a.intValue();
Autoboxing
(c
Beginning with Java Development Kit 5, Java language has further added two
important attributes: autoboxing and auto-unboxing. Autoboxing is the procedure by
which a primitive data type is without human intervention encapsulated (boxed) into its
Notes
e
corresponding type wrapper whenever an object of that type is required. There is no
requirement to clearly construct an object.
in
Auto-unboxing is the procedure by which the value of an encapsulated object
without human intervention is extracted (unboxed) from a type wrapper when its value
is required. There is no requirement to call a method such as doubleValue( ).
nl
The addition of autoboxing and auto-unboxing very much streamlines the coding
of more than a few algorithms, removing the boredom of manually boxing and unboxing
values. It also helps avert errors. Additionally, it is very significant to generics, which
O
operates barely on objects
ty
reference. Java automatically constructs the object for the developer. For example: A
developer in the modern way to construct an Integer object that has the value 30:
Integer a = 30;
si
To unbox an object, simply allocates that object reference to a primitive-type
variable. For example, to unbox a, developer can use this statement:
int x = a;
r
ve
Here is the previouscode rewritten to use autoboxing/unboxing:
class AutoBoxdemo {
int i = x; // auto-unbox
U
}
ity
takes place each time an object must be transformed into a primitive data type. Thus,
autoboxing/unboxing might come when an argument is transferred to a method, or
when a value is returned by a method
)A
Example
class AutoBoxdemo {
// an int value;
e
}
in
// Pass an int to b() and assign the return value
Integer x = b(30);
nl
System.out.println(x);
O
}
Output
ty
30
si
Integer, this value is automatically boxed. Then, a( ) returns the int corresponding of
its argument. This causes b to be auto-unboxed. Next, this int value is assigned to x in
main( ), which causes the int return value to be autoboxed.
r
Autoboxing/Unboxing Occurs in Expressions
ve
Usually, autoboxing and unboxing occur whenever a conversion into an object
or froman object is necessary. This applies to expressions. Inside an expression, a
numeric object isautomatically unboxed. The outcome of the statement is reboxed, if
ni
class AutoBoxdemo {
Integer a, b;
ity
int i;
x= 100;
// The following automatically unboxes x,performs the increment, and then reboxes
++x;
// Here, x is unboxed, the expression isevaluated, and the result is reboxed and
(c
// assigned to b.
b = x+ (x/ 3);
e
// The same expression is evaluated, but the
in
i = x+ (x/ 3);
nl
}
O
The output is shown here:
ty
After ++x: 101
si
In the program, pay special attention to this line:
++x;
r
This causes the value in x to be incremented. It works like this: x is unboxed, the
ve
value is incremented, and the result is reboxed.
class AutoBoxdemo {
Integer x= 200;
Double y = 98.6;
ity
y = y + x;
}
m
Output
)A
As you can see, both the Double object y and the Integer object x participated in
the addition, and the result was reboxed and stored in y.
Integer m = 2;
Amity Directorate of Distance & Online Education
196 Object Oriented Programming Using Java
switch(m) {
Notes
e
case 1: System.out.println(“one”);
break;
in
case 2: System.out.println(“two”);
break;
nl
default: System.out.println(“error”);
O
When the switch expression is checked, m is unboxed and its int value is obtained.
As in the code show above, because of autoboxing/unboxing, using numeric objects in
a statement is both instinctive and effortless.
ty
Autoboxing/Unboxing Boolean and Character Values
As described earlier, Javalanguage also provisions wrappers for boolean and char.
si
These are Booleanand Character. Autoboxing/unboxing applies to these wrappers as
well.
For example
r
// Autoboxing/unboxing a Boolean and Character.
ve
class AutoBoxdemo {
// Autobox/unbox a boolean.
ni
Boolean x = true;
// Autobox/unbox a char.
ity
System.out.println(“ch2 is “ + ch2);
m
}
)A
Output
x is true
ch2 is x
(c
The most significant thing to notice about this code is the auto-unboxing of x
inside the if conditional statement. The conditional statement that controlsan if must
estimate to type boolean. Because of auto-unboxing, the boolean value included within
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 197
e
withthe arrival of autoboxing/unboxing, a Boolean object can be used to control an if
declaration.
in
Because of auto-unboxing, a Boolean object can now also be used to control
any of Java’s language loop expression. When a Boolean is used as the conditional
statement of a while, for, ordo/while, it is automatically unboxed into its boolean
nl
correspondent. For example, this is nowperfectly valid code:
Boolean x;
// ...
O
while(x) { // ...
ty
In addition to the convenience that it offers, autoboxing/unboxing can also help
preventerrors. For example, consider the following program:
si
// An error produced by manual unboxing.
class UnboxingError {
}
U
This code shows not the predictable value of 1000, but –24! The reason is that the
valueinsidex is manually unboxed by calling byteValue( ), which causes the truncation
of thevalue stored in x, which is 1,000. This results in the garbage value of –24 being
allocated to y. Auto-unboxing prevents this type of error because the value in x will
ity
creating a string that cannot be altered. That means once a String object has been
Notes
e
created, developer cannot modify the characters that include that string. At first, this
may seem to be a grave constraint. Though, it is not the case.
in
Developers can still perform all kinds of string operations. The difference is
that each time developer need a distorted version of an existing string, a new String
object is produced that contains the changes. The original string is left unaltered. This
nl
perspective is used because fixed, immutable strings can be executed more efficiently
than changeable ones. For those cases in which a adaptable string is preferred, Java
provides two options: StringBuffer and StringBuilder. Both hold strings that can be
customized after they are created.
O
The String Constructors
The String class supports more than a few constructors. To make an empty String,
ty
developer calls the default constructor. For example,
si
Above code will create an instance of String with no characters in it.
Developer also wants to construct strings that have initial values. The String class
gives a diversity of constructors to handle this. To create a String initialized by an array
r
of characters, use the constructor shown here:
ve
String(char chars[ ])
Example:
char chars[] = { ‘x’, ‘y’, ‘z’ };
ni
Here, start specifies the index at which the subrange begins, and numCharsdemo
specifies the number of characters to use.
Example:
m
You can build a String object that includes the same character sequence as
another String object using this constructor:
String(String strObj)
(c
e
class MakeStringdemo {
in
char demo[] = {‘B’, ‘C’, ‘A’, };
nl
String a2 = new String(a1);
System.out.println(s1);
O
System.out.println(s2);
ty
}
Output
si
BCA
BCA
String(byte asciiChars[ ])
Above in first statement asciiChars specifies the array of bytes. The second form
statement you to specify a subrange. In both these constructors, the byte-to-character
conversion is finished with the help of default character encoding of the platform. The
ity
class SubStringCons {
m
System.out.println(a1);
System.out.println(a2);
(c
}
Notes
e
Output
ABCDEF
in
CDE
nl
Characters
In Java language, the data type characters used to store characters is char. Char
in Java language is not the same as char in C or C++. In C/C++ language char is 8
O
bits wide. But in java language is not the case in Java. Instead, Java language uses
Unicode to symbolize characters. Unicode defines a fully international character set that
can represent all of the characters found in all human languages.
Java language needs 16 bits. Thus, in Java language char is a 16-bit type.
ty
The array of a char is 0 to 65,536. There are no negative chars. The normal set of
characters known as ASCII still ranges from 0 to 127 as forever, and the extensive 8-bit
character set, ISO-Latin-1, range from 0 to 255. Since Java language is designed to
si
permits code to be written for worldwide use, it makes sense that it would use Unicode
to symbolize characters. Certainly, the use of Unicode is rather inefficient for languages
such as English, French Spanish, or Japanese, whose characters can with any trouble
be contained within 8 bits. r
ve
For eg:
class CharDemo {
a2 = ‘Y’;
System.out.println(a1 + “ “ + a2);
ity
}
m
Output
a1 and a2: X Y
)A
Character Literals
Characters in Java language are indices into the Unicode character set. They are
16-bit values that can be transformed into integers and used with the integer operators,
such as the addition and subtraction operators. A literal character is symbolized inside
a pair of single quotes. All of the noticeable ASCII characters can be straight entered
(c
inside the quotes, such as ‘a’, ‘z’, and ‘@’. For characters that are not possible to enter
straight, there are quite a few escape sequences that permit developer to enter the
character developer require, such as ‘\’’ for the single-quote character itself and ‘\n’for
Notes
e
the newline character.
in
\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character (xxxx)
\’ Single quote
nl
\” Double quote
\\ Backslash
\r Carriage return
O
\n New line (also known as line feed)
\f Form feed
\t tab
ty
\b Backspace
si
The constructor for Character is declared as:
Character(char a)
r
Here, a specifies the character that will be wrapped by the Character object being
created.
ve
To get the char value restricted in a Character object, call charValue( ), as shown
below:
char charValue( )
ni
Characters also contain several static methods that categorize characters and
modify their case.
m
Method Description
static boolean isDefined(char ch) Returns true if ch is defined by Unicode.
)A
e
isjavaldentifierPart(char ch) Java identifier (other than the first character)
Otherwise, it returns false.
in
static boolean Returns true if ch is allowed as the first
isJavaldentifierStart(char ch) character of a Java identifier Otherwise, it
returns false.
nl
static boolean isLetter(char ch) Returns true if ch is a letter. Otherwise, it
returns false.
static boolean isLetterOrDigit(char Returns true if ch is a letter or a digit.
ch) Otherwise, it returns false.
O
static boolean isLowerCase(char ch) Returns true if ch is a lowercase letter.
Otherwise, it returns false.
ty
Method Description
static boolean isMirrored(char ch) Returns mirrored character is one reversed
for that displayed right-to-left
si
static boolean isSpaceChar(char Returns true Unicode Otherwise, it returns
false
static boolean TitleCase(char ch) Returns true ch Unicode Otherwise, it
r returns false.
ve
Static boolean is Returns true ch allowed identifier (other than
UnicodeldentifierPart(char ch) the character) Otherwise, it returns false.
Static boolean is Returns true ch allowed of Unicode
UnicodeldentifierStart(char identifier. Otherwise, returns false
ni
ch)
Static char to lower case (char ch) Returns lower case equivalent of ch.
Static char to Title Case (char ch) Returns title case equivalent of ch.
ity
Static char to Upper Case (char ch) Returns uppercase equivalent of ch.
if(Character.isDigit(x[y]))
System.out.println(x[y] + “ is a digit.”);
(c
if(Character.isLetter(x[y]))
System.out.println(x[y] + “ is a letter.”);
if(Character.isWhitespace(x[y]))
Notes
e
System.out.println(x[y] + “ is whitespace.”);
if(Character.isUpperCase(x[y]))
in
System.out.println(x[y] + “ is uppercase.”);
if(Character.isLowerCase(x[y]))
nl
System.out.println(x[y] + “ is lowercase.”);
O
}
ty
Output
m is a letter.
si
m is lowercase.
n is a letter.
n is lowercase.
r
ve
7 is a digit.
M is a letter.
M is uppercase.
ni
is whitespace.
Character declares two methods, forDigit( ) and digit( ), that enable developer to
convertbetween integer values and the digits they symbolize.
U
In first statmentforDigit( ) returns the digit character associated with the value of
a. The radix of the conversion is specified by rx. In second statementdigit( ) returns
the integer value associated with the given character (which is presumably a digit)
according to the specified radix.
m
int compareTo(Character a)
)A
It returns zero if the calling object and a have the same value. It returns a negative
value if the calling objects has a lower value. Else, it gives a positive value.
The String Class: String is probably the most regularly used class in Java’s
language class library. The understandable reason for this is that strings are a very
significant part of programming or coding.
The first thing to recognize about strings is that every string you generate is
Notes
e
actually an object of type String. Even string constants are in fact String objects only.
For example:
in
System.out.println(“Welcome to Java”);
nl
The second thing to recognize about strings is that objects of type String are
unchallengeable; once a String object is created, its contents cannot be changed or
modified. While this may seem like a severe restriction, but it is not:
O
ty
Strings can be created in many ways. The simplest is to use a expression like this:
si
Once developer has constructed a String object, you can utilize it anywhere that a
string is permissible. For example, this expression displays welcome to java:
r
System.out.println(welcome java);
ve
Java declares one operator for String objects: +. It is used to merge two strings.
For example, this statement
// Demonstrating Strings.
class StringDemo {
String a1 = “Welcome”;
System.out.println(a1);
System.out.println(a2);
)A
System.out.println(a3);
}
(c
Output:
Welcome
To Java
Notes
e
Welcome and to Java
in
String Literals
For each string literal in your code, Java language automatically constructs a String
object. Thus, developer can use a string literal to start a String object. For example, the
nl
following program creates two equivalent strings:
O
String s1 = new String(chars);
Because a String object is constructed for every string literal, developer can use a
ty
string literal any place developer can use a String object. For example, developer can
call methods directly on a quoted string as if it was an object reference, as the following
expression shows. It calls the length( )method on the string “xyz”. As predictable, it
si
prints “3”.
System.out.println(“abc”.length());
String Concatenation r
ve
Usually, Java language does not allow operators to be applied to String objects.
The one exclusion to this rule is the + operator, which joins two strings, driving a String
object as the result. This allows developer to combine together a series of + operations.
For example, the code concatenates three different strings:
ni
System.out.println(a);
Output:
One sensible use of string concatenation is found when developer wants to create
very long strings.in place of letting the long strings wrap around within your source
m
code, developer can break them intosmaller pieces, using the + to join them. Here is an
example:
class ConCat {
“stops this.”;
Notes
e
System.out.println(longString);
in
}
nl
String Concatenation with Other Data Types
You can concatenate strings with other types of data. For example, consider this
slightlydifferent version of the earlier example:
O
int age = 50;
System.out.println(a);
ty
In this case, age is an int rather than another String, but the output produced is the
sameas before. This is because the int value in age is automatically converted into its
si
stringrepresentation within a String object. This string is then concatenated as before.
The compilerwill convert an operand to its string equivalent whenever the other operand
of the + is aninstance of String.
r
Be careful when you mix other types of operations with string concatenation
ve
expressions,however. You might get surprising results. Consider the following:
String a = “four: “ + 2 + 2;
System.out.println(a);
ni
Output
four: 22
U
You might be thinking of output 4that you probably expected. Operator priority
causes the concatenation of“four” with the string corresponding of 2 to take place first.
This result is then joinedwiththe string alike of 2 a second time. To complete the integer
addition first, developer must use expression, like this:
ity
method valueOf( ) declaredby String. valueOf( ) is filled to capacity for all the simple
types and for type Object. For the simpletypes, valueOf( ) returns a string that includes
the human-readable corresponding of the valuewith which it is called. For objects,
valueOf( ) request to the toString( ) method on the object
Now, let’s inspect the toString( )method, because it is the process by which you
(c
can define the string demonstration forobjects of classes that you create.
e
defaultimplementation of toString( ) is rarely enough. For most important classes that a
developer create, developer want to override toString( ) and provide his/her own string
representations. Luckily,this is easy to do. The toString( ) method has below mention
in
universal form:
String toString( )
nl
To put into practice toString( ), just return a String object that includes the human-
readablestring that suitably define an object of developerclass.By overriding toString(
) for classes that developer create, developerpermits them to be fully integratedinto
O
Java’s language programming environment. For example, developer can be used in
print( ) and println( )expressionand in concatenation statements.
ty
// Override toString() for Table class.
class Table {
si
double width;
double height;
double depth;
r
ve
Table(double w, double h, double d) {
width = w;
height = h;
ni
depth = d;
}
U
class toStringDemo {
m
System.out.println(z);
(c
e
Dimensions are 10.0 by 14.0 by 12.0
in
As you can see in above code, Table’s toString( ) method is automatically called
when a Tableobjectis used in a concatenation statements or in a call to println( ).
nl
String Comparison
The String class contains a number of methods that evaluate strings or substrings
O
within strings.
ty
booleanequals(Object str)
Here, str is the String object being evaluated with the calling String object. It returns
si
true if the strings include the identical characters in the same order, and false if not.
Thecontrast is case-sensitive.
booleanequalsIgnoreCase(String a)
Now, a is the String object being checked with the calling String object. It, also,
ni
returns true if the strings includes the similar characters in the similar order, and false is
the strings are not matching.
class equalsDemo {
ity
String a1 = “Java”;
String a2 = “Java”;
m
String a3 = “Good-bye”;
String a4 = “JAVA”;
)A
a1.equals(a2));
s1.equals(a3));
(c
a1.equals(a4));
Notes
e
System.out.println(a1 + “ equalsIgnoreCase “ + a4 + “ -> “ +
a1.equalsIgnoreCase(a4));
in
}
nl
Output
Java equals Java -> true
O
Java equals Good-bye -> false
ty
Java equalsIgnoreCase JAVA -> true
regionMatches( )
si
The regionMatches( ) method evaluate a definite region inside a string with another
definite region in another string. There is an overloaded form that permits developer to
ignore case in such evaluation. Below mentions the usual forms of representation for
these two methods: r
ve
booleanregionMatches(int startdemo, String a2,
booleanregionMatches(booleanignoreCase,
ni
For both statements, startdemo specifies the Demo at which the region begins
within the calling String object. The String being evaluate is specified by a2. The Demo
at whichthecomparison will start within a2 is specified by a2Startdemo. The length
of the substring being evaluate is passed in numCheck. In the second statement, if
ity
ignoreCase is true, the case of the characters willbe not being compared. Otherwise,
case is important.
String class defines two routines that are, more or less, expert forms of
regionMatches( ).The startsWith( ) method checks whether a given String starts with
a specified string. On the other hand, endsWith( ) determines whether the String in
)A
statement ends with a particular string. Below mentions there universal forms
booleanstartsWith(String a1)
booleanendsWith(String a2)
(c
At this time, a1 and a2 is the String being checked? If the string matches the
statement, true is returned. else, falseis returned by the code. For example,
“Demojava”.endsWith(“java”)
Notes
e
and
“Demojava”.startsWith(“Demo”)
in
In this case both statement matches hence it will return true.
nl
starting point:
O
At this time, startdemo specifies the demo into which the calling string at which
point the search will need to start. For example,
“Demojava”.startsWith(“Demo”, 3)
ty
returns true.
equals( ) Versus ==
si
It is significant to recognize that the equals( ) method and the == operator
execute twounusual operations. As just explained, the equals( ) method check the
characters insidea String object. The == operator evaluates two object references to
r
check whether they referto the matching instance. The following code displays how
ve
two different String objects can include the same characters, but references for these
objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTodemo {
ni
String a1 = “Welcome”;
U
a1.equals(a2));
}
m
The variable a1 refers to the String instance created by “Welcome”. The object
referred to by a2 is created with a1 as an initializer. Thus, the inside of the two String
)A
objects are equal,but they are distinct objects. This defines that a1 and a2 do not refer
to the similar objects andare, consequently, not ==, as is shown here by the output of
the previous example:
compareTo( )
Notes
e
Over and over again, it is not adequate to simply know whether the two strings
are similar or not. For sorting programs, developer require to know which is less than,
in
equal to, or greater than the next. A string is fewer than another if it comes previous to
the other in dictionary order. A string is larger than another if it comes subsequent to the
other in dictionary order. The String method compareTo( ) solves this function. Below
nl
mention its common form:
At this time, str is the String being evaluate with the calling String. The result of the
O
evaluation is returned and is interpret, as shown here below:
Value Meaning
Less than zero The invoking string is less than str.
ty
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
si
Here is a program that sorts an array of strings. The developer uses compareTo( )
to define sort ordering for a bubble sort:
class SortStringdemo {
if(arr[a].compareTo(arr[i]) < 0) {
String m = arr[i];
ity
arr[a] = arr[i];
arr[a] = m;
}
m
System.out.println(arr[i]);
)A
}
(c
Output
Now
aid
Notes
e
all
come
in
country
for
nl
good
is
O
men
of
ty
the
the
their
si
time
to
to
r
ve
As you can see from the output of this code, compareTo( ) takes into description
uppercaseand lowercase letters. The word “Now” came out before everyone because it
starts withan uppercase letter N, which shows that it has a lower value in the character,
ni
setASCII. If developer want to ignore case dissimilarity them comparing two strings, by
using command compareToIgnoreCase( ), as shown below:
int compareToIgnoreCase(String a)
U
This method returns the same output as compareTo( ), except that case dissimilarly
are ignored. Developer might want to try substituting it into the previous program. After
doing this, “Now”will no longer be first word in output.
ity
Searching Strings
The String class gives two methods that permit developer to look for a string for a
particularcharacter or substring:
m
cases, the methods return the value at which the character or substring was found, and
–1 if the value is not found.
int indexOf(int a)
(c
int lastIndexOf(int a)
Notes
e
Here, a is the character being look for.
in
int indexOf(String a)
int lastIndexOf(String a)
nl
Here, a declares the substring.
You can declare a starting point for the search using these statements:
O
int indexOf(int a, int startIndexdemo)
ty
int indexOf(String a, int startIndexdemo)
Here, startIndexdemo specifies the index at which point the checking begins.
si
For indexOf( ), thesearch runs from startIndexdemo to the end of the string. For
lastIndexOf( ), the search runs fromstartIndexdemo to zero.
System.out.println(a);
U
System.out.println(“indexOf(t) = “ +
a.indexOf(‘b’));
ity
System.out.println(“lastIndexOf(b) = “ +
a.lastIndexOf(‘b’));
System.out.println(“indexOf(the) = “ +
m
a.indexOf(“the”));
System.out.println(“lastIndexOf(the) = “ +
a.lastIndexOf(“the”));
)A
System.out.println(“indexOf(b, 10) = “ +
a.indexOf(‘b’, 10));
System.out.println(“lastIndexOf(b, 60) = “ +
(c
a.lastIndexOf(‘b’, 60));
System.out.println(“indexOf(the, 10) = “ +
Amity Directorate of Distance & Online Education
214 Object Oriented Programming Using Java
a.indexOf(“the”, 10));
Notes
e
System.out.println(“lastIndexOf(the, 60) = “ +
a.lastIndexOf(“the”, 60));
in
}
nl
Output
Now is the time for all good men to come to the aid of their country.
O
indexOf(b) = 7
lastIndexOf(b) = 65
ty
indexOf(the) = 7
lastIndexOf(the) = 55
si
indexOf(b, 10) = 11
lastIndexOf(b, 60) = 55
indexOf(the, 10) = 44
r
ve
lastIndexOf(the, 60) = 55
Modifying a String
Because String objects are incontrovertible, at any time developer want to modify
ni
substring( )
You can extract a substring using substring( ). It has two expression. The first is
ity
Here, startIndexdemo specifies the index at which the substring will start. This
statement returns a replica of the substring that begins at startIndexdemo and runs to
the end of the calling string.
m
The second statement of substring( ) permits developer to identify both the starting
and endingindex of the substring:
Here, startIndexdemo specifies the starting index, and endIndexdemo specifies the
stopping point. The string returned includes all the characters from the start index, up
to, but not containing, the ending index.
(c
The following example in which code uses substring( ) to change all instances of
one substring withotherinside a string:
// Substring replacement.
Notes
e
class StringReplacedemo {
in
String a = “This is a Java test. This is, too.”;
String b = “is”;
nl
String c = “was”;
O
int x;
ty
System.out.println(a);
x = a.indexOf(b);
if(x != -1) {
si
result = a.substring(0, x);
result = result + c;
}
ni
} while(x != -1);
}
U
Output
from this program is shown here:
ity
concat( )
As we study early we join two string using ‘+’ but there is method as well which
helps developer do so, Developer can join two strings using concat( ), whose syntax is
shown below:
(c
String concat(String a)
Notes
e
This method creates a new object that includes the calling string with the contents
of a appended to the end. concat( ) performs the same function as +. For example look
in
at below code
class Concatdemo {
nl
public static void main(String args[])
O
a = a.concat(“Java”);
ty
// Print and display combined string
System.out.println(a);
si
}
Output r
ve
Wecome to Java
{
U
String a1 = “Mechanical-”;
String a2 = “-Engineering”;
ity
String a3 = a1.concat(a2);
System.out.println(a3);
String a4 = “-Branchl”;
m
String a5 = a3.concat(a4);
System.out.println(a5);
)A
Output
(c
Mechanical—Engineering
Mechanical—Engineering-Branch
If you notice in this example we first join two string a1 and a2 in a3 and then we
Notes
e
also join that new string a3 to a4 to produce a5.
replace( )
in
Thereplace( ) method has two statement. The first statement replaces all
occurrences of a particular character in the calling string with another character. It has
the following expression:
nl
String replace(char a, char b)
O
specified by b.
ty
Output of the above statement will be ‘Hewwo’ word l is replaced by w.
The second statement of replace( ) change one character sequence with another. It
si
has thisgeneralstatement:
Example of replace r
ve
1. String replace()
public class repdemo1 {
ni
// Initialising String
System.out.println(Str.replace(‘w’, ‘A’));
ity
System.out.println(Str.replace(‘a’, ‘D’));
m
}
)A
Output
After replacing all w with A: Aelcome to Aorld of Java
2. String replaceAll()
public class rep2 {
e
String a = new String(“Welcome to Java”);
System.out.print(“Original String : “ );
in
System.out.println(a);
nl
System.out.print(“After replacing regex with replace_str : “ );
System.out.println(Str.replaceAll(“(.*)Java(.*)”, “OOPS”));
O
}
ty
Output
Original String : Welcome to Java
si
After replacing regex with replace_str :OOPS
3. String replaceFirst()
public class repdemo3 { r
ve
public static void main(String args[]) {
// Initialising String
System.out.print(“Original String : “ );
System.out.println(a);
U
System.out.println(Str.replaceFirst(“Java”, “World”));
}
ity
Output
m
After replacing 1st occurrence of regex with replace_str : Welcome to World for
Java
)A
trim( )
The trim( ) method returns a replica of the calling string from which any leading and
stragglingwhitespace has been removed. It has this common form:
(c
String trim( )
Here is an example:
e
This puts the string “Hello World” into a.
The trim( ) method is reasonably helpful when developer process user commands.
in
For example, the following code prompts the user to enter name of a state and then
displays that state’scapital. It uses trim( ) to remove any leading or trailing whitespace
that may have unintentionally been given by the user.
nl
import java.io.*;
class UseTrim {
O
public static void main(String args[])
throws IOException
ty
{
BufferedReader a = new
BufferedReader(aInputStreamReader(System.in));
si
String b;
b = a.readLine();
ni
if(b.equals(“Illinois”))
System.out.println(“Capital is Springfield.”);
U
else if(b.equals(“Missouri”))
else if(b.equals(“California”))
System.out.println(“Capital is Sacramento.”);
else if(b.equals(“Washington”))
m
System.out.println(“Capital is Olympia.”);
// ...
)A
} while(!b.equals(“stop”));
}
(c
Method Description
Notes
e
int code Point At (int) Retums the Unicode code point at the location
specified by L Added by J2SE 5.
in
int code Point Before (int i) Returns the Unicode code point at the location that
precedes that specified by . Added by J2SE 5.
int code Point Count (int Returns the number of code points in the portion of
nl
start, int end) the invoking String that are between start and end-1
Added by J2SE 5.
boolean contains (Char Returns true if the invoking object contains the string
O
Sequence str) specified by str Retums false, otherwise, Added by
J2SE 5.
boolean content Equals Returns true if the invoking string contains the same
(Char Sequence str) string as str. Otherwise, returns false. Added by J2SE
ty
5.
boolean content Equals Retums true if the invoking string contains the same
(String Buffer str) sining as str. Otherwise returns false.
si
static String format (String Returns a string formatted as specified by fmtstr. (See
fmtstr Object args) Chapter 18 for details on formatting) Added by J2SE 5.
static String format(Locale Returns a string formatted as specified by fmtstr.
loc, String fmtstr Object
args)
r Formatting is governed by the locale specified by loc.
(See Chapter 18 for details on formatting.) Added by
ve
J2SE 5.
boolean matches (string reg Returns true if the invoking string matches the regular
Exp) expression passed in regExp. Otherwise returns false
int offset By Code Points Returns the index with the invoking string that is num
ni
(int start, int num) code points beyond the starting index specified by
start. Added by J2SE 5.
String Retums a string in which the first substring that
U
replace First (String reg matches the regular expression specified by regExp is
Exp, String new Str replaced by newStr
String replace All (String reg Returns a string in which all substrings that match the
Exp String newStr) regular expression specified by regExp are replaced
ity
by newStr
Method Description
String [ ] split (String Decomposes the invoking string into parts and returns an
m
reg Exp) array that contains the result. Each part is delimited by the
regular expression passed in regExp
String [ ] split (String Decomposes the invoking string into parts and returns an
)A
reg Exp, int max) array that contains the result. Each part is delimited by the
regular expression passed in regExp. The number of pieces
is specified by max. If max is negative, then the invoking
string is fully decomposed. Otherwise, if max contains a
nonzero value, the last entry in the returned array contains
(c
e
Sequence (int start startindex and stopping at stopindex This method is required
index, int stop index) by the CharSequence interface, which is now implemented
in
by String.
nl
The valueOf( ) method change data from its interior format into a human-readable
statements. It is a static method that is overloaded inside String for all of Java’s
language built-in types so that each type can be transformed properly into a string.
valueOf( ) is also overloaded for type Object, so an object of any class type developer
O
can construct also be used as an argument. Few statements to represent Value of()
ty
static String valueOf(long b)
si
As we studied earlier, valueOf( ) is required when a string demonstration of
some other type of data is looked-for—example, during concatenation operations.
r
Developer can invoke this method directly with any data type and get a reasonable
String expression. All of the simple types are transformed to their common String
ve
representation. Any object that developer pass to valueOf( ) will return the outcome of
a call to the object’s toString( ) method. Actually, developer could just call toString( )
straight and get the same outcome.
ni
For majority of arrays, valueOf( ) returns a quite cryptic string, which define that it
is an array of some type. For arrays of char, however, a String object is constructed that
includes the characters in the char array. There is a special description of valueOf( )
that permits developer to specify a subset of a char array. It can be represented as:
U
Here, abc is the array that holds the characters, startIndexdemo is the index into
ity
the array of characters at which the desired substring begins, and abcChars specifies
the length of the substring.
{
)A
int i = 90;
double f = 3.56789;
String a = “91”;
(c
e
System.out.println(sample);
System.out.println(sample + i);
in
sample = String.valueOf(f);
System.out.println(sample);
nl
System.out.println(a + sample);
O
}
Output
ty
90
9091
si
3.56789
913.56789
_______________________________ .
Summary
●● A Wrapper class is a class whose object wraps or encapsulates primitive data
types. When we create an object to a wrapper class, it includes a field and in this
m
●● Java language has different methods to compare two strings, search for a
Notes
e
substring, concatenate two strings, and changes the case of letters within a string.
●● Characters in Java language are indices into the Unicode character set. They
in
are 16-bit values that can be transformed into integers and used with the integer
operators, such as the addition and subtraction operators. A literal character is
symbolized inside a pair of single quotes.
nl
●● The valueOf( ) method change data from its interior format into a human-readable
statements. It is a static method that is overloaded inside String for all of Java’s
language built-in types so that each type can be transformed properly into a string.
O
Activity
1. Create a program using Value Of ( ) Methods?
ty
Questions and exercises
1. What do you mean by Wrapper Classes
2. Define Strings and Characters?
si
3. Define Fundamentals of Characters and Strings?
4. Define The String Class?
5. What are String Operations? r
ve
6. What do you mean by Data Conversion using Value Of ( ) Methods ,
Glossary
●● The String Class: String is probably the most regularly used class in Java’s
ni
language class library. The understandable reason for this is that strings are a very
significant part of programming or coding.
U
char Character
byte Byte
short Short
int Onteger
m
long Long
float Float
double Double
)A
(c
Further Readings:
Notes
e
1. Fundamentals of Java Programming, Mitsunori Ogihara
2. Fundamentals of Java Programming, Ogihara Mitsunori
in
3. Think Java, Downey Allen B
4. Java Performance, Binu John and Charlie Hunt
nl
Check Your Understanding:
Answers
O
1. Object and object
2. wrapper classes
3. autoboxing/unboxing
ty
4. characters
5. 8 bits
si
6. StringBuffer
r
ve
ni
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● What are the Properties of StringBufferClass
●● What are the Methods used in forStringBufferclass
O
●● Difference between String and StringBuffer Class with code snippet
Introduction
StringBuffer is a examine class of String that provides a great deal of the
ty
functionality of strings. As you know, String definess fixed-length, unassailable
character sequence. On the contrary, StringBuffer shows growable and writeable
character sequences. StringBuffer might contain characters and substrings that
si
are entered in the middle or appended to the end. StringBuffer will without human
intervention grow to make room for such additions and frequently has more characters
preassigned than are actually required, to permit room for growth. Java languages uses
r
both classes heavily, but many developers deal only with String and let Java language
ve
influence StringBuffers behind the scenes by using the overloaded + operator.
mutable (modifiable) String objects. The StringBuffer class in Java is similar as String
class except it is mutable i.e. it can be altered.
U
ity
m
StringBuffer Constructors
)A
●● StringBuffer( )
●● StringBuffer(int size)
(c
●● StringBuffer(String str)
●● StringBuffer(CharSequence chars)
●● The default constructor means the first statement (the one with no parameters)
Notes
e
holds room for 16 characters without redistribution.
●● The second expression accepts an integer argument that clearly sets the size of
in
the buffer.
●● The third expression accepts a String argument that sets the first contents of the
StringBuffer object and saves room for 16 more characters without reallocation.
nl
StringBuffer assign room for 16 additional characters when no explicit buffer length
is needed, because reallocation is a expensive process with respect to time. Also,
regular reallocations can fragment memory. By assigning room for a few extra
O
characters, StringBuffer lowers the number of reallocations that occur.
●● The fourth constructor creates an object that includes the character sequence
enclosed in chars.
ty
3.3.2 Properties of StringBuffer Class
java.lang.StringBuffer - A class symbolize a mutable sequence of characters stored
in an interior buffer. A request of StringBuffer has 3 important properties:
si
●● Buffer: The storage where the characters are stored.
●● Capacity: The size of the storage.
●●
r
Length: The number of characters stored in the buffer.
ve
ni
U
ity
m
)A
Replace( )
Developer can replace one group of characters with another
(c
The substring being replaced is specified by the indexes Start and End. Thus,
Notes
e
the substring at Start through End1 is replaced. The replacement string is passed in –
a.The resulting StringBuffer object is returned.
in
Code demonstrate the uses of replace()
class replaceDemo {
nl
public static void main(String args[]) {
a.replace(5, 7, “is”);
O
System.out.println(“After replace: “ + a);
ty
}
si
After replace: This is a Java.
ensureCapacity( )
r
If you want to pre assign a room for a certain number of characters after a
ve
StringBuffer has been cretated, developer can use ensureCapacity( ) to set the range of
the buffer. This is useful if developer know in advance that you will be includinga large
number of small strings to aStringBuffer. ensureCapacity( )can be expressed as:
The current length of a StringBuffer can be found via the length( ) method, while
the totalowned capacity can be found through the capacity( ) method.
int length( )
ity
int capacity( )
class StringBufferDemo {
System.out.println(“Character = “ + a);
System.out.println(“length = “ + a.length());
System.out.println(“capacity = “ + sb.capacity());
(c
}
Amity Directorate of Distance & Online Education
228 Object Oriented Programming Using Java
Output
Notes
e
character = Welcome
length = 7
in
capacity = 23
Since a is initialized with the string “Hello” when it is constructed, its length is 7. Its
nl
capacity is 23 because room for 16 additional characters is automatically added by the
strigbuffer.
O
setLength( )
To set the length of the buffer inside a StringBuffer object, developer can use
setLength( ). Itscan be expressed as:
ty
void setLength(int length)
Here, length defines the length of the buffer. This value has to be nonnegative.
When developer extend the size of the buffer, null characters are supplementary added
si
to the end of the current buffer. If developer call setLength( ) with a value which is less
than the current value returned bylength( ), then the characters will be saved further
than the new length will be lost.
For charAt( ), abc specifies the index of the character need to be obtained. For
setCharAt( ),abc specifies the index of the character need to be set, and x defines the
new value of that character. For both statements, abc must be nonnegative and must
not defines a locationbeyond the end of the buffer.
ity
class setCharAtDemo {
m
sb.setCharAt(1, ‘i’);
(c
sb.setLength(2);
e
}
in
Output:
buffer before = Hello
nl
charAt(1) before = e
buffer after = Hi
O
charAt(1) after = i
getChars( )
ty
To create replica of a substring using aStringBuffer into an array, developer uses
the getChars( ) method. It can be represented as:
si
int targetStartdemo)
Here, Start specifies the index of the starting of the substring, and Endspecifiesan
r
index that is one past the end of the defined substring. This states that the substring
ve
includes the characters from Start through End–1. The array that will collect the
characters is specified by collect. The index inside target at which the substring will be
clichédis conceded in targetStartdemo. It must need to be taken care to assure that
the collect array is large enough tograsp the number of characters in the specified
ni
substring.
append( )
U
The append( ) method concatenates the string expression of any other type of data
to the end of the callingStringBuffer object. It has more than a few overloaded versions.
Here are a fewof its expression:
ity
StringBufferappend(String str)
StringBufferappend(int num)
StringBufferappend(Object obj)
m
String.valueOf( ) is called for each parameter to obtain its string depiction. The
output is appended to the current StringBuffer object. The buffer itself is returned by
eachdescription of append( ). This permits following calls to be chained together, as
shown in the below code:
)A
// Demonstrate append().
class appendDemo {
String a;
int i = 45;
Amity Directorate of Distance & Online Education
230 Object Oriented Programming Using Java
e
a = a.append(“i = “).append(i).append(“!”).toString();
System.out.println(a);
in
}
nl
Output
i = 45!
O
The append( ) method is most frequently called when the + operator is being used
on String objects. Java language automatically changes it to a String instance into
parallel operations on aStringBuffer instance. Therefore, a concatenation calls append(
ty
) on a StringBufferobject.After the concatenation has been executed, the compiler
inserts a call to toString( ) to transform the modifiable StringBuffer back into a constant
String.
si
All of this may seem irrationally complex. Why not just have only one string class
and have it act more or less likeStringBuffer? The counter is performance. There are
a lot of optimizations that the Java runtime can make significant that String objects
r
are immutable. Fortunately, Java language hides most of the difficulty of conversion
ve
between Strings and StringBuffers. Actually, a lot of developer will never feel the
requirement to use StringBuffer directly and will be able to represent most operationsin
terms of the + operator on String variables.
insert( )
ni
The insert( ) method inserts one string into other string. It is overloaded to
recognize values of all the simple types, plus Strings, Objects, and CharSequences.
Like append( ), it calls String.valueOf( ) to attain the string representation of the value it
U
is called with. This string is then inserted into the callingStringBuffer object. These are a
few of its representation:
Here, abc specifies the index at which point the string will be inserted into the
m
class insertDemo {
System.out.println(a);
}
Notes
e
}
Output:
in
Welcome to java
nl
reverse( )
Developers can change the direction of the characters inside a StringBuffer object
using reverse( ), It represent as:
O
StringBufferreverse()
ty
// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
si
public static void main(String args[]) {
System.out.println(a);
r
ve
a.reverse();
System.out.println(a);
ni
}
U
Output
uvwxyz
zyxwvu
ity
StringBufferdeleteCharAt(int loc)
)A
The delete( ) method deletes a sequence of characters from the calling object.
Here, Start specifies the index of the first character which needs to be remove, and End
specifies an index one past the last character that has to be remove. Therefore, the
substring deleted runs from Start to End–1. The outputStringBuffer object is returned.
ThedeleteCharAt( ) method deletes the character at the index particular by loc. It
(c
class deleteDemo {
Notes
e
public static void main(String args[]) {
in
a.delete(4, 7);
nl
a.deleteCharAt(0);
O
}
ty
Output:
After delete: This a exam.
si
After deleteCharAt: his a exam.
substring( )
r
Developer can obtain a part of a StringBuffer by calling substring( ). It has the
following two expressions:
ve
String substring(int start)
The first form returns the substring that starts at start and runs to the end of
thecallingStringBuffer object. The second expression returns the substring that starts at
start and runs through End–1.
U
class IndexOfDemo {
int b;
)A
b = a.indexOf(“one”);
B = a.lastIndexOf(“one”);
}
Notes
e
Output
First index: 0
in
Last index: 8
nl
Additional StringBuffer Methods
In addition to those methods we just discussed, StringBuffer includes several
others methods as well. They are briefed in the following table:
O
Method Description
int offset By Code Points Returns the index with the invoking string that is num
(int start, int num) code points beyond the starting index specified by start.
ty
Added by J2SE 5
Char Sequence Returns a substring of the invoking string, beginning at
subsequence (int start startindex and stopping at stopindex. This method is
index, int stop Index) required by the CharSequence interface, which is now
si
implemented by StringBuffer
void trimTo Size() Reduces the size of the character buffer for the invoking
object to exactly fit the current contents. Added by J2SE
5. r
ve
Method Description
StringBuffer Appends a Unicode code point to the end of the invoking
appendCodePoint(int object. A reference to the object is returned. Added by
ni
ch) J2SE 5.
int codePointAt(int) Returns the Unicode code point at the location specified
by I. Added by J2SE 5.
U
int codePointBefore(int i) Returns the Unicode code point at the location that
precedes that specified by I. Added by J2SE 5.
int codePointCount(int Returns the number of code points in the portion of the
start, int end) invoking String that are between start and end-1. Added
ity
by J2SE 5.
int indexOf(String str Searches the invoking StringBuffer for the first
occurrence of str. Returns the index of the match, or -1 if
no match is found.
m
int indexOf(String str, int Searches the invoking StringBuffer for the first
startindex) occurrence of str, beginning at startindex Returns the
index of the match, or -1 if no match is found.
)A
int lastindexOf(String str) Searches the invoking StringBuffer for the last
occurrence of str Returns the index of the match, or -1 if
no match is found
int lastindexOf(String str, Searches the invoking StringBuffer for the last
int startindex) occurrence of str beginning at startindex. Returns the
(c
e
sequence of characters. Since the String Class in Java creates an unchallengeable
sequence of characters, the StringBuilder class gives an option to String Class, as
it constructs a mutable sequence of characters. The function of StringBuilder is very
in
much related to the StringBuffer class, as both of them provide a substitute to String
Class by making a changeable sequence of characters.
nl
The StringBuilder class provides no assurance of synchronization whereas the
StringBuffer class provides synchronization. So this class is designed for use as a drop-
in substitute for StringBuffer in places where the StringBuffer was being utlized by a
single thread. Wherever possible, it is recommended that this class be used in first
O
choice to StringBuffer as it will be quicker under most use cases.
ty
public final class StringBuilder
extends Object
si
Constructors in Java StringBuilder:
r
ve
ni
U
Stringbuilder example:
ity
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
throws Exception
)A
a.append(“ABC”);
System.out.println(“String = “+ a.toString());
(c
System.out.println(“String1 = “ + a1.toString());
Notes
e
StringBuilder a2 = new StringBuilder(10);
in
StringBuilder a3 = new StringBuilder(a1.toString());
System.out.println(“String3 = “ + a3.toString());
nl
}
O
Output
String = ABC
ty
String1 = XXXXYYYYZZZZ
String2 capacity = 10
si
String3 = XXXXYYYYZZZZ
Method r Description
ve
public String Builder append It is used to append the specified string with this
(String s) string The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.
ni
public String Builder insert It is used to insert the specified string with this string
(int offset, String s) at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
U
public String Builder replace It is used to replace the string from specified
(int startindex, int endIndex, startindex and endindex.
String str)
ity
public String Builder delete It is used to delete the string from specified
(int start index, int end index) startindex and endIndex
public String Builder reverse() It is used to reverse the string
public int capacity() It is used to return the current capacity
public void ensure Capacity It is used to ensure the capacity at least equal to the
m
public int length() It is used to return the length of the string ie total
number of characters
public String substring (int It is used to return the substring from the specified
begin Index) beginIndex
(c
public String substring (int It is used to return the substring from the specified
beginindex, int endindex) beginindex and endindex.
e
String String Buffer
in
The String class is immutable. The StringBuffer class is mutable.
String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too many memory when we concatenate t strings.
nl
strings because every time it creates new
instance.
String class overrides the equals() method StringBuffer class doesn’t override
O
of Object class So you can compare equals() method of Object class.
the contents of two strings by equals()
method.
String class is slower while performing StringBuffer class is faster while
ty
concatenation operation. performing concatenation operation..
String class uses String constant pool. StringBuffer uses Heap memory
r si
ve
ni
U
String a = “Java”;
m
a = a + “Tpoint”;
)A
return a;
}
(c
e
b.append(“Tpoint”);
in
return b.toString();
nl
public static void main(String[] args){
O
concatString();
ty
startTime = System.currentTimeMillis();
concatStringBuffer();
si
System.out.println(“Time taken by ConcatingwithStringBuffer: “+(System.
currentTimeMillis()-startTime)+”ms”);
}
r
ve
}
Output:
Time taken by Concating with String: 578ms
ni
String a=”Java”;
m
System.out.println(a.hashCode());
a=a+”tpoint”;
)A
System.out.println(a.hashCode());
System.out.println(b.hashCode());
b.append(“tpoint”);
Notes
e
System.out.println(b.hashCode());
in
}
nl
Output
Hashcode test of String:
3254818
O
229541438
ty
118352462
118352462
si
Check your Understanding
1. Java language StringBuffer class is used when a developer wants to create mutable
(modifiable) ____________________ objects.
2.
r
The number of characters stored in the buffer is known as __________________ .
ve
3. To create replica of a substring using aStringBuffer into an array, developer uses the
______________________ method.
4. The append( ) method is most frequently called when the _________________ is
ni
Summary
●● StringBuffer is a peer class of String that provides a lot of string functionality.
ity
●● StringBuffer will automatically expand to make room for such additions, and it
frequently has more characters preallocated than are actually required to allow for
)A
growth.
●● The insert( ) method inserts one string into other string. It is overloaded
to recognize values of all the simple types, plus Strings, Objects, and
CharSequences. Like append( ), it calls String.valueOf( ) to attain the string
representation of the value it is called with. This string is then inserted into the
(c
callingStringBuffer object.
●● The function of StringBuilder is very much related to the StringBuffer class, as both
Notes
e
of them provide a substitute to String Class by making a changeable sequence of
characters.
in
●● The StringBuilder class provides no assurance of synchronization whereas the
StringBuffer class provides synchronization. So this class is designed for use as
a drop-in substitute for StringBuffer in places where the StringBuffer was being
nl
utlized by a single thread.
Activity
1. Create a same program using two different class methods stringbuffer and
O
stringbuilder?
ty
1. Define the Concept of StringBuffer Class?
2. What are the properties of StringBuffer Class?
3. What are the methods of StringBuffer class?
si
4. What are the difference between String and StringBuffer Class?
Glossary
●●
r
java.lang.StringBuffer - A class symbolize a mutable sequence of characters
ve
stored in an interior buffer. A request of StringBuffer has 3 important properties:
◌◌ Buffer: The storage where the characters are stored.
◌◌ Capacity: The size of the storage.
ni
Further Readings:
1. Fundamentals of Java Programming, Mitsunori Ogihara
2. Fundamentals of Java Programming, Ogihara Mitsunori
3. Think Java, Downey Allen B
(c
e
Check Your Understanding:
in
Answers
1. String
2. Length
nl
3. getChars( )
4. + operator
O
5. delete( ) deleteCharAt( )
ty
r si
ve
ni
U
ity
m
)A
(c
e
Structure:
in
4.1 Introduction to Interface
4.1.1 Introduction to Interface
nl
4.1.2 Code snippet showing implementation of Interface
4.1.3 Reference variable in interface
O
4.1.4 Extending Interface
4.2 Interfcae Methods
4.2.1 Type of Methods in interface
ty
4.2.2 Default method in interface
4.2.3 Static methods in interface
4.2.4 Constant variables in interface
si
4.3 Multithreading
4.3.1 Introduction to Multithreading
4.3.2 Concept of Thread in Multithreading r
ve
4.3.3 Lifecycle of Thread
4.3.4 Implementing a Thread
4.3.5 Thread vs Runnable method of creating thread
ni
e
Objectives
in
At the end of this unit, you will be able to understand:
●● What is Interface
nl
●● Code snippet showing implementation of Interface
●● What are Reference variable in interface
O
●● What is Extending Interface
Introduction
In general, an interface is a tool or a system that unrelated entities use to work
ty
together. To simplify this, a TV remote is an interface among you and a television set,
the English language is an interface between two people, and the etiquette of behavior
compulsory in the military is the interface among people of different ranks.
si
Within the Java programming language, an interface is a kind, just as a class is
a type. Like a class, an interface declares methods. Unlike a class, an interface never
executes methods; instead, classes that implement the interface execute the methods
r
declared by the interface. A class can employ several interfaces.
ve
A number of object-oriented programming languages, such as C++, let a class to
extend two or more superclasses. This is known as multiple inheritance. In the Figure
below, for example, class E is shown as have mutually class A and class B as direct
superclasses, while class F has three straight superclasses.
ni
U
ity
language does have an attribute that can be utilized to achieve many of the similar
goals as multiple inheritance is known interfaces.
e
be only abstract methods in the Java language interface, not method body. It is utilized
to accomplish abstraction and multiple inheritances in Java language.
in
To implement an interface, a category must create the entire set of methods
defined by the interface. However, each class is liberal to determine the small print of its
own implementation. By assigning the interface keyword, Java allows you to completely
nl
utilize the “one interface, multiple methods” aspect of polymorphism.
O
an blank body and are public and all objects are public, fixed and final by default. A
class that employs an interface must implement all the methods defined in the interface.
Interface can be expressed as:
ty
interface <interface_name> {
si
// by default.
}
r
ve
ni
U
ity
Interfaces are utilized pervasively in real Java language code. Not every class
is connected with an interface, but there are a few superior reasons to transport an
interface into the picture.
m
The point of all this is that, though interfaces are not classes, they are somewhat
very same. An interface is very similar to an abstract class, i.e., a class that can never
be utilized for creatingobjects, but can be used as a foundation for making subclasses.
)A
The subroutinesin an interface are abstract methods, which must be executed in any
existing class that employ the interface. And as with abstract classes, even though you
can’t createanobject from an interface, developer can define a variable whose type is
given by the interface. Forexample, if Drawabledemo is an interface, and if Line and
FilledCircledemo are classes that implementDrawabledemo:
(c
Drawabledemofigure;
e
figure = new FilledCircledemo(); // Now, figure refers to an object
// of class FilledCircle.
in
figure.draw(a); // calls draw() method from class FilledCircle
A variable of type Drawable demo can refer to any object of any class that
nl
implements the Drawable demo interface. A statement like figure.draw(a), above, is
permissible because figure is of type Drawabledemo,and any Drawable object has a
draw() method. So, anything object figure symbolize to, thatobject have to have a
O
draw() method.
ty
si
●● Interfaces store condition and details about a class. They include information
r
about the class behavior.
ve
●● It includes all the functions that a class can act upon. For example an interface for
a car would have to have break (), accelerate (), turn () methods.
●● A class whilst executing an interface must realize all the methods within the
interface. Nevertheless, it can choose not to employ all the methods if the class
ni
itself is abstract.
●● One of the well-liked interfaces in Java is the Comparator interface which is helpful
for organization containers.
U
ity
m
)A
(c
Every implementation class can encompass its own implementation for abstract
methods specified in the interface as shown in the below figure.
Notes
e
in
nl
O
ty
While the execution classes will have all the methods with a body, it is promising to
construct an instance of implementation classes.
si
Why developer uses interface:
There are several reasons for using interfaces, we have sum them in below five
points:
1. r
Architect-level people construct interfaces, and then it is given to programmers for
ve
writing classes by executing interfaces given.
2. Using interfaces is the optimal way to take away developer’s project’s API to some
other projects. In other words, developers can provide interface methods to the
third-party vendors for their execution. To take example from now days, that bank
ni
// A simple interface
interface I1
)A
void display();
{
Notes
e
public void display()
in
System.out.println(“Welcome”);
nl
public static void main (String[] args)
O
TestClassi = new TestClass();
i.display();
ty
System.out.println(x);
si
Output:
Welcome
r
ve
10
Let’s consider the example of vehicles like bicycle, car, bike, they have common
characteristics. So developer makes an interface and put all these common attributes.
And allows Bicycle, Bike, car etc executes all these functionalities in their personal
ni
import java.io.*;
U
interface Vechiledemo {
int s;
int g;
)A
g = newg;
}
(c
s = s + increment;
}
Notes
e
public void putBrakes(int decrement){
s = s - decrement;
in
}
nl
System.out.println(“speed: “ + s
+ “ gear: “ + g);
O
}
ty
class Bike implements Vechiledemo {
int sb;
int gb;
public void modifyGear(int nG){
gb = nG;
r si
ve
}
sb = sb + increment;
U
sb = sb - decrement;
System.out.println(“speed: “ + sb
+ “ gear: “ + gb);
)A
class XYZ {
(c
e
// doing some operations
in
bicycle.modifyGear(2);
bicycle.increasespped(3);
nl
bicycle.putBrakes(1);
O
bicycle.printStates();
ty
Bike bike = new Bike();
bike.modifyGear(1);
bike.increasespped(4);
si
bike.putBrakes(3);
r
bike.printStates();
ve
}
}
ni
Output:
Bicycle present state :
U
speed: 2 gear: 2
speed: 1 gear: 1
ity
Runnable r;
r = new Thread();
The Java language compiler does not lets a value to be allocated to a variable
(c
defining using an interface type if not the compiler can be sure that the object
referenced by the value implements the particular interface. Invoking a reference
variable to an interface type permits the variable to be allocated to that interface type,
because the invoke operation provides its own assurance that the object implements
Notes
e
the specific interface. Except the compiler is able to establish the actual class of the
object that will be referenced at execution time, the cast produces code that verifies
at execution time that the object being invoke really does employed the specified
in
interface. At execution time, if the object being invoke does not employ the needed
interface, a ClassCastException is thrown.
nl
4.1.4 Extending Interface
In java language, an interface can extend to another interface. When an interface
O
wants to extend to another interface, developer requires to use keyword extends. The
interface that extends another interface has its own members and all the members
declared in its parent interface too. The class which employ a child interface requires
giving code for the methods declared in both child and parent interfaces, or else, it
ty
needs to be declared as abstract class.
r si
ve
ni
U
ity
m
1. Developer can declare all the constants into one interface and methods in other
interface. Developer can use constants in classes where methods are not necessary.
Letsse how developer can achieve this.
interface XYZ
(c
int x = 10;
int y = 20;
Notes
e
}
in
interface Abc extends XYZ
nl
{
void show();
O
}
In this the interface Abc will encapsulate both the constant variable x & y.
ty
2. Developer can also extend various interfaces to a single interface. Its syntax will look
like this
si
interface ABC
int x = 20; r
ve
int y = 30;
void show();
U
........
}
m
interfaceParentInterface{
voidparentMethod();
)A
interfaceChildInterfaceextendsParentInterface{
(c
voidchildMethod();
}
Notes
e
classImplementingClassimplementsChildInterface{
publicvoidchildMethod(){
in
System.out.println(“Welcome to Java!!”);
nl
publicvoidparentMethod(){
System.out.println(“Interface extend!”);
O
}
ty
publicclassExtendingAnInterface{
publicstaticvoidmain(String[]args){
ImplementingClassobj=newImplementingClass();
si
obj.childMethod();
obj.parentMethod();
}
r
ve
}
Output
ni
Welcome to java!!
Interface extend!
U
keyword ________________________ .
Summary
●● An interface is a kind, just as a class is a type. Like a class, an interface declares
)A
defined by the interface. However, each class is liberal to determine the small print
of its own implementation. By assigning the interface keyword, Java allows you to
e
●● Interfaces store condition and details about a class. They include information
about the class behavior.
in
●● The Java language compiler does not lets a value to be allocated to a variable
defining using an interface type if not the compiler can be sure that the object
referenced by the value implements the particular interface.
nl
●● The interface that extends another interface has its own members and all the
members declared in its parent interface too. The class which employ a child
interface requires giving code for the methods declared in both child and parent
O
interfaces, or else, it needs to be declared as abstract class.
Activity
ty
1. Create a program using extended interface?
si
2. How to implement Interface?
3. What do you mean by reference variable in interface?
4. How to Extend Interface?r
ve
Glossary
●● Reference: A reference variable declared using an interface name as its kind can
only reference instances of classes that employ that interface.
ni
Further Readings:
1. The Java Native Interface: Programmer’s Guide and Specification, Sheng
Liang
ity
Answers
1. abstraction
2. interface
3. Thread
(c
4. extends
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● What is Default method in interface
●● What are Static methods in interface
O
●● What are Constant variables in interface
Introduction
Designing interfaces have forever been a tough task because if we want to add
ty
supplementary methods in the interfaces, it will need change in all the employing
classes. As interface grows old, the number of classes employing it might develop to
an amount that it’s not possible to extend interfaces. That’s why when designing an
si
application, most of the frameworks give a base employing class and then we expand it
and override methods that are appropriate for our application.
Before Java 8, interfaces possibly will have only abstract methods. The execution
of these methods has to be given in a separate class. So, if a new method is needed
to be added in an interface, then its execution code has to be provided in the class
)A
implementing the identical interface. To overcome this problem, Java 8 has introduced
the concept of default methods which permits the interfaces to have methods with
execution without disturbing the classes that execute the interface.
in the implementation class. Default methods are also called as defender methods or
virtual extension methods.
Notes
e
in
Example for default interface
nl
interface TestInterface
O
public void square(int x);
// default method
ty
{
si
}
r
class TestClass implements TestInterface
ve
{
System.out.println(x*x);
U
b.square(8);
m
b.show();
}
(c
Output:
Checking Default Method
64
Notes
e
Default Methods and Multiple Inheritance
in
If both the implemented interfaces include default methods with same method
statement, the implementing class should clearly identify which default method is to be
used or it supposed to override the default method.
nl
Example to show multiple inheritance through default method
interface TestInterfacedemo
O
{
// default method
ty
{
System.out.println(“DefaultInterfaceMethod”);
si
}
interface TestInterface2 r
ve
{
{
ni
}
U
TestInterfacedemo.super.show();
)A
TestInterface2.super.show();
}
(c
{
Amity Directorate of Distance & Online Education
256 Object Oriented Programming Using Java
e
d.show();
in
}
nl
Output:
Default Interface Method
O
Default Interface Method1
ty
r si
ve
ni
U
ity
default method, the static method defines in Interface hello(), cannot be overridden in
Notes
e
implementing the class.
interface NewInterface {
in
static void hello()
nl
System.out.println(“Welcome to Java”);
O
void overrideMethod(String str);
ty
public static void main(String[] args)
si
{
NewInterface.hello(); r
ve
InterfaceDemo.overrideMethod(“Override Mathod”);
@Override
ni
{
U
System.out.println(str);
}
ity
Output
Welcome to java
m
Override Method
interface PrintDemo {
{
(c
System.out.println(“Interface PrintDemo”);
}
Notes
e
public class InterfaceDemo implements PrintDemo {
in
public static void main(String[] args)
nl
PrintDemo.hello();
O
hello();
ty
// Class Static method is defined
si
System.out.println(“Invoke from Class”);
}
r
ve
Output
Interface PrintDemo
ni
values. Once developer include that interface during a class (that is, once developer
“implement” the interface), all of these variable names are going to be in scope as
constants. (This is analogous to employing a header enter C/C++ to make an outsized
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 259
e
methods, then any class that has such an interface doesn’t actually implement anything.
in
It is as if that class was calling the constant fields into the category name space as
final variables.
nl
Below program uses this system to implement an automatic “decision maker”:
import java.util.Random;
interface SharedConstantsdemo {
O
int NO = 0;
int YES = 1;
ty
int MAYBE = 2;
int LATER = 3;
si
int SOON = 4;
int NEVER = 5;
}
r
ve
class Question implements SharedConstantsdemo {
int ask() {
ni
if (a< 30)
U
else
)A
return NEVER; // 2%
}
(c
switch(result) {
Notes
e
case NO:
System.out.println(“No”);
in
break;
case YES:
nl
System.out.println(“Yes”);
break;
O
case MAYBE:
System.out.println(“Maybe”);
ty
break;
case LATER:
System.out.println(“Later”);
si
break;
case SOON:
r
System.out.println(“Soon”);
ve
break;
case NEVER:
ni
System.out.println(“Never”);
break;
U
answer(q.ask());
answer(q.ask());
m
answer(q.ask());
answer(q.ask());
)A
Notice that this program makes use of one of Java’s regular classes: Random. This
class contains pseudorandom numbers and provides them when they call. It provides
(c
several methods that allow you to obtain random numbers in the form required by your
program. In this program, developer used method nextDouble( ) is used. It returns
e
In this sample program, the two classes, Questiondemo and AskMedemo, both
implement the SharedConstantsdemo interface where NO, YES, MAYBE, SOON,
in
LATER, and NEVER are defined. Inside each class, the code refers to these constants
as if each class had defined or inherited them directly.
nl
Output
Later
Soon
O
No
Yes
ty
Check your Understanding
1. The interface in Java language is a instrument to achieve __________________ .
si
2. Before Java 8, interfaces possibly will have only __________________ methods.
3. Static Methods in Interface are those methods, which are declared in the
____________________ with the keyword static.
4. r
Developer can use ______________________ to call shared constants into multiple
ve
classes by simply declaring an interface that contains variables that are initialized to
the specified values.
Summary
ni
●● An interface can extends another interface or interfaces (more than one interface).
●● A class that implements interface must implements all the methods in interface.
)A
●● All the methods are public and abstract. And all the fields are public, static, and
final.
●● It is used to achieve multiple inheritance.
●● It is used to achieve loose coupling.
(c
e
of the Interface only.
Activity
in
1. What will be the output of below program
import java.io.*;
nl
{
O
final int a = 10;
void display();
ty
}
si
public void display()
r
System.out.println(“Geek”);
ve
}
{
ni
t.display();
U
System.out.println(a);
}
ity
Glossary
●● Lambda expression: Lambda expression is a new and important feature of Java
which was included in Java SE 8. It provides a clear and concise way to represent
(c
●● Interface: Like a class, an interface can have methods and variables, but the
Notes
e
methods declared in an interface are by default abstract (only method signature,
no body).
in
Further Readings:
1. The Java Native Interface: Programmer’s Guide and Specification, Sheng
Liang
nl
2. Essential JNI: Java Native Interface, Rob Gordon
3. The Java Application Programming Interface, Frank Yellin and James Gosling
O
Check Your Understanding:
Answers
ty
1. abstraction
2. abstract
3. Interface
si
4. interfaces
r
ve
ni
U
ity
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
●● Define Multithreading
nl
●● Understand the Concept of Thread in Multithreading
●● Define Lifecycle of Thread
O
●● How to Implement a Thread
●● Compare Thread v/s Runnable method of creating thread
●● Define Methods of Thread class
ty
●● What are Thread Priorities
Introduction
si
Contrasting to many other computer languages, Java language gives built-in
support for multithreaded programming. A multithreaded program includes two or more
parts that can execute alongside. Each fraction of such a program is called a thread,
r
and each thread declares a separate way of execution. Thus, multithreading is a
ve
dedicated type of multitasking.
Multithreading enables developer to write very efficient codes that make maximum
use of the CPU, because idle time can be reserved to a minimum. This is significant
for the interactive, networked environment in which Java language operates, because
U
inactive time is common. For example, the broadcast rate of data over a system is
much slower than the rate at which the computer can process it. Even local file system
resources are read and written at a very slower pace than they can be processed by the
ity
CPU. And, of course, user contribution is much slower than the computer. In a single-
threaded environment, developer program has to wait for each of these everyday jobs
to end before it can go on to the next one—even though the CPU is sitting idle most of
the time. Multithreading lets you gain admission to this inactive time and put it to good
use.
m
If developer have programmed for operating systems such as Windows, then you
are already recognizable with multithreaded programming. However, the fact that Java
language manages threads makes multithreading particularly suitable, because many
)A
more parts of a program for maximum consumption of CPU. Each part of such program
is called a thread. So, threads are light-weight processes inside a process.
e
common memory area. They don’t assign separate memory region so saves memory,
and context-switching among the threads takes less time than process.
in
There are two distinct types of multitasking: process based and thread-based. It is
important to understand the difference between the two.
nl
Process-based multitasking:
A process is, in core, a code that is executing. Thus, process-based multitasking
is the characteristic that lets your computer to run two or more programs alongside.
O
For example, process-based multitasking facilitates you to run the Java compiler at the
same time that when you are working on a text editor. In process based multitasking, a
program is the smallest unit of code that can be transmitted through the scheduler.
ty
r si
ve
Thread-based multitasking:
The thread is the least unit of dispatch able code. This means that a single code
can carry out two or more tasks at the same time. For example, text editors can layout
ni
text at the same time that it is printing, providing these two events are being executed
by two separate threads. Thus, process-based multitasking engaged with the “big
picture,” and thread-based multitasking takes care of the details.
U
Alternatively, threads are lightweight. They allocate the similar address space
and agreeably share the same heavyweight process. Inter-thread communication is
reasonably priced, and context switching among one thread to another is not that costly.
While Java language codes make use of process based multitasking environments,
m
Advantages of Multithreading
(c
1. It doesn’t stop the user because threads are self-governing, and developer can carry
out multiple operations at the equivalent time.
e
3. Threads are independent, so it does not impact other threads if an exception occurs
in a single thread.
in
4.3.2 Concept of Thread in Multithreading
In Java language, a single task is called a thread. The term “thread” refers to a
nl
“thread of control” or “thread of execution,” meaning a series of commands that
are executed one after another— the thread extends during time, connecting each
command to the next. In a multithreaded program, there can be many threads of
O
execution, weaving during time in equivalent and creating the complete framework of
the program.
Every Java language program has at least one thread; when the Java virtual
ty
machine executes your program, it constructs a thread that is accountable for executing
the main routine of the code. This main thread can in turn construct other threads that
can carry on even after the main thread has terminated. In a GUI code, there is at
least one supplementary thread, which is in charge for managing events and drawing
si
components on the display. This GUI thread is shaped when the first window is opened.
So in fact, developer has already done parallel programming! When a main schedule
opens a window, together the main thread and the GUI thread can carry on to execute
r
in parallel. Of course, parallel programming can be utilized in much more exciting ways.
ve
ni
U
ity
As depicted in the figure above, a thread is executed inside the different processes.
m
Java language offer Thread class to attain thread programming. Thread class
)A
present constructors and methods to construct and carry out operations on a thread.
Thread class expand Object class and execute Runnable interface.
The Java language run-time system rely on threads for several things, and all the
class libraries are intended with multithreading in mind. In actual fact, Java language
uses threads to enable the whole environment to be asynchronous. This helps in
(c
e
to its counterpart. Single-threaded scheme use an approach known as an event loop
with polling. In this model, a single thread of control executes in an infinite loop, polling
a single event queue to make a decision what to do next. Once this polling system
in
returns with, declare, a signal that a network file is all set to be read, then the event loop
transmits control to the suitable event handler.
nl
Till this event handler returns, system gets into an idle state. This takes too
much time of a CPU. It can also result in one part of a program taking control of the
system and avoiding any other events from being executed or processed. In common,
a singled-threaded environment, when a thread blocks (that is, suspends execution)
O
because it is looking for some resources, the entire code stops executing.
ty
of developer program. For example, the idle time created when a thread compile
data from a network or look for user contribution can be used somewhere else.
Multithreading permits animation loops to snooze for a second among each frame
si
without affecting the whole system to pause. When a thread blocks in a Java language
program, only the single thread that is blocked pauses. All other threads continue to
execute.
r
Threads presents in several states. A thread can be running. It can be ready to
ve
execute as soon as it gets CPU time. A running thread can be stopped, which for the
time being suspends its activity. A suspended thread can then be recommence, letting
it to pick up where it left off. A thread can be barren when looking for a resource.
At whatever time, a thread can be ended, which bring to an end to its execution
ni
Messaging
U
After developers divide his/her code into separate threads, developer requires
declaring how they will connect with each other. When programming with most other
languages, developer must depend on the operating system to set up communication
among threads. This adds overhead. By contrast, Java language provides a clean,
ity
low-cost method for two or more threads to communicate with each other, via calls
to predefined methods that all objects have. Java’s language messaging framework
permits a thread to enter a synchronized method on an object, and then stay there until
some other thread explicitly informs it to come out.
m
Thread Priorities
Java language allocates to every thread a priority that declares how that thread
should be indulgence with respect to the others. Thread priorities are integers that state
)A
switch. The rules that determine when a context switch takes place are simple:
●● A thread can willingly hand over control. This is done by clearly yielding, sleeping,
Notes
e
or blocking on pending I/O. In this scenario, all other threads are inspected, and
the highest-priority thread that is prepared to execute is given the CPU.
in
●● A thread can be obstructing by a higher-priority thread. In this case, a lower-priority
thread that does not give up the processor is simply holds—no matter what it is
doing— by a higher-priority thread. On the whole, as soon as a higher-priority
nl
thread wants to executes, it does irrespective of any other process. This is called
preemptive multitasking.
In cases where two threads with the similar priority are challenging for CPU cycles,
O
the circumstances are a bit difficult. For operating systems such as Windows, threads
of identical priority are time-sliced repeatedly in round-robin fashion. For other types
of operating systems, threads of equal priority have to willingly yield managed to their
peers. If they don’t, the other threads will not execute.
ty
Synchronization
Since multithreading brings in an asynchronous behavior to your code, there
si
must be a way for developer to implement synchronicity when developer require
it. For example, if you want two threads to converse and contribute to a complicated
data structure, such as a linked list, developer need some way to make sure that they
r
don’t argue among each other. That is, developer must stop one thread from writing
data while another thread is in the middle of reading it. For this purpose, Java language
ve
employs an elegant twist on an age-old model of inter-process synchronization: the
monitor. The monitor is a manage mechanism first explain by C.A.R. Hoare. Developer
can think of a screen as a very small box that can grasp only one thread. Once a thread
enters a screen, all other threads have to wait until that thread exits the screen. In this
ni
fashion, a monitor can be utilized to shield a shared asset from being influenced by
more than one thread at a time.
Most multithreaded systems expose screens as objects that your code must openly
U
acquire and manipulate. Java language provides a cleaner solution. There is no class
“Monitor”; instead, each object has its own implied monitor that is automatically go into
when one of the object’s synchronized methods is invoked. Once a thread is within a
ity
synchronized method, no other thread can invoke any other synchronized method on
the same object. This facilitates developer to write very clear and crisp multithreaded
code, because synchronization support is built within the language.
The Main Thread when a Java language program sets up, one thread starts
executing right away. This is generally invoked the main thread of your code, because
it is the one that is running when his/her program starts. The main thread is vital for two
)A
reasons:
Although the main thread is constructed without human intervention when your
program is begins, it can be managed through a Thread object. To carry out this,
e
public static member of Thread. Its general form can be represented as:
in
This method returns a reference to the thread in which it is invoked. Once
developer has a reference to the main thread, developer can control it just like any
other thread.
nl
Let’s look into below code and examine it
class CurrentThreadDemo1 {
O
public static void main(String args[]) {
Thread td = Thread.CurrentThreadDemo();
ty
System.out.println(“Current thread: “ + td);
td.setName(“My Thread”);
si
System.out.println(“After name change: “ + td);
try {
Thread.sleep(1000);
ni
} catch (InterruptedException e) {
}
ity
In this program, a reference to the current thread (the main thread, in this case) is
acquired by invoking CurrentThreadDemo( ), and this reference is stored in the local
variable td. Next, the program shows information about the thread. The program then
m
invoke setName( ) to modify the internal name of the thread. Information as regards the
thread is then redisplayed. Next, a loop counts down from seven, pausing one second
between each line.
)A
The pause is achieved by the sleep( ) method. The argument to sleep( ) identify the
holdup period in milliseconds. Observe the try/catch block around this loop. The sleep( )
method in Thread may throw an InterruptedException. This would happen if some other
thread wanted to break off this sleeping one. This example just prints a message if it
(c
gets broken up. In a real code, developer would need to tackle this differently. Here is
the output generated by this program:
Output
Notes
e
Current thread: Thread[main,7,main]
in
7
nl
5
O
3
ty
1
si
default, the name of the main thread is main.
Its priority is 7, which is the default value, and main is also the name of the group
of threads to which this thread fit in. A thread group is a data structure that manages the
r
pahse of a collection of threads as a complete. After the name of the thread is modified,
ve
td is again output. This time, the new name of the thread is showed.
states are:
1. New
U
2. Active
3. Blocked / Waiting
4. Timed Waiting
ity
5. Terminated
m
)A
(c
1. New Thread: When a new thread is constructed, it is in the new state. The thread
Notes
e
has not yet in progress to execute when thread is in this state. When a thread stays
in the new state, its code is yet to be run and hasn’t on track to execute.
in
2. Runnable State: A thread which is ready to run is moved to runnable state. In this
state, a thread might actually be executing or it might be ready run at any point of
time. It is the accountability of the thread scheduler to provide the thread, time to run.
nl
A multi-threaded code assigns a fixed amount of time to each entity thread. Each and
every thread runs for a little while and then pauses and abandon the CPU to another
thread, so that other threads can acquire a chance to run. When this occurs, all
O
such threads that are prepared to run, waiting for the CPU and the currently running
thread located in runnable state.
3. Blocked or Waiting: Whenever a thread is still for duration of time (not permanently)
then, either the thread is in the blocked phase or is in the waiting phase.
ty
For example, a thread (let’s say its name is X) may want to print some information
from the printer. However, at the similar time, the other thread (let’s say its name is Y)
is utilizing the printer to print some information. Consequently, thread X has to hang
si
about for thread Y to utilize the printer. Thus, thread X is in the blocked Phase. X
thread in the blocked state is not capable to carry out any execution and thus never
use any cycle of the Central Processing Unit (CPU). Hence, we can say that thread
r
X remains idle until the thread scheduler reinitiate thread X, which is in the waiting or
ve
blocked phase or state.
When the main thread calls the join() method then, it is thought that the main thread
is in the waiting state. The main thread then stops for the child threads to finish their
duties. When the child threads finish their job, an announcement is transmits to the
ni
main thread, which once more moves the thread from waiting to the active state.
If there are a group of threads in the waiting or blocked state, then it is the responsibility
of the thread scheduler to decide which thread to select and which one to negelect,
U
to leave that significant section. In such a scenario, another thread (its name is
Y) has to hold everlastingly, which leads to starvation. To keep away from such
circumstances, a timed waiting state is given to thread Y. Thus, thread located in
the waiting state for a definite duration of time, and not forever. A real example of
timed waiting is when we calls the sleep() method on a particular thread. The sleep()
m
method locate the thread in the timed wait state. After the time complete, the thread
wakes up and beginning its execution from where it has left earlier.
5. Terminated State: A thread ends because of either of the following reasons:
)A
◌◌ Because it exists as planned. This take place when the code of thread has
completely executed by the program.
◌◌ Because there take place some abnormal incorrect event, like segmentation
error or an unhandled exception.
(c
A thread that located in a terminated state does no longer eat any cycles of CPU.
e
In Java language, to get the present state of the thread, use Thread.getState()
method to get the present state of the thread. Java language provides java.lang.Thread.
in
State class that declares the ENUM constants for the state of a thread, as synopsis of
which is given below:
nl
public static final Thread.State NEW
Explanation: Thread state for a thread which has not yet started.
O
2. Constant type: Runnable
Expression: public static final Thread.State RUNNABLE
ty
Explanation: Thread state for a runnable thread. A thread in the runnable state is
running in the Java virtual machine but it might be looking for other resources from the
operating system such as processor.
si
3. Constant type: Blocked
Expression: public static final Thread.State BLOCKED
r
Explanation: Thread state for a thread blocked looking for a monitor lock. A thread
ve
in the blocked state is looking for a monitor lock to enter a synchronized block/method
or re-enter a synchronized block/method after invoking Object.wait().
Explanation: Thread state for a waiting thread. Thread state for a waiting thread. A
U
thread is in the waiting state due to invoking one of the following methods:
◌◌ LockSupport.park
A thread in the waiting state is looking for another thread to carry out a meticulous
action.
Explanation: Thread state for a waiting thread with a particular waiting time. A
)A
thread is in the timed waiting state due to invoking one of the methods described below
with a particular positive waiting time:
◌◌ Thread.sleep
◌◌ Object.wait with timeout
(c
e
◌◌ LockSupport.parkNanos
◌◌ LockSupport.parkUntil
in
6. Constant type: Terminated
Expression: public static final Thread.State TERMINATED
nl
Explanation: Thread state for a terminated thread. The thread has finished
execution.
O
class thread implements Runnable
ty
public void run()
si
// moving thread02 to timed waiting state
try
{
r
ve
Thread.sleep(1500);
catch (InterruptedException e)
ni
e.printStackTrace();
U
Test.thread1.getState());
try
{
m
Thread.sleep(200);
}
)A
catch (InterruptedException e)
e.printStackTrace();
(c
}
Notes
e
public class Test implements Runnable
in
public static Thread thread01;
nl
public static void main(String[] args)
O
ob = new Test();
ty
// thread1 constructed and is currently in the NEW state.
si
thread1.start();
r
System.out.println(“State of thread1 after invoking .start() method on it -
ve
“+
thread1.getState());
}
ni
{
U
thread02.start();
m
it - “ +
thread02.getState());
try
(c
e
Thread.sleep(200);
in
catch (InterruptedException e)
nl
e.printStackTrace();
O
System.out.println(“State of thread02 after invoking .sleep() method on
it - “+
thread02.getState() );
ty
try
si
// waiting for thread02 to die
thread02.join();
} r
ve
catch (InterruptedException e)
e.printStackTrace();
ni
execution - “ +
thread02.getState());
}
ity
Output
m
e
Creating a Thread
in
In the most general sense, developer constructs a thread by defining an object of
type Thread. Java defines two ways in which this can be completed:
nl
●● Developer can extend the Thread class, itself.
Common used method in thread class
O
Class Declaration
public void run() is used to perform action for a thread.
public void start() starts the execution of the thread.JVM calls the
ty
run() method on the thread
public void sleep(long Causes the currently executing thread to sleep
miliseconds) (temporarily cease execution) for the specified
number of milliseconds
si
public void join() waits for a thread to die.
public void jointlong waits for a thread to die for the specified
miliseconds) miliseconds.
public int getPriority() r returns the priority of the thread.
ve
public int setPriority(int changes the priority of the thread.
priority)
public String getName() returns the name of the thread.
public void setNamel String changes the name of the thread
ni
name)
public Thread currentThread) returns the reference of currently executing
thread
U
setDaemon(boolean b)
public void interrupt() interrupts the thread.
public boolesnisinterrupted) tests if the thread has been interrupted
public static boolean tests if the current thread has been interrupted.
(c
interrupted()
Implementing Runnable:
Notes
e
The simplest way to construct a thread is to create a class that employs the
Runnable interface. Runnable abstracts a element of executable program. Developer
in
can create a thread on any object that executes Runnable. To employ Runnable, a
class recquire only implement a single method known run( ), which is expressed like
this:
nl
public void run( )
Inside run( ), developer will declare the program that include the new thread. It is
significant to appreciate that run( ) can invoke other methods, use other classes, and
O
define variables, just like the main thread is able to. The only disparity is that run( )
establishes the access point for another, simultaneous thread of execution inside his/
her program. This thread will completes when run( ) returns.
ty
After developerconstructs a class that implements Runnable, developer will
instantiate an object of typeThread from inside that class. Thread declares several
constructors. The one that we will use is shown below:
si
Thread(Runnable threadObj, String threadDemo)
r
interface.Thisdeclares where implementation of the thread will start. The name of the
new thread is specifiedbythreadDemo.After the new thread is constructed, it will not
ve
start executing until you call its start( )method,which is definedinside Thread. In core,
start( ) executes a call to run( ).
Thread td;
NewThreaddemo() {
}
m
try {
)A
Thread.sleep(700);
(c
} catch (InterruptedException e) {
e
}
in
}
nl
class ThreadDemo {
O
new NewThreaddemo(); // create a new thread
try {
ty
for(int x = 5; x > 0; x--) {
Thread.sleep(1500);
si
}
} catch (InterruptedException e) {
r
System.out.println(“Main thread interrupted.”);
ve
}
}
U
Passing this as the first argument shows that developer wish for the new thread to
call the run( )method on this object. Next, start( ) is invoked, which starts the thread of
execution starting at the run( ) method. This cause the child thread’s for loop to start.
After invokingstart( ),NewThreaddemo’s constructor returns to main( ). When the main
thread resumes, it go intoforloop. Both threads carry on executing, allocating the CPU,
m
Output
)A
First Thread: 5
First Thread: 4
e
This is Child Thread: 2
First Thread: 3
in
This is Child Thread: 1
nl
First Thread: 2
First Thread: 1
O
Main thread exiting.
As told earlier, in a multithreaded code, frequently the main thread has to be thelast
thread to end running. In fact, for some older Java Virtual Machines, if the main thread
ty
end beforea child thread has finished, then the Java run-time system may “suspend.”
The previous example of program make sure that the main thread finishes at the end,
because the main thread sleeps for 1,500milliseconds between iterations, but the child
si
thread sleeps for only 700 milliseconds. This is the reason the child thread to end
earlier than the main thread.
Extending Thread
r
ve
The second method to create a thread is to construct a new class that extends
Thread, and then to create a module of that class. The extending class have to override
the run( ) method, which is the starting point for the new thread. It must also invoke
start( ) to start running of the new thread.
ni
NewThreadDemo() {
super(“Demo Thread”);
start();
m
try {
Thread.sleep(700);
}
Notes
e
} catch (InterruptedException e) {
System.out.println(“Child interrupted.”);
in
}
nl
}
O
class ExtendThread {
ty
new NewThread(); // create a new thread
try {
si
System.out.println(“Main Thread: “ + x);
Thread.sleep(1500);
}
r
ve
} catch (InterruptedException e) {
This program generates the same output as the preceding version. As you can
ity
Notes
e
in
nl
4.3.5 Thread v/s Runnable method of creating thread
O
Basis For
Thread Runnable
Comparison
Basic Each thread creates a unique Multiple threads share the
ty
object and gets associated with it. same objects.
Memory As each thread creates a unique As multiple threads share the
object, more memory required. same object less memory is
used.
si
Extending In Java, multiple inheritance If a class define thread
not allowed hence, after a class implementing the Runnable
extends Thread class, it cannot interface it has a chance of
extend any other class. r extending one class.
ve
Use A user must extend thread class If you only want to
only if it wants to override the specialize run method then
other methods in Thread class. implementing Runnable is a
better option.
ni
class and also the job assigned to Thread is separate from the
the thread. job of Threads.
Example of runnable:
ity
td1.start();
}
(c
Output
Notes
e
Thread is running for Runnable Implementation Demo
in
Example of Thread implementation:
class ThreadDemo extends Thread{
nl
System.out.println(“Thread Demo is running”);
O
public static void main(String args[]){
ty
x.start();
si
Output
Thread demo is running.
r
ve
Creating Multiple Threads
So far, we have been with only two threads: the main thread and one child thread.
Though, developer program can initiate as much threads as it requires. For example,
the following code constructs three child threads:
ni
Thread td1;
ity
NewThreadDemo(String threadname) {
name = threadname;
try {
System.out.println(name + “: “ + a);
Thread.sleep(1200);
Notes
e
}
} catch (InterruptedException e) {
in
System.out.println(name + “Interrupted”);
nl
System.out.println(name + “ exiting.”);
O
}
class MultiThreadDemo {
ty
public static void main(String args[]) {
new NewThreadDemo(“Two”);
si
new NewThreadDemo(“Three”);
try {
} catch (InterruptedException e) {
ni
}
U
}
ity
Output
New thread: Thread[One,5,main]
One: 5
)A
Two: 5
Three: 5
One: 4
(c
Two: 4
Three: 4
One: 3
Notes
e
Three: 3
Two: 3
in
One: 2
Three: 2
nl
Two: 2
One: 1
O
Three: 1
Two: 1
ty
One exiting.
Two exiting.
Three exiting.
si
Main thread exiting.
In above example, once started, all three child threads split the CPU. Notice the
r
call to sleep(12000) in main( ). This is reasons the main thread to sleep for twelve
ve
seconds and ensures that it will end last.
threads. Each thread has a priority which is used by the thread scheduler to decide
which thread must run at which place. Java language provides a thread class that
has various method calls in order to administer the behavior of threads by giving
U
Thread current
Thread
yield public static void Yield is a heuristic attempt to improve relative
yield() progression between threads that would otherwise
m
Lowners!
sleep public static void Causes the currently executing thread to sleep
Notes
e
sleep(long mills, (temporarily cease execution) for the specified
int nanos) number of milliseconds plus the specified number of
in
nanoseconds, subject to the precision and accuracy
of system timers and schedulers. The thread does
not lose ownership of any monitors
nl
clone protected Object Throws Clone NotSupported Exception as a Thread
clone() can not be meaningfully cloned. Construct a new
Thread instead
start public void start() Causes this thread to begin execution the Java
O
Virtual Machine calls the run method of this thread.
Run public void run() If this thread was constructed using a separate
Runnable run object, then that Runnable object’s
ty
run method is called, otherwise, this method does
nothing and returns.
stop public final void Forces the thread to stop executing
stop()
si
interrupted public void Interrupts this thread
interrupt()
interrupted public static The interrupted status of the thread is cleared by
boolean r
this method. In other words, if this method were
ve
interrupted() to be called twice in succession, the second call
would return false funless the current thread were
interrupted again, after the first call had cleared its
interrupted status and before the second call had
ni
is interrupted public boolean is Tests whether this thread has been interrupted. The
interrupted() interrupted status of the thread is unaffected by this
method. A thread interruption ignored because a
thread was not alive at the time of the interrupt will
ity
suspend public final void First, the checkAccess method of this thread
suspend() is called with no arguments. This may result in
throwing a SecurityException in the current thread) if
the thread is alive but suspended, it is resumed and
is permitted to make progress in its execution.
(c
resume public final void First the checkAccess method of this thread is called
Notes
e
resume() with no arguments. This may result in throwing a
SecurityException otherwise, the priority of this
in
thread is set the smaller of the specified newfrienty
and the main permitted pilarity of the thead’s thread
group.
nl
set Priority public final void Returns this thread’s priority.
set Priority (int
new Priority)
set Name public final void Changes the name of this thread to be equal to the
O
set Name (String argument name. First the checkAccess method of
Name) this thread is called with no arguments. This may
result in throwing a SecurityException.
ty
get Name public final string Returns this thread’s name.
get Name()
get Thread public final Thread Returns the thread group to which this thread
Group Group get Thread belongs. This method returns null if this thread has
si
Group() died (been stopped) Returns an estimate of the
number of active threads in the current thread’s
thread group and its subgroups. Recursively iterates
r over all subgroups in the current thread’s thread
ve
group.
active Count public static int Copies into the specified array every active thread in
active count() the current thread’s thread group and its subgroups.
This method simply Invokes the ThreadGroup.
ni
(thread[] tarray)
count Stack public int count Waits at mest millis milliseconds for this thread to
Frames stack frames() die. A timeout of 0 means to wait forever.
ity
join public final void Marks this thread as either a daemon thread or a
join (long millis) user thread. The Java Virtual Machine exits when
the only threads running are all daemon threads.
set Daemon public final void Tests if this thread is a daemon thread.
set Daemon
m
(boolean on)
is Daemon public final Determines if the currently running thread has
boolean is permission t to modify this thread. if there is a
)A
group
e
string() including the thread’s name, priority, and thread
group.
in
get Context public Class Returns the context ClassLoader for this Thread.
Class Loader Loader get The context ClassLoader is provided by the creator
Context Class of the thread for use by code running in this thread
nl
Loader() when loading classes and resources. If not set, the
default is the of the parent Thread ClassLoader
context text Classtoader of the primordial The thread
is typically set to the class loader used to load the
O
application.
set Context public void set Sets the context ClassLoader for this Thread The
Class Loader Context Class context ClassLoader can be set when a thread
ty
Loader (Class is created, and allows the creator of the thread
Loader cl) to provide the appropriate class loader through
getContextClassLoader to code running in the
thread when loading classes and resources
si
holds Lock public static Sets the context ClassLoader for this Thread. The
boolean holds context Classtoader can be set when a thread
Lock (Object obj) is created, and allows the creator of the thread
r
to provide the appropriate class loader, through
ve
ContextClassLoader, to code running in the thread
when loading classes and resources if security
manager is present, its checkPermission method is
invoked with a RuntimePermission(“setContextClass
ni
get Stack public Stack Trace Returns an array of stack trace elements
Trace Element[] get representing the stack dump of this thread This
Stack Trace() method will return a zero-length array if this thread
has not started, has started but has not yet been
scheduled to run by the system, or has terminated. If
m
Often developer wishes for the main thread to finish at the end. In the previous
examples, this is completed by invoking sleep( ) inside main( ), with a sufficient delay to
make sure that all child threads finish prior to the main thread. On the other hand, this is
Notes
e
barely a reasonable solution, however there class provide us a solution for that
There are two ways to define whether a thread has ended or not.
in
First, developer can call isAlive( ) on the thread. This method is declared by
Thread, and it can be represented as:
nl
final booleanisAlive( )
The isAlive( ) method returns true if the thread upon which it is invoke is still
running. It returns false else.
O
While isAlive( ) is infrequently useful, the method that developer will more
commonly use to wait for a thread to finish is known join( ), its syntax is given below
ty
This method stay until the thread on which it is invokes ends. Its name comes from
the idea of the invoking thread waiting until the particular thread joins it. Supplementary
forms of join( ) lets developer to indicate a maximum amount of time that developer
si
want to wait for the particular thread to end.
r
class NewThreadDemo implements Runnable {
ve
String name; // name of thread
Thread a;
NewThreadDemo(String threadname) {
ni
name = threadname;
try {
m
System.out.println(name + “: “ + x);
)A
Thread.sleep(1200);
} catch (InterruptedException e) {
System.out.println(name + “ interrupted.”);
(c
System.out.println(name + “ exiting.”);
Notes
e
}
in
class DemoJoin {
nl
NewThreadDemo ob1 = new NewThreadDemo(“One”);
O
NewThreadDemo ob3 = new NewThreadDemo(“Three”);
ty
+ ob1.a.isAlive());
+ ob2.a.isAlive());
si
System.out.println(“Thread Three is alive: “
+ ob3.a.isAlive());
ob1.a.join();
ob2.a.join();
U
ob3.a.join();
} catch (InterruptedException e) {
+ ob1.a.isAlive());
m
+ ob2.a.isAlive());
)A
+ ob3.a.isAlive());
Output
Notes
e
New thread: Thread[One,5,main]
in
New thread: Thread[Three,5,main]
nl
Thread Two is alive: true
O
Waiting for threads to complete.
One: 3
ty
Two: 3
Three: 3
One: 2
si
Two: 2
Three: 2
One: 1
r
ve
Two: 1
Three: 1
ni
Two exiting.
Three exiting.
One exiting.
U
In Java language, each thread is dispersing a different priority that will choose the
preference in which it is scheduled for executing.
Thread priorities are symbolized by a number from 1 to 10 that specify the priority
of one thread to another. The thread with the uppermost priority is chosen by the
(c
e
threads. In practice, the sum of CPU time that a thread find often based on several
factors in addition to its priority. (For example, how an operating system realizes
multitasking can influence the relative availability of CPU time.) A higher-priority thread
in
is able to anticipate a lower-priority one. For instance, when a lower-priority thread is
executing and a higher-priority thread starts again (from sleeping or waiting on I/O, for
example), it will anticipate the lower priority thread.
nl
The default priority of a thread is 5. Thread class in Java language also provides
quite a few priority constants to describe the priority of a thread. These are:
O
1. MIN_PRIORITY = 1
2. NORM_PRIORITY = 5
3. MAX_PRIORTY = 10
ty
These 3 constant can be represented as:
●● public static int MIN_PRIORITY
si
●● public static int NORM_PRIORITY
●● public static int MAX_PRIORITY
r
These constants are public, final, and static associate of the Thread class.
ve
In all the previous examples, threads we have discussed are of the same priority
(equal priority). The threads of the similar priority are given equal time by Java
language scheduler.
Thread scheduler choose the thread for execution on the first-come, first-serve
ni
foundation. That is, the threads having identical priorities split the processor time on the
first-come, first-serve basis.
U
When multiple threads are prepared for execution, the uppermost priority thread
is preferred and executed by Java virtual machine. In case when high priority threads
discontinue, give ways, or enters the blocked state, then a low priority thread starts
running.
ity
If any high priority thread goes into the runnable state, it will block the currently
running thread forcing it to shift to the runnable state. Note that the highest priority
thread forever prevents any lower priority thread to execute.
m
invoked.
{
Notes
e
System.out.println(Thread.currentThread()); // This method is static.
in
public static void main(String[] args)
nl
ABC a = new ABC();
O
System.out.println(“Priority of Thread: “ +x.getPriority());
ty
System.out.println(“Name of Thread: “ +x.getName());
x.start();
si
}
Output:
r
ve
Priority of Thread: 5
Thread[NewThread,5,main]
ni
In the above code, the getPriority() method is invoked using reference variable x of
Thread class, therefore it returns the precedence of current thread through Thread.
U
ThreadName.setPriority(a);
{
)A
{
Notes
e
ABC a = new ABC();
in
x.setPriority(3); // Setting the priority of thread.
nl
System.out.println(“Name of Thread: “ +x.getName());
x.start();
O
}
ty
Output:
Priority of Thread: 3
si
Name of Thread: NewThreadDemo
Thread[NewThread,3,main]
r
In above code, the setPriority() method sets the priority of Thread x to 3.
ve
ni
The below program exhibit two threads at unusual priorities, which do not execute
U
long click = 0;
Thread x;
public XYZ(int a) {
x = new Thread(this);
)A
x.setPriority(a);
while (running) {
click++;
}
Notes
e
}
in
running = false;
nl
public void start() {
x.start();
O
}
ty
class HiLoPri {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
si
XYZ hi = new XYZ(Thread.NORM_PRIORITY + 2);
lo.start();
r
ve
hi.start();
try {
ni
Thread.sleep(10000);
} catch (InterruptedException e) {
U
lo.stop();
ity
hi.stop();
try {
m
hi.x.join();
lo.x.join();
)A
} catch (InterruptedException e) {
System.out.println(“InterruptedException caught”);
}
(c
}
Notes
e
}
The output of this program, shown below when execute under Windows, indicates
in
thatthe threads did background switch, even though neither willingly yielded the CPU
nor blockedfor I/O. The higher-priority thread got the greater part of the CPU time.
nl
Low-priority thread: 4408112
O
Check your Understanding
1. Developers are certainly familiar with multitasking, because it is supported by
nearly all modern operating systems. Nevertheless, there are two separate types of
multitasking ___________________ and __________________.
ty
2. In Java language, a single task is called a __________________ .
3. _________________ scheme use an approach known as an event loop with polling.
si
4. A thread’s priority is used to determine when to jumps from one running thread to the
next is called a ___________________ switch.
5.
r
Most multithreaded systems expose screens as objects that your code must openly
_________________ and ________________ .
ve
6. A thread that located in a ___________ state does no longer eat any cycles of CPU.
7. In Java language, to get the present state of the thread, use ________________
method to get the present state of the thread.
ni
Summary
ity
●● Process-based multitasking is the characteristic that lets your computer to run two
or more programs alongside.
●● In a GUI code, there is at least one supplementary thread, which is in charge for
managing events and drawing components on the display. This GUI thread is
m
shaped when the first window is opened. So in fact, developer has already done
parallel programming
●● Java language offer Thread class to attain thread programming. Thread class
)A
data from a network or look for user contribution can be used somewhere else.
●● Java language allocates to every thread a priority that declares how that thread
Notes
e
should be indulgence with respect to the others. Thread priorities are integers that
state the comparative precedence of one thread to another.
in
●● A thread can willingly hand over control. This is done by clearly yielding, sleeping,
or blocking on pending I/O. In this scenario, all other threads are inspected, and
the highest-priority thread that is prepared to execute is given the CPU.
nl
●● A thread can be obstructing by a higher-priority thread. In this case, a lower-priority
thread that does not give up the processor is simply holds—no matter what it is
doing— by a higher-priority thread. On the whole, as soon as a higher-priority
O
thread wants to executes, it does irrespective of any other process. This is called
preemptive multitasking.
●● A thread always exists in any one of the following states. These states are:
ty
1. New
2. Active
3. Blocked / Waiting
si
4. Timed Waiting
5. Terminated
●● r
The simplest way to construct a thread is to create a class that employs the
ve
Runnable interface. Runnable abstracts a element of executable program.
Developer can create a thread on any object that executes Runnable. To employ
Runnable, a class recquire only implement a single method known run( ).
●● Thread priority in Java language is a number allocated to a thread i.e. utilized by
ni
discontinue, give ways, or enters the blocked state, then a low priority thread starts
running.
Activity
ity
1. Create a program and include multiple thread and assign different priorities to them?
Glossary
Notes
e
●● Multithreading: Multithreading is a Java characteristic that lets simultaneous
execution of two or more parts of a program for maximum consumption of CPU.
in
●● Thread: The term “thread” refers to a “thread of control” or “thread of execution,”
meaning a series of commands that are executed one after another— the thread
extends during time, connecting each command to the next.
nl
●● GUI: Graphical User Interface
●● CPU: Central processing Unit
O
●● New Thread: When a new thread is constructed, it is in the new state.
●● Runnable State: A thread which is ready to run is moved to runnable state. In this
state, a thread might actually be executing or it might be ready run at any point of
ty
time.
●● Blocked or Waiting: Whenever a thread is still for duration of time (not
permanently) then, either the thread is in the blocked phase or is in the waiting
phase.
si
●● Timed Waiting: Sometimes, waiting for takes code to starvation.
●● Terminated State: A thread ends because of either of the following reasons:
◌◌
r
Because it exists as planned. This take place when the code of thread has
ve
completely executed by the program.
◌◌ Because there take place some abnormal incorrect event, like segmentation
error or an unhandled exception.
ni
Further Readings:
1. The Java Native Interface: Programmer’s Guide and Specification, Sheng
Liang
U
2. thread
3. Single-threaded
4. Context
)A
8. Construct
9. scheduled
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● How to Implement Synchronization in Thread
●● Define the Benefits and Loopholes of Synchronization
O
●● Understanding the concept of Resuming and stopping Threads
●● A code snippet to demonstrate thread with and without synchronization
Introduction
ty
It is already mentioned in above segments that threads in Java language are
executing in the same memory space, and therefore it is easy to converse between two
threads. Inter-thread connections allow threads to talk to or wait on each other. Again,
si
because all the threads in a code share the similar memory space, it is promising for
two threads to use the same variables and methods in object.
r
Problems may happen when two or more threads are accessing the same data
alongside, for example, one thread stores data into the shared object and the other threads
ve
reads data, and there can be synchronization trouble if the first thread has not completed
storing the data earlier than the second one goes to read it. So developer needs to make
sure to utilize the data by only one thread process at a same time. Java language offer
unique language level support for such synchronization. In this segment we will learn how
ni
When two or more threads require admission to a shared resource, they require
some way to make sure that the resource will be used by only one thread at a time. The
procedure by which this is achieved is known synchronization. As you will see, Java
ity
obtain a lock, it is said to encompass entered the monitor. All other threads attempting
to go into the locked monitor will be hovering until the first thread exits the monitor.
These other threads are supposed to be waiting for the monitor. A thread that possess a
)A
Once a thread is inside a synchronized method, no other Thread can invoke any other
synchronized system on the same object. This facilitates developer to write very clear
Notes
e
and brief multithreaded code.
in
Suppose we want to sustain a bank account of customers. Several transactions,
such as deposits withdrawal some amount from an account etc. are possible. Now, for a
given account, if two or more transactions come concurrently then only one transaction
nl
should be allowed at a time instead of simultaneous transaction giving out so that data
inconsistency will never takes place. So, what developer needs to do is to synchronize
the transaction.
O
class Accountdemo {
ty
public int accountNo;
void displayBalance() {
si
}
displayBalance();
ni
displayBalance();
}
m
int amount;
)A
AccountdemoaccountX;
accountX = x;
(c
this.amount = amount;
new Thread(this).start();
}
Notes
e
public void run(){
accountX.deposit(amount);
in
}
nl
class TransactionWithdraw implements Runnable{
O
int amount;
AccountdemoaccountY;
ty
TransactionWithdraw(Accountdemo y, int amount) {
accountY = y;
this.amount = amount;
si
new Thread(this).start();
}
ni
class Demonstration_119{
U
ABC.balance = 1000;
ity
ABC.accountNo = 0218;
TransactionDepositt1;
TransactionWithdrawt2;
m
t2 = new TransactionWithdraw(ABC,1000);
)A
Output:
(c
600 is deposited
1000 is withdrawn
Notes
e
Account No:0218Balance: 600
In the above code, the keyword synchronized is utilizedfor the methods void
in
deposits() and void withdraw so that these two methods will never execute for the same
object instance concurrently.
nl
4.4.2 Implementing Synchronization in Thread
O
Synchronization is easy in Java language, because all objects have their own
implied monitor linked with them. To enter an object’s monitor, just invoke a method
that has been customized with the synchronized keyword. While a thread is within a
ty
synchronized method, all other threads that try to invoke it (or any other synchronized
method) on the similar instance have to wait. To exit the monitor and hand over control
of the object to the next coming up thread, the holder of the monitor just returns from
the synchronized method.
si
To understand the requirement for synchronization, let’s begin with a simple
example that does not use it—but should have to use. The below program has three
r
simple classes. The first one, Callmedemo, has a single method named call( ). The call(
) method obtain a String parameter called m. This method attempt to print the m string
ve
inside of square brackets. The interesting thing to notice is that after call( ) prints the
opening bracket and the m string, it calls Thread .sleep(1200), which pauses the current
thread for 1.2 second.
ni
on the target instance of Callmedemo, passing in the m string. Finally, the Synch
class starts by constructing a single instance of Callmedemo, and three instances of
Callerdemo, each with a exclusive message string. The same instance of Callmedemo
ity
class Callmedemo {
m
void call(String m) {
System.out.print(“[“ + m);
try {
)A
Thread.sleep(1200);
} catch(InterruptedException e) {
System.out.println(“Interrupted”);
(c
System.out.println(“]”);
Amity Directorate of Distance & Online Education
302 Object Oriented Programming Using Java
}
Notes
e
}
in
String m;
Callmedemotarget;
nl
Thread t;
O
target = targ;
m = s;
ty
t = new Thread(this);
t.start();
si
public void run() {
target.call(m);
}
r
ve
}
class Synch {
ni
try {
ob1.t.join();
m
ob2.t.join();
ob3.t.join();
)A
} catch(InterruptedException e) {
System.out.println(“Interrupted”);
}
(c
Output
Notes
e
Hello[Synchronized[World]
in
]
As we can see in above code, by calling sleep( ), the call( ) method lets execution
nl
to switch to another thread. This consequences in the mixed-up output of the three
message strings. In this code, nothing exists to end all three threads from invoking the
same method, on the same object, at the similar time.
O
This is called as a race condition, because the three threads are racing among
other to complete the method. This example used sleep( ) to compose the effects
repeatable and obvious. In most situations, a race situation is more subtle and less
ty
expected, because developer can’t be sure when the context switch will occur. This can
be a reason for program to run right one time and wrong the next.
To correct the previous code, developer must serialize access to call( ). i.e.,
si
developer must restrict its right of entry to only one thread at a time. To do this,
developer simply require to precede call( )’s statement with the keyword synchronized,
as shown below:
class Callmedemo { r
ve
synchronized void call(String m) {
This stopss other threads from entering call( ) while another thread is utilizing it.
After synchronized has been added to call( ), the output of the program will look like
ni
this:
[Hello]
[Synchronized]
U
[World]
Any time that developers have a method, or group of method, that influence the
ity
class First
(c
{
Notes
e
System.out.print (“[“+k);
try
in
{
Thread.sleep(1000);
nl
}
catch(InterruptedException e)
O
{
e.printStackTrace();
ty
}
System.out.println (“]”);
si
}
{
r
ve
String k;
First fobj;
ni
{
U
fobj = fp;
k = str;
start();
ity
{
m
{
)A
fobj.display(k);
}
(c
{
Notes
e
public static void main (String[] args)
in
First fnew = new First();
nl
Second ss1= new Second (fnew,”To”);
O
}
ty
Output
[welcome]
si
[To]
[Java]
Loopholes of Synchronization
m
)A
(c
Notes
e
in
nl
O
ty
si
4.4.4 Resuming and stopping Threads
Prior to Java 2, a code utilized suspend( ) and resume( ), which are methods
r
declared by Thread, to pause and restart the execution of a thread. They can be
ve
represent as:
Thread t;
ity
NewThreadDemo(String threadname) {
name = threadname;
}
)A
try {
(c
System.out.println(name + “: “ + i);
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 307
Thread.sleep(200);
Notes
e
}
} catch (InterruptedException e) {
in
System.out.println(name + “ interrupted.”);
nl
System.out.println(name + “ exiting.”);
O
}
class SuspendResume {
ty
public static void main(String args[]) {
si
try {
Thread.sleep(1000);
ob1.x.suspend();
r
ve
System.out.println(“Suspending thread One”);
Thread.sleep(1000);
ni
ob1.x.resume();
ob2.x.suspend();
Thread.sleep(1000);
ity
ob2.x.resume();
} catch (InterruptedException e) {
m
}
)A
try {
ob1.x.join();
ob2.x.join();
} catch (InterruptedException e) {
Notes
e
System.out.println(“Main thread Interrupted”);
in
System.out.println(“Main thread exiting.”);
nl
}
Output
O
New thread: Thread[One,5,main]
One: 15
ty
New thread: Thread[Two,5,main]
Two: 15
si
One: 14
Two: 14
One: 13
r
ve
Two: 13
One: 12
Two: 12
ni
One: 11
Two: 11
U
Two: 10
Two: 9
ity
Two: 8
Two: 7
Two: 6
m
One: 10
One: 9
One: 8
(c
One: 7
One: 6
e
Waiting for threads to finish.
Two: 5
in
One: 5
Two: 4
nl
One: 4
Two: 3
O
One: 3
Two: 2
ty
One: 2
Two: 1
One: 1
si
Two exiting.
One exiting.
The suspend( ) method of the Thread class was criticize by Java 2 several years
ago. This was done because suspend( ) can from time to time root of serious system
failures. The resume( ) method is also criticize. It does not create problems, but cannot
U
Because developer can’t now use the suspend( ), resume( ), or stop( ) methods to
manage a thread, developer might be thinking that no way exists to pause, restart, or
ity
terminate a thread. But, luckily, this is not true. In its place, a thread must be considered
so that the run( ) method regularly checks to establish whether that thread should
suspend, resume, or stop its own execution. Typically, this is achieved by creating a flag
variable that signifies the execution condition of the thread.
m
Providing this flag is set to “running,” the run( ) method must carry on to allow the
thread execute. If this variable is set to “suspend,” then the thread must break. If it is set
to “stop,” then the thread must end.
)A
The below example exemplify how the wait( ) and notify( ) methods that are
incorporated from Object can be used to manage the execution of a thread. This
example is identical to the program in the previous section. Though, the criticized
method calls have been removed.
(c
looks for suspendFlag. If that variable is true, the wait( ) method is called to suspend
Notes
e
the execution of the thread. The mysuspend( ) method puts suspendFlag to true. The
myresume( ) method sets suspendFlag to false and calls notify( ) to wake up the thread.
Finally, the main( ) method has been changed to call the mysuspend( ) and myresume(
in
) methods.
nl
String name; // name of thread
Thread t;
O
booleansuspendFlag;
NewThreadDemo(String threadname) {
name = threadname;
ty
t = new Thread(this, name);
si
suspendFlag = false;
} r
ve
public void run() {
try {
System.out.println(name + “: “ + i);
Thread.sleep(200);
U
synchronized(this) {
while(suspendFlag) {
ity
wait();
}
m
} catch (InterruptedException e) {
)A
System.out.println(name + “ interrupted.”);
System.out.println(name + “ exiting.”);
}
(c
void mysuspend() {
suspendFlag = true;
Notes
e
}
in
suspendFlag = false;
notify();
nl
}
O
class SuspendResume {
ty
NewThreadDemo ob1 = new NewThreadDemo(“One”);
try {
si
Thread.sleep(1000);
ob1.mysuspend();
ob1.myresume();
ni
ob2.mysuspend();
U
Thread.sleep(1000);
ob2.myresume();
ity
} catch (InterruptedException e) {
try {
ob1.t.join();
(c
ob2.t.join();
} catch (InterruptedException e) {
e
}
in
}
nl
Output:
The output of this program is identical to the previous code output.
O
4.4.5 A code snippet to demonstrate thread with and without
synchronization
ty
Multithreading Example without Synchronization:
class PrintDemo {
si
public void printCount() {
try {
} catch (Exception e) {
ni
System.out.println(“Thread interrupted.”);
}
U
private Thread x;
PrintDemo PD;
threadName = name;
PD = pd;
}
(c
PD.printCount();
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 313
e
}
in
System.out.println(“Starting “ + threadName );
if (x == null) {
nl
x = new Thread (this, threadName);
x.start ();
O
}
ty
}
T1.start();
ni
T2.start();
U
try {
T1.join();
ity
T2.join();
} catch ( Exception e) {
System.out.println(“Interrupted”);
m
}
)A
Output
Starting Thread - 1
(c
Starting Thread - 2
Counter --- 5
Counter --- 4
Notes
e
Counter --- 3
Counter --- 5
in
Counter --- 2
Counter --- 1
nl
Counter --- 4
O
Counter --- 3
Counter --- 2
ty
Counter --- 1
si
Multithreading Example with Synchronization
class PrintDemo {
r
public void printCount() {
ve
try {
System.out.println(“Counter --- “ +i );
ni
} catch (Exception e) {
U
System.out.println(“Thread interrupted.”);
}
ity
private Thread t;
m
PrintDemo PD;
)A
threadName = name;
PD = pd;
(c
synchronized(PD) {
Notes
e
PD.printCount();
in
System.out.println(“Thread “ + threadName + “ exiting.”);
nl
public void start () {
System.out.println(“Starting “ + threadName );
O
if (t == null) {
ty
t.start ();
si
}
T1.start();
U
T2.start();
try {
ity
T1.join();
T2.join();
} catch ( Exception e) {
m
System.out.println(“Interrupted”);
}
)A
Output
(c
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Notes
e
Counter --- 4
Counter --- 3
in
Counter --- 2
Counter --- 1
nl
Thread Thread - 1 exiting.
Counter --- 5
O
Counter --- 4
Counter --- 3
ty
Counter --- 2
Counter --- 1
Summary
●● Synchronized methods is invoked. Once a thread is inside a synchronized method,
ity
no other Thread can invoke any other synchronized system on the same object.
This facilitates developer to write very clear and brief multithreaded code.
●● Synchronization is easy in Java language, because all objects have their own
implied monitor linked with them. To enter an object’s monitor, just invoke a
m
no class “Monitor”; in its place, Each object has its own understood monitor that is
automatically entered when one of the object’s.
●● The synchronised method is used to secure an object’s access to a shared
resource. When a thread calls a synchronised method, the lock for that object is
automatically acquired and released when the thread completes its task.
(c
e
which can cause a subtle concurrent issue if we don’t use synchronized or volatile
keywords.
in
●● Synchronized keyword involves locking and unlocking. before entering into a
synchronized method or block thread needs to acquire the lock, at this point it
reads data from main memory than cache and when it releases the lock, it flushes
nl
write operation into main memory which eliminates memory inconsistency errors.
Activity
1. What will be the output of below program?
O
class Line
ty
synchronized public void getLine()
si
for (int i = 0; i < 3; i++)
System.out.println(i);
r
ve
try
Thread.sleep(400);
ni
catch (Exception e)
U
System.out.println(e);
}
ity
}
m
{
)A
Line line;
Train(Line line)
{
(c
this.line = line;
@Override
Notes
e
public void run()
in
line.getLine();
nl
}
class GFG
O
{
ty
{
si
// same Object.
r
Train train2 = new Train(obj);
ve
// both threads start executing .
train1.start();
ni
train2.start();
}
U
Glossary
)A
●● Suspend Method: The suspend() method of thread class puts the thread from
running to waiting state. This method is used if you want to stop the thread
execution and start it again when a certain event occurs. This method allows a
e
using the resume() method.
●● Race condition: If a multiple threads want to operate on a same object
in
simultaneously. There may be problem of data inconsistency. This condition is
called Race condition.
Further Readings:
nl
1. Java threads, Scott Oaks
2. Mastering Concurrency Programming with Java 8, Javier Fernández Gonzalez
O
3. Programming Concurrency on the JVM: Mastering Synchronization, STM, and
Actors, Venkat Subramaniam
4. The Java Native Interface: Programmer’s Guide and Specification, Sheng
ty
Liang
5. Essential JNI: Java Native Interface, Rob Gordon
6. The Java Application Programming Interface, Frank Yellin and James Gosling
3. pause restart
4. synchronized block
U
ity
m
)A
(c
e
Structure:
in
5.1 Introduction to Applet Class
5.1.1 Introduction to applets
nl
5.1.2 Lifecycle of Applet
5.1.3 Methods of Applet class
O
5.1.4 Applet vs Application
5.1.5 Embedding Applet in HTML Page
5.1.6 A code snippet to implement Applet
ty
5.2 Introduction to Graphic class
5.2.1 Introduction to Graphic class
5.2.2 Methods in Graphic class
si
5.2.3 A code snippet to create different shapes.
5.2.4 Using loops in applet
5.3 Introduction to AWT r
ve
5.3.1 Introduction to AWT package
5.3.2 Classes in AWT package
5.3.3 Role of Layout manager in applet
ni
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Lifecycle of Applet
●● Methods of Applet class
O
●● Compare Applet v/s Application
●● Embedding Applet in HTML Page
●● A code snippet to implement Applet
ty
Introduction
Java language was launched on 23-Jan-1996(JDK 1.0) and at that time it only
si
compatible CUI(Character User Interface) application. But in 1996 Visual Basic of
Microsoft was favored for GUI programming. So the Java developers in rush (i.e. within
7 days) have given the compatible for GUI from Operating System (OS). Now, the
r
mechanism like button, etc. was platform-dependent (i.e. in each platform there will be
different size, shape button). But they did the connection of such mechanism from all
ve
platforms and gave a small library which contains these intersections and it is available
in AWT(Abstract Window Toolkit) technology but it doesn’t have advanced features like
dialogue box, etc.
ni
“Netscape” company is also known as “Mozilla Firefox” which we all be familiar with is a
browser. Now, these two companies have urbanized a technology called “SWING” and
the advantage is that the SWING mechanisms are produced by Java language itself.
ity
Therefore now it is independent as well as some additional attributes have also been
plug-in which were not in AWT technology. So we can articulate that SWING is much
more advanced as compared to AWT technology.
first are those based directly on the Applet class. These applets employ the Abstract
Window Toolkit (AWT) to give the graphic user interface (or use no GUI at all). This
style of applet has been available since Java language was first produced.
The second types of applets are those which are based on the Swing class
(c
JApplet. Swing applets utilize the Swing classes to offer the Graphical User Interface.
Swing offers a better-off and often easier-to-use user interface than does the AWT.
Therefore, Swing-based applets are now the most popular. However, traditional
Amity Directorate of Distance & Online Education
322 Object Oriented Programming Using Java
AWT-based applets are still used by the developers, especially when only a very
Notes
e
straightforward user interface is necessary. Consequently, both AWT- and Swing-based
applets are applicable.
in
Because JApplet encapsulate Applet, all the features and characteristics of Applet
are also accessible in JApplet, and most of the information is applies to both types of
applets.
nl
Applets
Applets are little applications that are examined on an Internet server, elated
O
over the Internet, without human intervention installed, and execute as part of a
web document. After an applet retrieve on the client side, it has restricted access
to resources so that it can construct a graphical user interface and run intricate
computations without introducing the threat of viruses or breaching data reliability.
ty
The essentials connected to the construction of an applet are accessible below,
because applets are not planned in the same way as the programs that have been used
so far. Applets vary from console-based applications in a number of key areas.
si
Let’s start with the simple applet code shown below:
import java.awt.*;
import java.applet.*; r
ve
public class SimpleAppletdemo extends Applet {
}
U
This applet starts with two import statements. The first invoke the Abstract Window
Toolkit (AWT) classes. Applets work together with the end-user (either directly or
indirectly) with the help of AWT, not with the help of console-based I/O classes. The
ity
AWT includes sustain for a window-based, graphical user interface. As developer might
expect, the AWT is quite big and sophisticated. Luckily, this straightforward applet
makes very limited use of the AWT. The second call statement invokes the applet
package, which include the class Applet. Every applet that a developers create must be
a subclass of Applet.
m
The next line in the code defines the class SimpleAppletdemo. This class must be
defined as public, because it will be used by code that is exterior the program.
)A
paint( ) is also called when the applet starts execution. Whatever the reason, whenever
the applet have to redraw its result, paint( ) is called. The paint( ) method has one
stricture of type Graphics. This parameter includes the graphics context, which defines
Notes
e
the graphics environment in which the applet is executing. This context is utilized
whenever output to the applet is needed.
in
Inside paint( ) is a invoke to drawString( ), which is a associate of the Graphics
class. This method outputs a string start at the particular a,b location. It has the
following syntax:
nl
void drawString(String message, int a, int b)
Here, message is the string to be output starting at a,b. In Java language window,
the upper-left corner is location 0,0. The call to drawString( ) in the applet causes the
O
message “A Simple Java Applet” to be displayed starting at location 10,10.
If you have pay attention to the code you would have realize that the applet does
not have a main( ) method. Unlike Java language code, applets do not start execution
ty
at main( ). Actually, many of applets don’t still have a main( ) method. In its place, an
applet starts execution when the name of its class is passed or invoked to an applet
viewer or to a network browser.
si
After developer enter the source code for SimpleApplet, compile it in the same way
that developer have been compiling codes. Though, executing SimpleApplet involves
a special procedure. In fact, there are two ways in which developer can execute an
applet: r
ve
1. Running the applet inside a Java-compatible web browser.
2. Using an applet viewer, such as the regular tool, appletviewer. An applet viewer runs
developer applet in a window. This is usually the quickest and simplest way to check
your applet
ni
To run an applet in a web browser, developer need to write a short HTML text file
U
that includes a tag that loads the applet. At present, Java language suggests using the
APPLET tag for this purpose. Here is the HTML code that runs SimpleApplet:
</applet>
The width and height expression defines the dimensions of the display area used
by the applet. After developercreate this file, developer can run this on his/her browser
m
To runSimpleApplet with an applet viewer, developer might also execute the HTML
file shown above. For example, if the earlier HTML file is known as RunAppdemo.html,
)A
C:\>appletviewer RunAppdemo.html
Though, a more suitable method exists that developer can use to accelerate
testing. Simply contain a comment at the head of his/her Java language source code
(c
file that includes the APPLET tag. By doing so, developer code is documented with a
prototype of the needed HTML statements, and developer can test your compiled
applet just by opening the applet viewer with your Java language source code file. If
Notes
e
developers use this method, the SimpleApplet source code file looks like this:
import java.awt.*;
in
import java.applet.*;
/*
nl
<applet code=”SimpleApplet” width=300 height=80>
</applet>
O
*/
ty
a.drawString(“A Simple Java Applet”, 10, 10);
si
}
r
ve
ni
U
Applet Architecture
An applet is a window-based program or code. As such, Applet architecture is
ity
system informs the applet about an event by invoking an event handler that has been
given by the applet. Once this occurs, the applets have to take suitable action and then
swiftly return.
)A
This is a vital point. For the majority part, developer applet should not enter a
“mode” of operation in which it manages control for an extensive period. In its place, it
must carry out precise actions in reply to events and then return control to the run-time
system. In those phases in which developer applet needed to carry out a frequent task
(c
on its own (for example, displaying a scrolling message across its window), developer
must start an extra thread of execution.
Second, the end-user starts interacting with an applet not the other way around.
Notes
e
As you know, in a non windowed program, when the program needs contribution from
the user, it will prompt the user and then invoke some input method, such as readLine(
). But this not works in an applet. In its place, the user connects with the applet as they
in
wants, when they want.
nl
which the applet must act in response. For example, when an end-user presses any
key inside the applet’s window, a key-pressed event is generated. Whenever the end
user communicates with one of these controls, always there will be an event which is
generated.
O
While the architecture of an applet is not as simple to recognize as that of a
console-based program, Java language makes it easier. If developer has written
programs for Windows, developer must know how threatening that environment can
ty
be. Luckily, Java language provides a much cleaner approach that is more rapidly
mastered.
si
5.1.2 Lifecycle of Applet
All but the most insignificant applets override a set of methods that gives the basic
instrument by which the browser or applet viewer interfaces to the applet and manages
r
its execution. Four of these functions are init( ), start( ), stop( ), and destroy( ), relate to
ve
all applets and are decaled by Applet. Default implementations for all of these methods
are given. Applets do not reacquire to override those methods they do not employ.
Though, only very simple applets will not require declaring all of them.
AWT-based applets will also supersede the paint( ) method, which is declared by
ni
the AWT Component class. This method is invoked when the applet’s output need to be
redisplayed. (Swing-based applets use a different mechanism to accomplish this task.).
Example showing how 5 methods assembled
U
import java.awt.*;
import java.applet.*;
ity
/*
</applet>
m
*/
// Called first.
e
// start or resume execution
in
// Called when the applet is stopped.
nl
// suspends execution
O
/* Called when applet is terminated. This is the last
method executed. */
ty
public void destroy() {
si
// Called when an applet’s window must be restored.
}
ni
Output
U
ity
Notes
e
in
nl
O
ty
1. init( ): The init( ) method is the first method which is invoked. This is where developer
should initialize the variables which will be used in program. This method is called
only once during the execution time of your applet. It can be represent as:
si
public void init()
//Define variables// r
ve
}
2. start( ): This is the second phase called after init(). It is also invoked to restart an
applet after it has been stopped. Whereas init( ) is called once—the first time when
ni
3. paint( ) The paint( ) method is invoked each time your applet’s result must be redrawn.
This situation can happen for quite a few reasons. For example,the applet window
possibly will be minimized and then restored or the window in which the applet is
m
running may be hide by another window and then unhide. paint( ) is also called when
the applet starts execution. There might be any reason but when the applet must
redraw its output, paint( ) method is invoked. The paint( ) method has only single
)A
parameter which of Graphics type. This parameter will include the graphics context,
which declares the graphics environment in which the applet is running. It can be
expressed as:
public void paint(Graphics graphics)
(c
}
Notes
e
4. stop( ): The stop( ) method is invoked when a web browser exits the HTML document
including the applet—when it goes to another page, for example. When stop( ) is
in
invoked, the applet is probably executing. Developer should use stop( ) to hang
threads that don’t require to execute when the applet is not able to be seen. You can
restart them when it appears again and invoke the start( ) if the user returns to the
nl
page. Its syntax will look like this.
public void stop()
O
// To stop the applet code
ty
5. destroy( ): The destroy( ) method is invoked when the environment defines that your
applet desires to be detached completely from memory. At this point, developer
should free up any resources the applet may be utilizing. It can be represent as:
si
public void destroy()
import java.awt.Graphics;
import javax.swing.JApplet;
)A
int painted;
(c
e
{
infomsgdemo(“init”);
in
double c = 81;
double d = 100;
nl
double e = 100;
O
double delta = 2.0*Math.PI / 3.0;
ty
a[i] = (int)(d + c*Math.cos(phi+i*delta));
si
painted = 0;
{
ni
infomsgdemo(“start”);
}
U
{
ity
infomsgdemo(“stop”);
{
)A
infomsgdemo(“destroy”);
infomsgdemo(“paint “ + ++painted);
Notes
e
g.drawLine(a[0],b[0],a[1],b[1]);
g.drawLine(a[1],b[1],a[2],b[2]);
in
g.drawLine(a[2],b[2],a[0],b[0]);
nl
public void infomsgdemo(String str)
O
System.out.println(str);
ty
}
si
getDocumentBase( ) and getCodeBase( )
Time and again, Developer will construct applets that will require to explicitly
r
loading media and text. Java language will permits the applet to load data from the
index holding the HTML file that initiated the applet (the document base) and the
ve
index from which the applet’s class file was loaded (the code base). These directories
are gives back as URL objects by getDocumentBase( ) and getCodeBase( ). They
can be joined with a string that names the file developer wants to load. To really
load another file, developer will utilize the showDocument( )method declared by the
ni
import java.awt.*;
U
import java.applet.*;
import java.net.*;
ity
/*
</applet>
m
*/
String i;
(c
e
url = getDocumentBase(); // get document base
in
a.drawString(msg, 30, 50);
nl
}
Output:
O
ty
AppletContext and showDocument( )
si
One application of Java language is to use lively images and animation to offer
a graphical means of navigating the Web that is more striking than easy text-based
links. To permit your applet to shift control to another URL, developer must use the
r
showDocument( ) method declared by the AppletContext interface.
ve
Applet Context is an interface that allows developer to get information from the
applet’s running environment. The context of the at present executing applet is get by a
call to the getAppletContext( ) method declared by Applet.
ni
Inside an applet, once developer have obtained the applet’s context, developer
can get another document into view by invoking showDocument( )method. This
showDocument() method has no return value and throws no exception if it fails to
U
import java.awt.*;
import java.applet.*;
)A
import java.net.*;
/*
</applet>
*/
e
public void start() {
AppletContext ac = getAppletContext();
in
URL url = getCodeBase(); // get url of this applet
try {
nl
ac.showDocument(new URL(url+”Test.html”));
} catch(MalformedURLException e) {
O
showStatus(“URL not found”);
ty
}
Method Description
si
Applet getApplet(String Returns the applet specified by appletName if it is within
appletName) the current applet context. Otherwise, null is returned.
Enumeration<Applet>
getApplets()
rReturns an enumeration that contains all of the applets
within the current applet context.
ve
AudioClip Returns an AudioClip object that encapsulates the audio
getAudioClip(URL urt) clip found at the location specified by urt.
Image getimage(URL ur) Returns an Image object that encapsulates the image
found at the location specified by url.
ni
InputStream strm) key The key is deleted from the invoking object if strm is
null.
void showDocument(URL Brings the document at the URL specified by url into
urf) view. This method may not be supported by applet
m
viewers.
void showDocument(URL Brings the document at the URL specified by urf into
urf, view. This method may not be supported by applet
)A
e
The APPLET tag in HTML permits developer to pass parameters to your applet. To
get back a parameter, developer use the getParameter( ) method. It returns the value
in
of the particular parameter in the form of a String object. Therefore, for Boolean and
numeric values, developer will required to transform their string representations into
their internal Types.
nl
Example to explain passing parameters:
// Use Parameters
O
import java.awt.*;
import java.applet.*;
/*
ty
<applet code=”ParamDemo” width=200 height=60>
si
<param name=fontSize value=14>
*/
String a;
int b;
U
float leading;
booleanactive;
ity
String param;
m
a = getParameter(“a”);
if(a == null)
a = “Not Found”;
)A
param = getParameter(“b”);
try {
b = Integer.parseInt(param);
else
Amity Directorate of Distance & Online Education
334 Object Oriented Programming Using Java
catch(NumberFormatException e) {
Notes
e
b = -1;
in
param = getParameter(“leading”);
try {
nl
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
O
else
leading = 0;
ty
} catch(NumberFormatException e) {
leading = -1;
si
param = getParameter(“accountEnabled”);
if(param != null)
r
active = Boolean.valueOf(param).booleanValue();
ve
}
// Display parameters.
ni
Output
m
)A
(c
message to the status window of the browser or applet viewer on which it is executing.
Notes
e
For this developer require to invoke showStatus( ) with the string that developer want
displayed. The status window is an ideal place to give the end-user advice about what
is happening in the applet, put forward options, or possibly report some types of issues.
in
The status window also makes an excellent debugging help, because it gives developer
a straightforward way to output information about your applet.
nl
Example of applet using showStatus( ):
import java.awt.*;
O
import java.applet.*;
/*
ty
<applet code=”StatusWindow” width=200 height=30>
</applet>
si
*/
}
ity
Output
m
)A
e
Here, newColor defines the new color which developer want to use. The class
Color declares the constants revealed here that can be used to identify colors: Colors
in
code are given below
Color.black Color.magenta
Color.blue Color.orange
nl
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
O
Color.green Color.yellow
Color.lighGray
ty
An excellent place to set the foreground and background colors is inside the init( )
method. Certainly developer can change these colors as frequently as essential during
the running of his/her applet.
si
Developer can obtain the current settings for the background and foreground
colors by invoking getBackground( ) and getForeground( ), in that order. They are also
declared by Component and are shown here:
Color getBackground( )
r
ve
Color getForeground( )
import java.awt.*;
import java.applet.*;
U
/*
</applet>
ity
*/
String a;
m
setBackground(Color.cyan);
setForeground(Color.red);
e
a += “ Inside start( ) --”;
in
// Display a in applet window.
nl
a += “ Inside paint( ).”;
O
}
ty
Output:
r si
ve
A Simple Banner Applet
To demonstrate repaint( ), a simple banner applet is urbanized. This applet moves
a message, from right to left, across the applet’s window. Since the moving of the
message is a recurring task, it is done by another thread, created by the applet when it
ni
import java.awt.*;
U
import java.applet.*;
/*
</applet>
*/
Thread a = null;
)A
int state;
booleanstopFlag;
setBackground(Color.cyan);
setForeground(Color.red);
Notes
e
}
// Start thread
in
public void start() {
a = new Thread(this);
nl
stopFlag = false;
a.start();
O
}
ty
public void run() {
char c;
// Display banner
si
for( ; ; ) {
try {
repaint();
r
ve
Thread.sleep(250);
c = s.charAt(0);
ni
s = s.substring(1, s.length());
s += c;
U
if(stopFlag)
break;
} catch(InterruptedException e) {}
ity
stopFlag = true;
)A
a = null;
}
Notes
e
}
in
Output
nl
O
Let’s see how this applet work. First, notice that SimpleBannerDemo extends
Applet, as predicted, but it also implements Runnable. This is essential, since the applet
will be constructing a second thread of execution that will be used to move the banner.
ty
Inside init( ), the foreground and background colors of the applet are declared.
After starting, the run-time system invoksstart( ) to start the applet running. Inside
start( ), a new thread of execution is constructed and allocated to the Thread variable a.
si
Then, the boolean variable stopFlag, which controls the running of the applet, is kept to
false. Next, the thread is initiated by a invoke to a.start( ). Remember that a.start( ) calls
a method declared by Thread, which causes run( ) to begin executing. It does not basis
r
a call to the version of start( ) declared by Applet. These are two separate methods.
ve
Inside run( ), the characters in the string contained in s are frequently rotated
left. flanked by each rotation, a call to repaint( ) is complete. This finally causes the
paint( ) method to be called, and the current contents of s are displayed. Between
each iteration, run( ) sleeps for a section of a second. The net effect of run( ) is that the
ni
contents of s are scrolled right to left in a continuously moving display. The stopFlag
variable is checked on each step. When it is true, the run( ) method ends.
U
Java Application:
m
Notes
e
in
nl
O
Java Applet:
ty
An applet is a Java language program that can be entrenched into a web page.
It runs within the web browser and works at user side. An applet is surrounded in an
HTML page using the APPLET or OBJECT tag and hosted on a web server. Applets are
si
used to create the web site more lively and enjoyable.
r
ve
ni
U
ity
Main() Method The execution of the Java The Java applet initializes
application begins with the main() through the init(). It does
method The usage of the main() is not require the usage of any
a prerequisite here. main() method.
Execution It cannot run alone, but it requires It cannot run independently
(c
e
application priorly and explicitly on require any prior installation.
a local computer.
in
Communication it is possible to establish it cannot really establish
among other communication with the other communication with the other
Servers servers. servers.
nl
Read The Java applications are capable A Java applet cannot perform
and Write of performing the read and write these applications on any
Operations operations on various files present local computer.
in a local computer.
O
Restrictions These can easily access the file or These cannot access the
data present in a computer system file or data available on any
or device. system or local computers.
ty
Security Jave applications are pretty Java applets are not very
trusted, and thus, come with no trusted Thus, they require
security concerns. security.
si
5.1.5 Embedding Applet in HTML Page
The representation for a fuller form of the APPLET tag is shown below.
ni
< APPLET
[CODEBASE = codebaseURL]
U
CODE = appletFile
[ALT = alternateText]
ity
[NAME = appletInstanceName]
[ALIGN = alignment]
m
>
)A
...
</APPLET>
e
of the applet code, which is the directory that will be searched for
the applet’s executable class file (specified by the CODE tag). The
in
HTML document’s URL directory is used as the CODEBASE if this
attribute is not specified. The CODEBASE does not have to be on
the host from which the HTML document was read.
nl
CODE CODE is a required attribute that gives the name of the file
containing your applet’s compiled .class file. This file is relative to
the code base URL of the applet, which is the directory that the
HTML file was in or the directory indicated by CODEBASE if set.
O
ALT The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser recognizes the
APPLET tag but can’t currently run Java applets. This is distinct
ty
from the alternate HTML you provide for browsers that don’t
support applets.
NAME NAME is an optional attribute used to specify a name for the applet
instance, Applets must be named in order for other applets on the
si
same page to find them by name and communicate with them. To
obtain an applet by name, use getApplet(), which is defined by the
AppletContext interface.
WIDTH and r
WIDTH and HEIGHT are required attributes that give the size (in
ve
HEIGHT pixels) of the applet display area.
ALIGN ALIGN is an optional attribute that specifies the alignment of the
applet. This attribute is treated the same as the HTML IMG tag with
these possible values: LEFT, RIGHT, TOP BOTTOM, MIDDLE,
ni
import java.applet.*;
import java.awt.*;
)A
import java.net.*;
private AppletContextcontext;
context = this.getAppletContext();
Notes
e
String iURL = this.getParameter(“image”);
if(iURL == null) {
in
iURL = “java.jpg”;
nl
try {
O
image = context.getImage(url);
} catch (MalformedURLException e) {
ty
e.printStackTrace();
si
}
}
U
import java.awt.*;
import java.net.*;
private AudioClipclip;
private AppletContextcontext;
)A
context = this.getAppletContext();
if(aURL == null) {
aURL = “default.au”;
}
Notes
e
try {
in
clip = context.getAudioClip(url);
} catch (MalformedURLException e) {
nl
e.printStackTrace();
O
}
ty
public void start() {
if(clip != null) {
clip.loop();
si
}
clip.stop();
ni
}
U
initiate an applet from both an HTML document and from an applet viewer.
Summary
Notes
e
●● An applet is a type of programme that is embedded in a website to generate
dynamic content. It operates on the client side and runs within the browser.
in
●● Applets are little applications that are examined on an Internet server, elated over
the Internet, without human intervention installed, and execute as part of a web
document.
nl
●● There are two ways in which developer can execute an applet:
◌◌ Running the applet inside a Java-compatible web browser.
O
◌◌ Using an applet viewer, such as the regular tool, appletviewer. An applet
viewer runs developer applet in a window. This is usually the quickest and
simplest way to check your applet
●● It is significant to recognize in a broad way how the event-driven architecture
ty
impacts the plan of an applet. An applet seems like a set of interrupt service
routines. An applet waits till an event happened.
●● All but the most insignificant applets override a set of methods that gives the
si
basic instrument by which the browser or applet viewer interfaces to the applet
and manages its execution. Four of these functions are init( ), start( ), stop( ), and
destroy( ), relate to all applets and are decaled by Applet.
●●
r
Java Application is just like a Java language program that executes on a
ve
fundamental operating system with the support of a virtual machine. It is also
recognized as an application program. The graphical user interface is not essential
to run the java applications.
ni
Activity
1. Create a program to insert below image using applet?
U
ity
m
Glossary
Notes
e
●● CUI: Character User Interface
●● GUI: Graphic User Interface
in
●● OS: Operating System
●● AWT: Abstract Window Toolkit
nl
●● HTML: Hypertext Markup Language
●● <applet code=”SimpleApplet” width=300 height=80>
O
●● </applet>
●● The width and height expression defines the dimensions of the display area used
by the applet. After developer creates this file, developer can run this on his/her
browser and then load this file, which causes Simple Applet to be executed.
ty
●● init( ): The init( ) method is the first method which is invoked. This is where
developer should initialize the variables which will be used in program.
si
●● start( ): This is the second phase called after init(). It is also invoked to restart an
applet after it has been stopped.
●● paint( ) The paint( ) method is invoked each time your applet’s result must be
redrawn. r
ve
●● stop( ): The stop( ) method is invoked when a web browser exits the HTML
document including the applet
●● destroy( ): The destroy( ) method is invoked when the environment defines that
your applet desires to be detached completely from memory.
ni
applet’s executable class file (specified by the CODE tag). The HTML
document’s URL directory is used as the CODEBASE if this attribute
is not specified. The CODEBASE does not have to be on the host
from which the HTML document was read.
ity
CODE CODE is a required attribute that gives the name of the file containing
your applet’s compiled .class file. This file is relative to the code base
URL of the applet, which is the directory that the HTML file was in or
the directory indicated by CODEBASE if set.
ALT The ALT tag is an optional attribute used to specify a short text
m
applets.
NAME NAME is an optional attribute used to specify a name for the applet
instance, Applets must be named in order for other applets on the
same page to find them by name and communicate with them. To
obtain an applet by name, use getApplet(), which is defined by the
(c
AppletContext interface.
WIDTH and WIDTH and HEIGHT are required attributes that give the size (in
Notes
e
HEIGHT pixels) of the applet display area.
ALIGN ALIGN is an optional attribute that specifies the alignment of the
in
applet. This attribute is treated the same as the HTML IMG tag with
these possible values: LEFT, RIGHT, TOP BOTTOM, MIDDLE,
BASELINE, TEXTTOP ABSMIDDLE, and ABSBOTTOM.
nl
VSPACE and These attributes are optional VSPACE specifies the space, in pixels,
HSPACE above and below the applet. HSPACE specifies the space, in pixels,
on each side of the applet. They’re treated the same as the IMG tag’s
VSPACE and HSPACE attributes.
O
PARAM The PARAM tag allows you to specify applet-specific arguments in an
NAME and HTML page. Applets access their attributes with the getParameter()
VALUE method.
ty
Further Readings:
1. An Introduction to Programming with Java Applets, Elizabeth Boese
2. Java Applet Powerpack, Tad Ringo, Robin Drake
si
3. Programming Concurrency on the JVM: Mastering Synchronization, STM, and
Actors, Venkat Subramaniam
4. r
The Java Application Programming Interface, Frank Yellin and James Gosling
ve
5. Developing Professional Java Applets, K. C. Hopson and Stephen E. Ingram
1. HTML
2. program or code
U
3. control
4. event
5. Applet Context
ity
6. setBackground( )
7. APPLET
m
)A
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● What are Methods in Graphic class
●● A code snippet to create different shapes.
O
●● How to use loops in applet
Introduction
The AWT supports a rich collection of graphics methods. All graphics are pinched
ty
relative to a window. This can be the major window of an applet, a child window of an
applet, or a separate application window. The source of each window is at the top-left
corner and is 0,0. Coordinates are described in pixels. All result to a window takes place
si
all the way through a graphics context. A graphics context is embedded by the Graphics
class and is received in two ways:
r
ve
ni
graphics color, which is always black by default. When a graphics object is made that
surpass the dimensions of the window, output is without human intervention clipped to
fit into applet window.
ity
The Graphics class can be defined as conceptual super class for all graphics
contexts which permit an application to draw onto mechanism that can be display on
various devices or against off-screen images as well.
A Graphics object includes all state information necessary for the basic rendering
m
Notes
e
in
nl
O
Expression for Java.awt.Graphics class is:
ty
public abstract class Graphics extends Object
si
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*; r
ve
import java.awt.geom.*;
public GraphicsDemo(){
ni
super(“Java Demo”);
prepareGUI();
U
GraphicsDemo.setVisible(true);
}
m
setSize(400,400);
)A
addWindowListener(new WindowAdapter() {
System.exit(0);
}
(c
});
}
Notes
e
public void paint(Graphics gp) {
gp.setColor(Color.GRAY);
in
Font font = new Font(“Courier New”, Font.PLAIN, 20);
gp.setFont(font);
nl
gp.drawString(“Welcome to Java”, 50, 150);
O
}
Output
ty
5.2.2 Methods in Graphic class
r si
ve
Some of the common method in graphic class:
Method Description
ni
drawstring (String str, Draws the text given by the string str. The string is drawn
int x, int y) using the current color and font of the graphics context. x
specifies the position of the left end of the string. y is the y
coordinate of the baseline of the string. The baseline is a
U
drawLine(int x1, int -Draws a line from the point (x1 y1) to the point (x2,y2)
y1, int x2, int y2) The line is drawn as if with a pen that hangs one pixel to
the right and one pixel down from the (x,y) point where the
pen is located. For example, if g refers to an object of type
Graphics, then the command g.drawLine(x,y,x,y). which
m
int width, int height) inside the rectangle specified by x, y, width, and height. If
width equals height, the oval is a circle.
fillArc(int x; int y, int Draw a filled-in arc. This looks like a wedge of pie, whose
width, int height, crust is the arc that would be drawn by the drawArc method.
int startAngle, int
(c
arcAngle)
draw Ract (Int x, Draws the outline of a rectangle. The upper left comer is
Notes
e
int y, int width, int at (x,y), and the width and height of the rectangle are as
height)— specified. If width equals height, then the rectangle is a
in
square. If the width or the height is negative, then nothing
is drawn. The rectangle is drawn with the same pen that is
used for drawLine(). This means that the actual width of the
rectangle as drawn is width+1, and similarly for the height.
nl
There is an extra pixel along the right edge and the bottom
edge. For example, if you want to draw a rectangle around
the edges of the component, you can say drawRect(0, 0,
O
getWidth()-1, getHeight()-1),” where g is a graphics context
for the component. If you use gdrawRect(0, 0, getWidth().
getHeight) then the right and bottom edges of the rectangle
will be drawn outside the component.
ty
drawRoundRect(int Draws the outline of a rectangle with rounded corners. The
x, Inty, int width, int basic rectangle is specified by x, y, width, and height, but
height, int xdiam, int the corners are rounded. The degree of rounding is given
si
ydiam) by adiam and ydiam. The corners are arcs of an ellipse with
horizontal diameter xdiam and vertical diameter ydiam. A
typical value for xdiam and ydiam is 16, but the value used
r
should really depend on how big the rectangle is
ve
drawsDRect(int x, Draws the outline of a rectangle that is supposed to have a
int y, int width, Int three dimensional effect, as if it is raised from the screen or
height, boolean pushed into the screen. The basic rectangle is specified by
raised) x, y, width, and height The raised parameter tells whether
the rectangle seems to be raised from the screen or pushed
ni
int width, int height, specified by x, y, width, and height. The part drawn is an
int startAngle, int arc that extends arcAngle degrees from a starting angle at
arcAngle) startAngle degrees. Angles are measured with 0 degrees at
the 3 ddock position (the positive direction of the horizontal
axis). Positive angles are measured counterdockwise from
m
fillRect(int x, Inty, int Draws a filled-in rectangle. This fills in the interior of the
Notes
e
width, int height) rectangle that would be drawn by drawRect(x,y,width,height).
The extra piel along the bottom and right edges is not
in
included. The width and height parameters give the exact
width and height of the rectangle For example, if you wanted
to fill in the entire component, you could say’g AllRect(0, 0,
getWidth(), getHeight());
nl
5.2.3 A code snippet to create different shapes.
O
1. Drawing Lines
Lines are drawn by using of the drawLine( ) method.
// Draw lines
ty
import java.awt.*;
import java.applet.*;
si
/*
</applet> r
ve
*/
}
m
Output
)A
(c
e
import java.awt.*;
import javax.swing.*;
in
public class ellipse extends JApplet {
nl
{
setSize(300, 300);
O
}
ty
{
center of the
int x, y;
si
x = 150;
y = 175;
double x, y;
a = A * Math.sin(Math.toRadians(i));
b = B * Math.cos(Math.toRadians(i));
U
if (i != 0) {
g.drawLine((int)px + x, (int)py + y,
}
m
px = a;
)A
py = b;
}
(c
Output:
Notes
e
in
nl
O
ty
si
3. Draw a rectangle using drawLine(int x, int y, int x1, int y1)
import java.awt.*;
import javax.swing.*;
r
ve
public class rectangle extends JApplet {
setSize(400, 400);
repaint();
U
gp.setColor(Color.green);
m
Output:
Notes
e
in
nl
O
ty
si
4. Drawing Multiple rectangles in program: In this code we are constructing four
r
different types of rectangle, filled rectangle, rounded rectangle, filled round
rectangle. They can be represented as:
ve
void drawRect(int top, int left, int w, int h);
void drawRoundRect(int top, int left, int w, int h, int xDiam, int yDiam);
ni
void fillRoundRect(int top, int left, int w, int h, int xDiam, int yDiam);
import java.awt.*;
U
import java.applet.*;
/*
ity
</applet>
*/
m
}
Notes
e
Output
in
nl
O
ty
5. Java Program to draw a ellipse using drawOval(int x, int y, int width, int
height)
import java.awt.*;
si
import javax.swing.*;
// set size
setSize(400, 400);
ni
repaint();
}
U
{
ity
g.setColor(Color.red);
// draw a ellipse
}
)A
Output
(c
Notes
e
in
nl
O
ty
si
6. Drawing Arcs: Arc can be drawn using method drawArc( ) and fillArc( ). It can
be represent as:
r
void drawArc(int top, int left, int width, int height, int startAngle,
ve
int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,
int sweepAngle)
ni
import java.awt.*;
import java.applet.*;
U
/*
</applet>
*/
}
Amity Directorate of Distance & Online Education
358 Object Oriented Programming Using Java
Output
Notes
e
in
nl
O
7. Drawing Polygons Polygon can be draw using method drawPolygon( ) and
fillPolygon( ), These can be represented as:
void drawPolygon(int x[ ], int y[ ], int numPoints)
ty
void fillPolygon(int x[ ], int y[ ], int numPoints)
import java.awt.*;
si
import java.applet.*;
/*
r
<applet code=”HourGlass” width=230 height=210>
ve
</applet>
*/
int num = 5;
ity
}
m
Output
)A
(c
e
1. Implementing for loop in applet
in
import java.awt.*;
import java.applet.*;
nl
{
O
{
for(int a=1;a<=4;a++)
ty
{
if(a%2==0)
si
{
gs.fillOval(90,a*50+10,50,50);
gs.setColor(Color.black);
r
ve
}
else
{
ni
gs.drawOval(90,a*50+10,50,50);
gs.setColor(Color.red);
U
}
ity
</applet> */
m
Output:
)A
(c
e
import java.awt.*;
import java.applet.Applet;
in
import java.awt.event.*;
nl
public void paint (Graphics gp)
O
// The starting coordinates for each pie slice:
ty
int w = 100, h = 100;
si
int degrees = (int) (360.0 / numSlices);
int startAngle = 0;
int slice = 1;
r
ve
// Loop:
if (slice != 1) {
}
ity
if (slice % 2 == 0) {
g.setColor (Color.yellow);
else {
)A
g.setColor (Color.red);
}
(c
// Increment counter:
slice ++;
} // end-while
Notes
e
}
in
3. Loop in Animation applet
import java.awt.*;
nl
import java.awt.event.*;
import java.applet.Applet;
O
public class BouncingBallApplet extends Applet implements Runnable {
int dd;
ty
int ff;
Thread animatorThread;
si
public void init ()
animatorThread = null;
}
U
ff = 0;
if (animatorThread == null) {
m
}
)A
animatorThread.start ();
animatorThread = null;
Notes
e
}
in
{
nl
while (animatorThread != null) {
ff ++;
O
// Draw next frame.
repaint ();
ty
try {
Thread.sleep (dd);
si
catch (InterruptedException e) {
break;
}
r
ve
}
}
ni
{
U
setBackground (Color.red);
gp.setColor (Color.white);
ity
// Here’s how to get the size of the applet bounds within the program:
Dimension d = getSize();
m
if (ff % 2 == 1) {
else {
(c
}
Notes
e
}
in
Check your Understanding
1. The Graphics class declares a number of ____________________ functions.
nl
2. A ___________________________ includes all state information necessary for the
basic rendering operations that Java language supports.
O
Summary
●● A number of drawing functions are declared in the Graphics class. Each shape can
be drawn either edge-only or filled. Objects are drawn and filled in the graphics
ty
colour that is currently selected, which is always black by default. When a graphics
object is created that exceeds the dimensions of the window, the output is clipped
to fit into the applet window without the need for human intervention.
si
Activity
1. Create a code to using graphic class replicate below image.
r
ve
ni
U
ity
Glossary
●● AWT: Abstract Window Toolkit
●● Graphics Class: The Graphics class can be defined as conceptual super class for
(c
all graphics contexts which permit an application to draw onto mechanism that can
be display on various devices or against off-screen images as well.
Method Description
Notes
e
drawstring (String Draws the text given by the string str. The string is drawn using
str, int x, int y) the current color and font of the graphics context. x specifies the
in
position of the left end of the string. y is the y coordinate of the
baseline of the string. The baseline is a horizontal line on which
the characters rest. Some parts of the characters, such as the
nl
tail on a y or g. extend below the baseline
drawLine(int x1, int -Draws a line from the point (x1 y1) to the point (x2,y2) The line
y1, int x2, int y2) is drawn as if with a pen that hangs one pixel to the right and
one pixel down from the (x,y) point where the pen is located.
O
For example, if g refers to an object of type Graphics, then the
command g.drawLine(x,y,x,y). which corresponds to putting
the pen down at a point, colors the single pixel with upper left
ty
corner at the point (xy).
drawOval(int x; Draws the outline of an oval. The oval is one that just fits inside
int y, int width, int the rectangle specified by x, y, width, and height. If width equals
height) height, the oval is a circle.
si
fillArc(int x; int y, int Draw a filled-in arc. This looks like a wedge of pie, whose crust
width, int height, is the arc that would be drawn by the drawArc method.
int startAngle, int
arcAngle) r
ve
draw Ract (Int x, Draws the outline of a rectangle. The upper left comer is at (x,y),
int y, int width, int and the width and height of the rectangle are as specified. If
height)— width equals height, then the rectangle is a square. If the width
or the height is negative, then nothing is drawn. The rectangle
ni
is drawn with the same pen that is used for drawLine(). This
means that the actual width of the rectangle as drawn is
width+1, and similarly for the height. There is an extra pixel
U
along the right edge and the bottom edge. For example, if you
want to draw a rectangle around the edges of the component,
you can say drawRect(0, 0, getWidth()-1, getHeight()-1),”
where g is a graphics context for the component. If you use
ity
int ydiam) and ydiam. The corners are arcs of an ellipse with horizontal
diameter xdiam and vertical diameter ydiam. A typical value for
xdiam and ydiam is 16, but the value used should really depend
)A
e
int y, int width, Int three dimensional effect, as if it is raised from the screen or
height, boolean pushed into the screen. The basic rectangle is specified by
in
raised) x, y, width, and height The raised parameter tells whether the
rectangle seems to be raised from the screen or pushed into it.
The 3D effect is achieved by using brighter and darker versions
of the drawing color for different edges of the rectangle. The
nl
documentation recommends setting the drawing color equal to
the background color before using this method The effect won’t
work well for some colors.
O
drawArc(int x, Inty, Draws part of the oval that just fits inside the rectangle specified
int width, int height, by x, y, width, and height. The part drawn is an arc that extends
int startAngle, int arcAngle degrees from a starting angle at startAngle degrees.
arcAngle) Angles are measured with 0 degrees at the 3 ddock position
ty
(the positive direction of the horizontal axis). Positive angles are
measured counterdockwise from cero, and negative angles are
measured clockwise. To get an arc of a circle, make sure that
si
width is equal to height
illRoundRect(int x, Draws a filled-in rounded rectangle
Int y, int width, int
height, int xdiam, r
ve
int ydiam)
fillRect(int x, Inty, Draws a filled-in rectangle. This fills in the interior of the
int width, int height) rectangle that would be drawn by drawRect(x,y,width,height).
The extra piel along the bottom and right edges is not included.
ni
The width and height parameters give the exact width and
height of the rectangle For example, if you wanted to fill in the
entire component, you could say’g AllRect(0, 0, getWidth(),
getHeight());
U
Further Readings:
1. Graphic Java 1.2: Mastering the JFC, David M. Geary Java Applet Powerpack,
Tad Ringo, Robin Drake
ity
1. Drawing
2. Graphics object
(c
e
Objectives
in
At the end of this unit, you will be able to understand:
nl
●● Define the classess in AWT package
●● What is the Role of Layout manager in applet
O
●● A code snipet to implement applet with layout manager
Introduction
The AWT Abstract window toolkit includes several classes and methods that permit
ty
developer to create and manage windows. It is also the basis on which Swing is made.
The AWT is quite big and a full explanation would easily fill an entire book. Therefore, it
is not doable to describe in detail every AWT class, method, or instance variable.
si
Although a frequent use of the AWT is in applets, it is also utilized to construct
stand-alone windows that execute in a GUI environment, such as Windows. To execute
them, developer need to use an applet viewer or a Java-compatible web browser.
r
ve
One other point before starting. Today, most Java language programs utilize user
interfaces based on Swing. Because Swing provides better-off implementations than
does the AWT of some general GUI controls, such as buttons, lists, and check boxes,
it is easy to jump to the end that the AWT is no longer significant, that it has been
outdated by Swing. This assumption is, however, quite incorrect. As mentioned, Swing
ni
is built on the AWT. Thus, many features of the AWT are also features of Swing.
Java AWT (Abstract Window Toolkit) is an API to expand Graphical User Interface
(GUI) or windows-based applications in Java language.
ity
The java.awt package provides different classes for AWT API such as Event,
m
The AWT describes windows according to a class hierarchy that adds usability and
specificity with each segments. The two most widespread windows are those which
)A
are carryout from Panel, which is utilized by applets, and those which were taken out
from Frame, which construct a standard application window. Much of the performance
of these windows is carries out from their parent classes. Consequently, a explanation
of the class hierarchies connecting these two classes is essential to their perceptive.
Below Figure displays the class hierarchy for Panel and Frame.
(c
Notes
e
in
nl
O
The class hierarchy for Panel and Frame
ty
Component
si
In starting of the Abstract Window Toolkit hierarchy is the Component class.
Component is a conceptual class that contains all of the characteristics of a visual
component. All user interface basics that are showed on the monitor and that connect
r
with the end-user are the subclasses of Component. It declares over a hundred public
methods that are accountable for administrating events, such as mouse click and
ve
keyboard input by user, positioning of window and sizing the window. A Component
object is accountable for identification of the recent foreground and background colors
and the resently selected text font.
ni
Container
The Container class is a child class for Component. It has multiple methods that
permits other Component objects to be encapsulate in it. Other Container objects can
U
Panel
ity
The Panel class is an actual subclass of Container. It doesn’t put in any fresh
methods; it simply execute Container. A Panel may well be considering of as a
repeatedly nestable, existing screen part. Panel is the superclass for Applet. When
screen output is heading for an applet, it is traced on the exterior of a Panel object. In
m
essence, a Panel is a window that does not enclose any of these title bar, menu bar,
or border. This is why at client side they don’t see this substance when an applet is
execute with in a browser. When you execute an applet by means of an applet viewer,
)A
the applet viewer just only gives the title and border.
Window
Notes
e
The Window class constructs a top-level window. A top-level window is not included
within any other object; it sits in a straight line on the monitor. Usually, developer won’t
in
create Window stuff directly. In its place, developer will use a subclass of Window called
Frame, which is explained next.
Frame
nl
Frame contains what is usually consideration as “window.” It is a subclass of
Window and unilike panel it has a title bar, menu bar, borders, and resizing corners.
O
If developer constructs a Frame object from inside an applet, it will have a caution
message, like “Java Applet Window,” to the end-user that an applet window has been
constructed. This communication warns end-users that the window they see was
initiated by an applet and not by software executing on their computer. When a Frame
ty
window is produced by a stand-alone function rather than an applet, a normal window is
formed.
si
5.3.2 Classes in AWT package
The AWT classes are included in the java.awt package. It is one of Java’s language
biggest packages. Luckily, it is logically ordered in a top-down, hierarchical fashion, it is
r
easier to recognize some of the many AWT classes are list below in table.
ve
Class Description
AWT Event Encapsulates AWT events.
AWT Event Multicaster Dispatches events to multiple listeners.
Border Layout The border layout manager Border layouts use five
ni
Card Layout The card layout manager Card layouts emulate index cards.
Only the one on top is showing.
Check box Creates a check box control.
ity
Flow Layout The flow layout manager. Flow layout positions components
left to right, top to bottom.
e
Font Metrics Encapsulates various information related to a font. This
information helps you display text in a window.
in
Frame Creates a standard window that has a title bar, resize
corners, and a menu bar.
Graphics Encapsulates the graphics context. This context is used by
nl
the various output methods to display output in a window.
Graphics Device Describes a graphics device such as a screen or printer.
Graphics Environment Describes the collection of available Font and
O
GraphicsDevice objects.
Grid Bag Constraints Defines various constraints relating to the GridBagLayout
class.
Grid Bag Layout The grid bag layout manager. Grid bag layout displays
ty
components subject to the constraints specified by
GridBagConstraints.
Grid Layout The grid layout manager. Grid layout displays components
si
in a two-dimensional grid.
Image Encapsulates graphical images.
Insets Encapsulates the borders of a container.
Label r
Creates a label that displays a string.
ve
List Creates a list from which the user can choose. Similar to the
standard Windows list box.
Media Tracker Manages media objects.
Menu Creates a pull-down menu.
ni
System Colour Contains the colors of GUI widgets such as windows, scroll
bars, text, and others.
Text Area Creates a multiline edit control.
Text Component A superclass for TextArea and TextField.
Text Field Creates a single-line edit control.
(c
e
Since Frame is a subclass of Component, it contains all the characteristics
declared by Component. This means that developer can use and run a frame window
in
just like developer administer an applet’s main window.
nl
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
O
/*
ty
</applet>
*/
si
// Create a subclass of Frame.
r
implements MouseListener, MouseMotionListener {
ve
String s = “”;
SampleFrame(String title) {
super(title);
U
addMouseListener(this);
addMouseMotionListener(this);
ity
addWindowListener(adapter);
}
)A
}
(c
// save coordinates
Notes
e
msX = 20;
msY = 64;
in
s = “Mouse just entered child.”;
repaint();
nl
}
O
public void mouseExited(MouseEventevtObj) {
// save coordinates
ty
msX = 20;
msY = 64;
si
repaint();
// save coordinates
ni
msX = me.getX();
msY = me.getY();
U
s = “Down”;
repaint();
}
ity
// save coordinates
m
msX = me.getX();
msY = me.getY();
)A
s = “Up”;
repaint();
}
(c
// save coordinates
Notes
e
msX = me.getX();
msY = me.getY();
in
mvX = me.getX();
mvY = me.getY();
nl
s = “*”;
repaint();
O
}
ty
public void mouseMoved(MouseEvent me) {
// save coordinates
mvX = me.getX();
si
mvY = me.getY();
}
r
ve
public void paint(Graphics gp) {
}
U
SampleFramesampleFrame;
ity
public MyWindowAdapter(SampleFramesampleFrame) {
this.sampleFrame = sampleFrame;
}
m
sampleFrame.setVisible(false);
)A
// Applet window.
(c
SampleFramef;
Notes
e
String s = “”;
in
int mvX=0, mvY=0;
nl
public void init() {
O
f.setSize(200, 100);
f.setVisible(true);
ty
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
si
}
}
ni
f.setVisible(true);
// save coordinates
)A
msX = 0;
msY = 24;
repaint();
e
public void mouseExited(MouseEvent me) {
// save coordinates
in
msX = 0;
msY = 24;
nl
s = “Mouse just left applet window.”;
repaint();
O
}
ty
public void mousePressed(MouseEvent me) {
// save coordinates
msX = me.getX();
si
msY = me.getY();
s = “Down”;
repaint();
r
ve
}
// save coordinates
U
msX = me.getX();
msY = me.getY();
s = “Up”;
ity
repaint();
// save coordinates
)A
msX = me.getX();
msY = me.getY();
mvX = me.getX();
(c
mvY = me.getY();
s = “*”;
repaint();
Notes
e
}
in
public void mouseMoved(MouseEvent me) {
// save coordinates
nl
mvX = me.getX();
mvY = me.getY();
O
repaint(0, 0, 100, 20);
ty
// Display s in applet window.
si
gp.drawString(“Mouse at “ + mvX + “, “ + mvY, 0, 10);
}
r
ve
Output
ni
U
ity
m
e
void setLayout(LayoutManagerObj)
in
developer wish to disable the layout manager and position components manually then
he/she recquire pass null for Obj. If developer do this then developer will require to
determine the figure and location of each component manually, using the setBounds( )
nl
method declared by Component. Normally, developer will want to use a layout manager.
Java language has several predefined LayoutManager classes out which some are
explained below:
O
BorderLayout
The BorderLayout class executes a common layout style for top-level windows. It
ty
has 4 narrow, fixed-width components at the edges and one large area in the center.
The four sides are known to as north, south, east, and west. The core area is called the
center. BorderLayout can be express as
si
BorderLayout( )
r
The first expression construct a default border layout. The second allows developer
to identify the horizontal and vertical space left between components in ha and vb, in
ve
that order.
import java.awt.*;
import java.applet.*;
ity
import java.util.*;
/*
</applet>
*/
)A
setLayout(new BorderLayout());
(c
BorderLayout.NORTH);
e
BorderLayout.SOUTH);
in
add(new Button(“Left”), BorderLayout.WEST);
nl
“here we study how to use;\n” +
O
“code.\n\n\n”
ty
}
si
Output
r
ve
ni
U
FlowLayout
FlowLayout is the default layout. FlowLayout executes an easy layout style, which
is like to how words flow in a text editor. The path of the layout is administered by
ity
the container’s component direction property, which, by default, is left to right, top to
bottom. So, by default, components are laid out line-by-line starting at the upper-left
corner. In all cases, when a line is filled till the end, layout moves to the next line. A
small space is left among each component, on top of and ends, as well as left and right.
m
FlowLayout( )
)A
FlowLayout(int ha)
The first statement creates the default layout, which enter components at center
and leaves five pixels of space between each component. The second statement lets
(c
developer to specify how each line is needs to be aligned. Valid values for ha are as
follows:
FlowLayout.LEFT
Notes
e
FlowLayout.CENTER
FlowLayout.RIGHT
in
FlowLayout.LEADING
FlowLayout.TRAILING
nl
The third statement lets developer to specify the horizontal and vertical space left
among the components in ht and vt, respectively.
O
Checkbox code using left aligned flowlayout
import java.awt.*;
import java.awt.event.*;
ty
import java.applet.*;
/*
si
<applet code=”FlowLayoutDemo” width=250 height=200>
</applet>
*/
r
ve
public class FlowLayoutDemo extends Applet
implements ItemListener {
ni
String s = “”;
setLayout(new FlowLayout(FlowLayout.LEFT));
ity
add(Win7);
)A
add(Win2010);
add(Linux);
add(macOS);
(c
Win7.addItemListener(this);
Win2010.addItemListener(this);
Notes
e
Linux.addItemListener(this);
macOS.addItemListener(this);
in
}
nl
public void itemStateChanged(ItemEventie) {
repaint();
O
}
ty
public void paint(Graphics gp) {
s = “Current state: “;
gp.drawString(s, 6, 80);
si
s = “ Windows 7: “ + Win7.getState();
gp.drawString(s, 6, 100);
s = “ Linux: “ + Linux.getState();
ni
gp.drawString(s, 6, 140);
s = “ MacOS: “ + macOS.getState();
U
gp.drawString(s, 6, 160);
}
ity
Output:
m
)A
(c
GridLayout
Notes
e
GridLayout puts out components in a 2-D grid. When developer Invoke a
GridLayout, developer define the number of rows and columns he/she requires. The
in
GridLayout can be expressed as:
GridLayout( )
nl
GridLayout(int nR, int nC)
The first statements creates a single-column grid layout. The second statements
O
create a grid layout with the particular number of rows and columns. The third
statements lets developer to specify the horizontal and vertical space left between
components in ht and vt, respectively. Either nR or nC can be zero. Specifying nR as
ty
zero result-in unlimited-length columns. Specifying nC as zero result-in unlimited-length
rows.
CardLayout
si
The CardLayout class is exclusive between the other layout managers in that it
stores quite a few diverse layouts. This can be helpful for user interfaces with elective
components that can be animatedly enabled and disabled upon user contribution.
r
Developer can arrange the other layouts and have them hidden, ready to be activated
ve
when required. CardLayout method can be represented as:
CardLayout( );
The first statements creates a default card layout. The second statement lets
developer to identify the horizontal and vertical space left between components in ht
and vt respectively.
U
Use of a card layout needs a bit more work as compared to other layouts. The
cards are characteristically seized in an object of type Panel. This panel have to have
CardLayout selected as its layout manager. The cards that shape the deck are also
ity
Developer must present some method for the user to select among cards. One general
approach is to comprise one push button for each card in the deck.
)A
When all card panels are added to a panel, they are generally given a name.
Therefore, usually, developer will use this statement of add( ) when adding cards to a
panel:
Here, N is a string that identifies the name of the card whose panel is specified by
paneldemo.
e
invoking one of the following methods declared by CardLayout:
void first(Container d)
in
void last(Container d)
void next(Container d)
nl
void previous(Container d)
O
Here, d is a reference to the container that kept the cards, and cN is the name
of a card. Calling first( ) generate the first card in the d to be shown. To show the last
card, call last( ) method to be invoked. To show the next card, call next( ) method to be
invoked . To show the previous card, call previous( ) method to be invoked. Both next(
ty
) and previous( ) without human intervention cycle back to the top or bottom of the d ,
respectively. The show( ) method shows the card whose name is passed in cN.
si
GridBagLayout
Even though the previous layouts are completely acceptable for loads of
uses, some situations will require developer to take a bit more power over how the
r
components needs to be arranged. A superior way to do this is to use a grid bag layout,
ve
which is defined by the GridBagLayout class. What makes the grid bag useful is that
developer can define the relative placement of components by specifying their positions
inside cells within a grid. The main benefit to the grid bag is that each component can
have different size, and each row in the grid can have a different number of columns.
This is why the layout is called a grid bag. It’s a compilation of small grids joined
ni
together.
The location and size of each component in a grid bag are defined by a set
U
The common modus operandi for using a grid bag is to first generate a new
ity
GridBagLayout object and to make it the current layout manager. Then, set the
constraints that be relevant to each component that will be added to the grid bag.
Finally, add those components to the layout manager.
GridBagLayout()
Notes
e
Fleid Purpose
int anchor Specifies the location of a component within a cell. The default is
in
GridBagConstraints.CENTER.
int fill Specifies how a component is resized if the component is smaller
than its cell Valid values are GridBagConstraints NONE (the
default). GridBagConstraints.HORIZONTAL GridBagConstraints.
nl
VERTICAL Grid BagConstraints.BOTH.
int gridheight Specifies the height of component in terms of cells. The default is 1.
int gridwidth Specifies the width of component in terms of cells. The default is 1.
O
int gridx Specifies the X coordinate of the cell to which the component will be
added. The default value is Grid BagConstraints RELATIVE.
int gridy Specifies the Y coordinate of the cell to which the component will be
ty
added. The default value is Grid BagConstraints RELATIVE
Insets insets Specifies the Insets Default insets are all zero.
int ipadx Specifies extra horizontal space that surrounds a component within
a cell. The default is 0.
si
int ipady Specifies extra vertical space that surrounds a component within a
cell The default is 0.
double weightx
r
Specifies a weight value that determines the horizontal spacing
between cells and the edges of the container that holds them. The
ve
default value is 0.0. The greater the weight, the more space that
is allocated. If all values are 0.0, extra space is distributed evenly
between the edges of the window.
double weighty Specifies a weight value that determines the vertical spacing
ni
between cells and the edges of the container that holds them. The
default value is 0.0. The greater the weight, the more space that
is allocated. If all values are 0.0, extra space is distributed evenly
U
When a component is smaller than its cell, developer can use the anchor field to
m
identify where inside the cell component’s top-left corner will be situated. There are
three types of values that you can give to anchor. The first are absolute declared below
GridBagConstraints.CENTER GridBagConstraints.SOUTH
)A
GridBagConstraints.EAST GridBagConstraints.SOUTHEAST
GridBagConstraints.NORTH GridBagConstraints.SOUTHWEST
GridBagConstraints.NORTHEAST GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
(c
As their names suggest, these values helps the component to be placed at the
specific locations. The second type of values that can be given to anchor is relative, The
relative values are shown here:
Amity Directorate of Distance & Online Education
Object Oriented Programming Using Java 383
GridBagConstraints.FIRST_LINE_END GridBagConstraints.LINE_END
Notes
e
GridBagConstraints.FIRST_LINE_START GridBagConstraints.LINE_START
GridBagConstraints.LAST_LINE_END GridBagConstraints.PAGE_END
in
GridBagConstraints.LAST_LINE_START GridBagConstraints.PAGE_START
Their names describe the placement. The third type of values that can be given
to anchor were added by Java SE 6. They allow you to position components vertically
nl
relative to the baseline of the row. They are shown here:
GridBagConstraints.BASELINE GridBagConstraints.
O
BASELINE_LEADING
GridBagConstraints.BASELINE_TRAILING GridBagConstraints.ABOVE_
BASELINE
GridBagConstraints.ABOVE_BASELINE_ GridBagConstraints.ABOVE_
ty
LEADING BASELINE_TRAILING
GridBagConstraints.BELOW_BASELINE GridBagConstraints.BELOW_
BASELINE_LEADING
si
GridBagConstraints.BELOW_BASELINE_
TRAILING
r
5.1.4 A Code Snippet to Implement Applet with Layout Manager
ve
1. Creating a grid layout:
import java.awt.*;
import java.applet.*;
ni
/*
</applet>
*/
ity
int k = x * a + y;
if(k > 0)
(c
}
Notes
e
}
in
}
nl
Output
O
ty
si
2. Creating a program using GridBaglayout
import java.awt.*;
import java.awt.event.*;
r
ve
import java.applet.*;
/*
</applet>
*/
U
implements ItemListener {
setLayout(gB);
)A
e
// Use default row weight of 0 for first row.
in
gC.ipadx = 200; // pad by 200 units
nl
gC.anchor = GridBagConstraints.NORTHEAST;
gC.gridwidth = GridBagConstraints.RELATIVE;
O
gB.setConstraints(winXP, gC);
gC.gridwidth = GridBagConstraints.REMAINDER;
ty
gB.setConstraints(winVista, gC);
gC.weighty = 1.0;
si
gC.gridwidth = GridBagConstraints.RELATIVE;
gB.setConstraints(solaris, gC);
gC.gridwidth = GridBagConstraints.REMAINDER;
r
ve
gB.setConstraints(mac, gC);
add(winXP);
add(winVista);
U
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
m
mac.addItemListener(this);
}
)A
repaint();
(c
e
msg = “Current state: “;
g.drawString(msg, 6, 80);
in
msg = “ Windows XP: “ + winXP.getState();
g.drawString(msg, 6, 100);
nl
msg = “ Windows Vista: “ + winVista.getState();
g.drawString(msg, 6, 120);
O
msg = “ Solaris: “ + solaris.getState();
g.drawString(msg, 6, 140);
ty
msg = “ Mac: “ + mac.getState();
g.drawString(msg, 6, 160);
si
}
Output
r
ve
ni
U
ity
import java.awt.event.*;
m
import java.applet.*;
/*
)A
</applet>
*/
(c
e
Panel osCards;
CardLayoutcardLO;
in
Button Win, Other;
nl
Win = new Button(“Windows”);
O
add(Win);
add(Other);
ty
cardLO = new CardLayout();
si
win07 = new Checkbox(“Windows 07”, null, true);
winPan.add(win07);
U
winPan.add(win2010);
otherPan.add(linux);
otherPan.add(mac);
osCards.add(winPan, “Windows”);
osCards.add(otherPan, “Other”);
)A
add(osCards);
Win.addActionListener(this);
Other.addActionListener(this);
e
addMouseListener(this);
in
// Cycle through panels.
nl
cardLO.next(osCards);
O
// Provide empty implementations for the other MouseListener methods.
ty
}
si
public void mouseExited(MouseEvent me) {
}
r
public void mouseReleased(MouseEvent me) {
ve
}
if(ae.getSource() == Win) {
cardLO.show(osCards, “Windows”);
U
else {
cardLO.show(osCards, “Other”);
ity
}
m
Output
)A
(c
Notes
e
in
nl
Check your Understanding
1. Java AWT (Abstract Window Toolkit) is an API to expand ____________________ .
O
2. Java AWT components are ________________________ i.e. components are
showed according to the analysis of OS.
3. The AWT classes are included in the _________________________ .
ty
4. Since Frame is a subclass of Component, it contains all the characteristics declared
by ________________________ .
5. FlowLayout is the ______________________ layout.
si
Summary
●●
r
The AWT describes windows according to a class hierarchy that adds usability
and specificity with each segments. The two most widespread windows are those
ve
which are carryout from Panel, which is utilized by applets, and those which were
taken out from Frame, which construct a standard application window.
●● Today, most Java language programs utilize user interfaces based on Swing.
Because Swing provides better-off implementations than does the AWT of some
ni
general GUI controls, such as buttons, lists, and check boxes, it is easy to jump to
the end that the AWT is no longer significant, that it has been outdated by Swing.
U
Activity
1. Create a code to using grid layout replicate below image
m
)A
Glossary
Notes
e
●● AWT: Abstract Window Toolkit
●● GUI: Graphical User Interface
in
●● OS: Operating System
●● Component: In starting of the Abstract Window Toolkit hierarchy is the Component
nl
class. Component is a conceptual class that contains all of the characteristics of a
visual component.
●● Container: The Container class is a child class for Component. It has multiple
O
methods that permits other Component objects to be encapsulate in it.
●● Panel: The Panel class is an actual subclass of Container. It doesn’t put in any
fresh methods; it simply execute Container.
ty
●● Window: The Window class constructs a top-level window. A top-level window is
not included within any other object; it sits in a straight line on the monitor.
●● BorderLayout: The BorderLayout class executes a common layout style for top-
si
level windows.
●● FlowLayout: FlowLayout is the default layout. FlowLayout executes an easy layout
style, which is like to how words flow in a text editor.
●●
r
GridLayout: GridLayout puts out components in a 2-D grid.
ve
Further Readings:
1. Java AWT reference, John Zukowski
ni
2. Learn Java GUI Applications 11th Edition: A JFC Swing Tutorial, Philip Conrod,
Lou Tylee
3. Graphic Java 1.2: Mastering the JFC, David M. Geary Java Applet Powerpack,
U
2. platform-dependent
3. java.awt package
)A
4. Component
5. Default
(c