Ebook Programming in Java 2nd
Ebook Programming in Java 2nd
Java
Second Edition
SACHIN MALHOTRA
Associate Professor
IMS, Ghaziabad
SAURABH CHOUDHARY
Formerly, Head
IT Department
IMS, Ghaziabad
1
3
Oxford University Press is a department of the University of Oxford.
It furthers the University’s objective of excellence in research, scholarship,
and education by publishing worldwide. Oxford is a registered trade mark of
Oxford University Press in the UK and in certain other countries.
Published in India by
Oxford University Press
YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India
ISBN-13: 978-0-19-809485-2
ISBN-10: 0-19-809485-X
Sachin Malhotra is currently Associate Professor in the IT department of IMS Ghaziabad. He has more
than a decade long experience in mentoring students on developing Java applications as well as training
practising professionals in the field of Java. He has also designed and conducted various corporate
trainings in Java and networking.
Saurabh Choudhary is currently a practising IT consultant and corporate trainer. He has more than 12
years of experience in industry, academia, and consultancy. He has worked on positions of eminence
at IMS Ghaziabad as Head of IT department and Dean Academics (University Campus). His areas of
expertise include Java, Database Management System, and Information Systems.
Testimonials
From pervasive computing to communications industry, medical science to aerospace, Java is
gaining a foothold in every domain. Programming in Java has been written to arouse the interest
even in a novice computer programmer to an expert, craving to sharpen his programming skills.
Pankaj Verma | Senior Software Engineer | OSI Inc.
It is definitely the best textbook on Java that I have run into. I highly recommend it.
Sachin Dhama | Team Lead | Accenture
Java is a very powerful language for developing enterprise applications. I am hopeful that this
book will provide a basic building platform for Java programmers to enhance their knowledge.
Awadhesh Kumar Katiyar | Technical Lead | HCL Technologies Ltd.
Java enables users to develop applications on the Internet for servers, desktops computers, and small
handheld devices. The future of computing is being influenced by the Internet, and Java promises to
play a big part in it. This book is perfect for those who are seeking a clear understanding of Java. It
should allow the readers to create codes that are a lot clearer and are far more effective than before.
Saurabh Moondhra | Sr. Technical Consultant | SGT Inc
This is the most interesting Java programming book for beginners; at the same time, it is equally
good for intermediate readers as well. This should be your first Java book if you are learning
from scratch.
Pankaj Jain | Senior Manager | Bank of America
When you go through this book, you will gain confidence after completing each chapter. The
authors have written it in such a simple way covering each and every aspect of Java that anyone
can learn how to develop effective codes.
Rajeev Varshney | Lead Consultant | HCL NZ Ltd.
Preface to the First Edition
Java was primarily designed as a platform-independent language for usage in small consumer
electronic devices. It was derived from C++ but with a lot of difference. Java’s platform
independence originally addressed the problem that applications for embedded devices must
run on a wide variety of hardware. But since the Internet was emerging at the same time, Java
soon got adopted as an Internet language because of its portable nature. Major Internet browsers
such as Netscape Navigator and Microsoft Internet Explorer became Java-compatible, as it
effectively addressed the concerns for security by providing a firewall between web applications
and the computer. Eventually it became a standard programming language and is now being
used for creating a variety of applications including standalone applications, web applications,
enterprise-wide applications, and mobile games.
It can therefore be inferred that since its inception, Java has emerged as the most important
programming language. As the domain of Java is quite vast and a bit more complex than other
programming languages such as C, C++, and Visual Basic, it is observed that students and novice
programmers strive hard to comprehend its core concepts. Hence, a need for a book in this area,
which is both concise and simple, is a necessity.
About the Book
The book encapsulates the concepts of the latest version of Java, i.e. Java 6, encompassing a
comprehensive coverage of curriculum and industry expectations. It is useful for the students of
undergraduate and postgraduate courses of computer science and engineering and information
technology disciplines as well as for the instructors at various levels.
The book provides a thorough understanding of the basic concepts of object-oriented
programming principles and gradually moves on to the advanced concepts in Java. It includes
numerous examples, line-by-line description of examples, figures, explanation of concepts, and
key notes. Review questions and programming exercises are included as chapter-end exercises
to assess the learning outcomes. Every topic in the book is supported by examples followed
by an output and explanation. It also offers an appendix on general interview questions which
provides students an insight into the current requirements of the industry and allows them to
prepare accordingly.
The main features of this book include the following:
an exhaustive coverage of Java features such as operators, classes, objects, inheritance,
logging API, console class, StringBuilder class, NetworkInterface class, and assertions
latest features combined with core concepts such as multithreading, applets, AWT, and
swings
an introduction to the advanced concepts in Java such as servlets, RMI, and JDBC
Preface to theLab
Appendix A: Lab Manual—Java First Edition XIxi
Exercises
ACKNOWLEDGEMENTS
Several people have been instrumental throughout this tiring yet wonderful journey. First of all,
we would like to express our sincere gratitude to our families without whose support, patience,
and cooperation, this would not have been possible and we would not have been what we are
today. We are very thankful to Dr R. K. Bharadwaj, Head of our institution, for his inspirational
thoughts which inculcated urgency for writing this book. We are also thankful to our colleagues
for their endless support and suggestions during the entire process of writing this book.
Sachin Malhotra
Saurabh Choudhary
Preface to the Second Edition
Java is an easy-to-learn, versatile, robust, portable, and secure language with rich user interfaces.
It has set up new benchmarks in the software development world ranging from desktop to web-
based enterprise applications to mobile and embedded applications. Since its inception in 1995,
it has come a long way by continuously evolving itself and in the process, changing the style of
programming the world over. Java is not only found in laptops or data centres, it is also widely
used in cell phones, SIM cards, smart cards, printers, routers and switches, set-top boxes, ATMs,
and navigation systems, to name a few. According to Oracle, a staggering 1.1 billion desktops
and 3 billion cell phones are based on Java.
This second edition of Programming in Java confirms to Java Standard Edition 7, the latest
release since Oracle took over Sun Microsystems. It is significant in the sense that the last update
was six years back and this major release comes bundled with plenty of enhancements which were
overdue. To list a few noticeable enhancements, Java 7 includes support for strings in switch and
try-with-resources statements, improved multi-catch, binary numeric literals, numeric literals
with underscores, new APIs in NIO such as path and files, automatic resource management, and
much more. All the new topics are appropriately explained with suitable examples.
New to the Second Edition
This revised edition has been updated thoroughly with greater topical coverage as well as more
programming examples in every chapter, in addition to the confirmation to Java 7. Practically
every chapter, with the exception of Chapter 11, has been revisited to refine the text as much as
possible. The most noticeable changes are as follows:
New practical programming examples to show how Java is used in practice.
Enhanced coverage of servlets and JDBC along with an introduction to JSP, Java beans,
Appendix B contains more interview questions to help students prepare for their interviews.
The second edition is supplemented with a rich online resource centre that contains chapter-
wise PPTs for teachers and additional practical programming examples for students.
Key Features
The most prominent feature of this book has been the line-by-line explanation section under
each program. They facilitate in-depth understanding of the whole program. We have retained
this feature in the second edition as it has been well appreciated by the users. Other noticeable
features include the following:
Preface to the Second Edition vii
forms the core of the java.util package. This concept along with its application has been covered
in detail.
Chapter 11 explains how network programming can be done in Java. In-depth coverage of
sockets is extended in this chapter. Client and server concept is illustrated by the programs
created. TCP and UDP clients and server and their interactions are demonstrated. The concept
of multithreading is merged with socket and illustrated to create server programs. Some main
classes such as URL, URL connection, and network interface (new feature) are also discussed.
Chapter 12 focuses on applets, its lifecycle, methods, etc. and how they are different from
applications. Besides providing an in-depth coverage of java.applet package, some of the
classes of java.awt package are also discussed as they are very useful in creating applets such
as Graphics class, Font class, Color class, and FontMetric class. All these classes are discussed
and supported by an example for each of them.
Chapter 13 talks about event handling in Java. Basically for creating effective GUI applications,
we need to handle events and this forms the basis of this chapter. The event handling model is
not only discussed but applied throughout the chapter. All the approaches to event handling have
been discussed such as Listener interfaces, Adapter classes, inner classes, and anonymous inner
classes.
Chapter 14 focuses on GUI creation through java.awt package. It has an in-depth coverage
of containers and components. Containers like Frame, Window, etc. and components like Label,
Button, TextField, Choice, Checkbox, List, etc. are discussed in detail. How the components can
be arranged in a container is also discussed, e.g. BorderLayout, GridBagLayout, and GridLayout.
Chapter 15 shows how to create more advanced and lightweight GUI applications in Java.
More advanced layouts like SpringLayout have been discussed. Lightweight components like
JButton, JLabel, JCheckBox, JToggleButton, JList, JScrollPane, JTabbedPane, etc. have been
discussed. How to create Dialogs is also discussed. The pluggable look and feel of Java is
explained in detail.
Chapter 16 focuses on advanced Java concepts such as servlets, JDBC, and RMI. An
introduction to the advanced technologies has been discussed. This chapter is equipped with
numerous figures showing how to install the necessary softwares required for executing an
advanced Java program. The chapter also provides a step-by-step and simplified approach on
how to learn advanced concepts.
Appendix A on practical lab problems will facilitate better understanding of the concepts
explained in the book. Appendix B includes a list of interview questions along with their answers
that provides an overview of the industry scenario and their requirements.
ACKNOWLEDGEMENTS
Several people have been instrumental throughout this tiring yet wonderful journey. First of all, we
would like to express our sincere gratitude to our families without whose support, patience, and
cooperation, this would not have been possible and we would not have been what we are today.
We are also thankful to our colleagues and friends for their endless support and suggestions
during the entire process of writing this book. Lastly, we would also like to thank all our readers
/students who have supported us, encouraged us, and provided feedback to us regularly which
has helped us in shaping this edition.
Sachin Malhotra
Saurabh Choudhary
Brief Contents
Preface to the Second Edition vi
Preface to the First Edition x
Detailed Contents xiii
1. Introduction to OOP 1
2. Getting Started With Java 12
3. Java Programming Constructs 42
4. Classes and Objects 74
5. Inheritance 132
6. Interfaces, Packages, and Enumeration 156
7. Exception, Assertions, and Logging 199
8. Multithreading in Java 224
9. Input/Output, Serialization and Cloning 256
10. Generics, java.util and other API 296
11. Network Programming 336
12. Applets 354
13. Event Handling in Java 394
14. Abstract Window Toolkit 429
15. Swing 495
16. Introduction to Advanced Java 553
Appendix A: Lab Manual 628
Appendix B: Interview Questions 650
Index 657
Detailed Contents
Preface to the Second Edition vi
Preface to the First Edition x
comprehend the problems in procedural programming and how OOP overcomes them
1.1 INTRODUCTION
Object-oriented programming (OOP) is one of the most interesting and useful innovations in
software development. OOP has strong historical roots in programming paradigms and practices.
It addresses the problems commonly known as the software crisis. Software have become
inherently complex which has led to many problems within the development of large software
projects. Many software have failed in the past. The term ‘software crisis’ describes software
failure in terms of
Exceeding software budget
Software not meeting clients’ requirements
Bugs in the software
OOP is a programming paradigm which deals with the concepts of object to build programs
and software applications. It is modeled around the real world. The world we live in is full of
objects. Every object has a well-defined identity, attributes, and behavior. Objects exhibit the
same behavior in programming. The features of object-oriented programming also map closely
to the real-world features like inheritance, abstraction, encapsulation, and polymorphism. We
will discuss them later in the chapter.
2 Programming in Java
Note If we try to represent the CPU of a computer in OOP terminology, then CPU is the object.
The CPU is responsible for fetching the instructions and executing them. So fetching and
executing are two possible functions (methods or behavior) of CPU. The place (attributes)
where CPU stores the retrieved instructions, values and result of the execution (registers) will
then be the attributes of the CPU.
1.3.3 Abstraction
Can you classify the following items?
Elephant CD player
Television Chair
Table Tiger
How many classes do you identify here? The obvious answer anybody would give is three, i.e.,
Animal, Furniture, and Electronic items. But how do you come to this conclusion? Well, we
grouped similar items like Elephant and Tiger and focused on the generic characteristics rather
than specific characteristics. This is called abstraction. Everything in this world can be classified
as living or non-living and that would be the highest level of abstraction.
Another well-known analogy for abstraction is a car. We drive cars without knowing the
internal details about how the engine works and how the car stops on applying brakes. We are
happy with the abstraction provided to us, e.g., brakes, steering, etc. and we interact with them.
In real life, human beings manage complexity by abstracting details away. In programming,
we manage complexity by concentrating only on the essential characteristics and suppressing
implementation details.
4 Programming in Java
1.3.4 Inheritance
Inheritance is the way to adopt the characteristics of one class into another class. Here we have
two types of classes: base class and subclass. There exists a parent–child relationship among
the classes. When a class inherits another class, it has all the properties of the base class and it
adds some new properties of its own. We can categorize vehicles into car, bus, scooter, ships,
planes, etc. The class of animals can be divided into mammals, amphibians, birds, and so on.
The principle of dividing a class into subclass is that each subclass shares common
characteristics with the class from where they are inherited or derived. Cars, scooters, planes,
and ships all have an engine and a speedometer. These are the characteristics of vehicles. Each
subclass has its own characteristic feature, e.g., motorcycles have disk braking system, while
planes have hydraulic braking system. A car can run only on the surface, while a plane can fly
in air and a ship sails over water (see Fig. 1.1).
Vehicle
1.3.6 Polymorphism
Polymorphism simply means many forms. It can be defined as the same thing being used in
different forms. For example, there are certain bacteria that exhibit in more than one morphological
form. In programming, polymorphism is of two types: compile-time and runtime polymorphism.
Runtime polymorphism, also known as dynamic binding or late binding, is used to determine
which method to invoke at runtime. The binding of method call to its method is done at runtime
and hence the term late binding is used. In case of compile-time polymorphism, the compiler
determines which method (from all the overloaded methods) will be executed. The binding of
method call to the method is done at compile time. So the decision is made early and hence
the term early binding. Compile-time polymorphism in Java is implemented by overloading
and runtime polymorphism by overriding. In overloading, a method has the same name with
different signatures. (A signature is the list of formal argument that is passed to the method.)
In overriding, a method is defined in subclass with the same name and same signature as that
of parent class. This distinction between compile-time and runtime polymorphism is of method
invocation. Compile-time polymorphism is also implemented by operator overloading which
is a feature present in C++ but not in Java. Operator overloading allows the user to define new
meanings for that operator so that it can be used in different ways. The operator (+) in Java is
however an exception as it can be used for addition of two integers as well as concatenation of
two strings or an integer with a string. This operator is overloaded by the language itself and
the Java programmer cannot overload any operator.
Employee Class
name
address
designation Attributes
salary
addEmployee
deleteEmployee Behavior
searchEmployee
:Employee Object
name=peter
address=NY
designation=manager Attributes
salary=10000
addEmployee
deleteEmployee
searchEmployee
An instance of a class can be related to any number of instances of other class known as
multiplicity of the relation. One-to-one, one-to-many, and many-to-many are different types
of multiplicities that exist among objects. The multiplicities along with their examples and
respective notations are shown below. Figure 1.5(a) illustrates the generic notation for representing
multiplicity in object-oriented analysis and design. One-to-one mapping is shown as a straight
line between the two classes. Figure 1.5(b) shows the UML notation for demonstrating the one-
to-one mapping. The 1..1 multiplicity depicted on the straight line (both ends) indicates a single
instance of a class is associated with single instance of other class. Figure 1.5 shows that each
country has a president and a president is associated with a country.
(a) (b)
A country has many states and many states belong to a country. So there exists a one-to-many
relationship between the two. This relationship is shown in Fig. 1.6. Part (a) of this figure shows
the generic notation where a solid dot is indicated on the many side and both classes are joined
by a straight line. Figure 1.6(b) shows the UML notation where 1..* indicates the one to many
relationship between country and states. On the country end, a 1..1 multiplicity is placed to
indicate one country and on states end, a 1..* is placed to indicate many states.
(a) (b)
Let us take another example to explain many-to-many relationship. A teacher teaches many
students and a student can be taught by many teachers. There exists a many-to-many relationship
between them. Many-to-many relationship (Generic notation in OOAD) are represented by
placing solid dots on both ends joined by a straight line as shown in Fig. 1.7(a). The respective
notation in UML is shown in Fig. 1.7(b) where 1..* on both ends is used to signify many-to-
many relationship.
(a) (b)
Shape
Triangle Square
Shape
area( )
Another kind of relationship that exists among objects is the part-of-relationship. When a
particular object is a part of another object then we say that it is aggregation. For example, car is
Introduction to OOP 9
an aggregation of many objects: engine, door, etc. and engine in turn is an aggregation of many
objects, e.g., cylinder, piston, valves, etc. as shown in Fig. 1.10(a). A special kind of aggregation
is composition where one object owns other objects. If the owner object does not exist, the
owned objects also ceases to exist. For example, the human body is a very good example of
composition. It is a composition of different organs. The hands, feet, and internal organs such
as the lung and intestine are also parts of the body owned by the body.
Car
Human body
Engine Door
(a) (b)
a Date object would be created and used. At a later point of time, if a change is required, for
example, the year of Date class needs to be changed to four digits, then this change would be
incorporated in the class only and this change would automatically be reflected in all the objects
of the Date class whenever they are created and used. So, the change would have to be done at
one place only, i.e., the class and wherever the objects of the class are being used, the changes
would be reflected automatically. There is no need to analyze the whole code and change it.
In OOP, we access data with the help of objects, so it is very easy to overcome a problem
without modifying the whole system. Likewise, OOP is used in various fields, such as
Real-time systems Neural networks
Expert systems
SUMMARY
Object-oriented languages have become an ubiquitous large projects, a technique known as OOAD is used.
standard for programming. They have been derived Object-oriented analysis and design deals with how a
from the real world. OOP revolves around objects and system is modeled. OOA deals with what the system
classes. A class is defined as a group of objects with should do and OOD deals with how the system
similar attributes and behavior. OOP is a programming achieves what has been specified by OOA.
paradigm which deals with the concepts of objects to OOAD is realized with the help of a language known
develop software applications. Certain principles have as UML. UML stands for unified modeling language;
been laid down by OOP which are followed by every it is a standard language used for visualizing the
OOP language. These principles are: inheritance, software. An abstract model is created for the entire
abstraction, encapsulation, and polymorphism. software using graphical notations provided by UML.
We have presented a detailed comparison of
procedural and object-oriented languages. For building
EXERCISES
Objective Questions
1. In an object model, which one of the following is (c) Polymorphism (d) None of the above
true? 4. Which one of the following terms must relate to
(a) Abstraction, encapsulation, and multitasking polymorphism?
are the major principles (a) Static allocation (b) Static typing
(b) Hierarchy, concurrency, and typing are the
(c) Dynamic binding (d) Dynamic allocation
major principles
5. Providing access to an object only through its
(c) Abstraction, encapsulation, and polymor-
phism are the major principles member functions, while keeping the details
(d) Typing is the major principle private is called
(a) Information hiding (b) Encapsulation
2. Which one of the following is not an object-
(c) Modularity (d) Inheritance
oriented language?
(a) Simula (b) Java 6. The concept of derived classes is involved in
(c) C++ (d) C (a) Inheritance
3. The ability to hide many different implementations (b) Encapsulation
behind an interface is. (c) Data hiding
(a) Abstraction (b) Inheritance (d) Abstract data types
Introduction to OOP 11
Review Questions
1. Explain the importance of object-oriented pro- 4. Write short notes on: (a) inheritance, (b) poly-
gramming languages. morphism, (c) abstraction, (d) encapsulation.
2. Explain the difference between class and object. 5. Differentiate between runtime and compite-time
3. Differentiate between procedural languages and polymorphism.
OOP languages.
Programming Exercises
1. Identify the relevant classes along with their A hospital wants to keep track of scheduled
attributes for the following: A departmental store appointments of a patient with his doctor. When
needs to maintain an inventory of cosmetic items a patient is given an appointment, he should be
which might be found there. You should include given a confirmation that states the time and date
female as well as male cosmetic items. Keep of appointment along with the doctor’s name.
information on all items such as item name, Meanwhile the doctor should also be informed
category, manufacturer, cost, date purchased, about the patient details. Each doctor has one
and serial number. weekday as off-day and no patients should be
2. Identify the relevant classes along with their assigned to a doctor on that day.
attributes from the following problem specification:
2.1 INTRODUCTION
Java is a popular and powerful language. Although it is a very simple language, there are a
number of subtleties that can trip up less-experienced programmers. Java is an object-oriented
programming language with a built-in application programming interface (API) that can handle
graphical user interfaces (GUI) used to create applications or applets. Java provides a rich set
of APIs apart from being platform-independent.
Much of the syntax in Java is similar to C and C++. One of the major differences between
Java and other languages is that it does not have pointers. However, the biggest difference is that
you are forced to write object-oriented code in Java. Procedural code is embedded in objects.
In Java, we distinguish between applications and applets, applications being programs that
perform functions similar to those written in other programming languages and applets are
programs that are meant to be embedded in a web page and downloaded over the Internet.
When a program is compiled, a byte code is generated which can be executed on any platform,
provided the runtime environment exists on the destination platform.
This chapter guides the readers to a step-by-step introduction to Java programming. An
important thrust of this chapter is to cover the features of Java from an object-oriented perspective.
It also gives an insight about the installation of Java runtime environment and the various
integrated development environments (IDEs) of Java.
This chapter also focusses on the different versions of Java (including the latest Java 7) and
the Core API’s (Java 7 is also known as Java 1.7).
Getting Started with Java 13
Client
Browser Internet
(running Web server
Java applet)
Java is designed to be architecturally neutral so that it can run on multiple platforms. The
same runtime code can run on any platform that supports Java. To achieve its cross-architecture
capabilities, the Java compiler generates architecturally neutral bytecode instructions. These
instructions are designed to be both easily interpreted on any machine and easily translated into
native machine code on-the-fly, as shown in Fig. 2.3. Java Runtime Environment (JRE) includes
JVM, class libraries, and other supporting files.
JRE = JVM + Core Java API libraries
JDK = JRE + development tools like compilers
Tools such as javac (compiler), java (interpreter), and others are provided in a bundle, popularly
known as Java Development Kit (JDK). JDK comes in many versions (enhanced in each version)
and is different for different platforms such as Windows and Linux. A runtime bundle is also
provided as a part of JDK (popularly known as Java Runtime Environment).
Operating Systems
(Window, Unix, etc)
Hardware
(Intel, Motorola, Alpha, etc.)
Compile-Time Runtime
Bytecode
Bytecode
moves through
Java compiler verifier
network or
file system
Machine code
Interpreter
generator
Java
bytecode
Operating system
Hardware
But there remains the drawback of an extra compilation step after every correction during
debugging. Also, the interpretation of bytecode is still slower in many cases than a program in
local machine code. Advanced JVM can ameliorate this, and in many cases, reach speeds similar
to programs compiled to local machine code.
2.6.4 Java is Robust
The type checking of Java is at least as strong as that of C++. The compile-time and runtime
checks in Java catch many errors and make them crash-proof. The program cannot crash the
system. To sum up, Java is one of the most robust languages to have ever evolved. Automatic
garbage collection of allocated memory is the biggest contributor here.
2.6.5 JAVA Language Security Features
Java has several language features that protect the integrity of the security system and prevent
several common attacks.
Security Through Definition Java is strict in its definition of the language:
All primitive data types in the language have a specific size.
Security Through Strict Compile-Time Checking The Java compiler performs extensive,
stringent compile-time checking so that as many errors as possible can be detected by the
compiler. The Java language is strongly typed, that is:
Objects cannot be cast to a subclass without an explicit runtime check.
References to methods and variables of a class are checked to ensure that the objects
Strict compilation checks make Java programs more robust and avoid runtime errors. The
bytecode verifier runs the bytecode generated by the compiler when an applet is loaded and
makes security checks. The compiler also ensures that a program does not access any uninitialized
variables.
Java Security Model
Java’s security model is focused on protecting users from hostile programs downloaded from
untrusted sources across a network. Programs downloaded over the Internet are executed in a
sandbox. It cannot take any action outside the boundaries specified by the sandbox.
The sandbox for untrusted Java applets, for example, prohibits many activities, including
Reading or writing to the local disk
Making a network connection to any host, except the host from which the applet came
By making it impossible for the downloaded code to perform certain actions, Java’s security
model protects the user from the threat of hostile codes.
Sandbox—Definition
Traditionally, you had to trust a software before you ran it. You achieved security by allowing
a software from trusted sources only, and by regularly scanning for viruses. Once a software
gets access to your system, it has full control and if it is malicious, it can damage your system
because there are no restrictions placed on the software by the computer. So, in the first place,
you prevent malicious code from ever gaining access to your system.
The sandbox security model makes it easier to work with the software that comes from untrusted
sources by restricting codes from untrusted sources from taking any actions that could possibly
harm your system. The advantage is—you don’t need to figure out what code is trusted and what
is not. In addition to that, you don’t need to scan for viruses as well. The sandbox is made up of
the following components operating together.
Class Loader It is the first link in the security chain. It fetches executable codes from the
network and enforces the namespace hierarchy.
Bytecode Verifier The verifier checks that the applet conforms to the Java language guarantees
and that there are no violations like stack overflows, namespace violations, illegal data type
casts, etc.
Security Manager It enforces the boundary of the sandbox. Whenever an applet performs an
action which is a potential violation, the security manager decides whether it is approved or not.
20 Programming in Java
No Pointers
Java uses references instead of pointers. A reference provides access to objects. The programmer
is relieved from the overhead of pointer manipulation.
No Global Variables
In Java, the global namespace is the class hierarchy and so, one cannot create a variable outside
the class. It is extremely difficult to ensure that a global variable is manipulated in a consistent
manner. Java allows a modified type of the global variable called static variable.
3. Compiling and Running the Source Java programs are compiled using DOS. For
opening OS, type cmd at the run prompt and move to the folder that contains the saved
Example.java file. Now compile the program using javac, specifying the name of the
source file on the command line as shown below. (Assuming the file was saved in a
folder ‘javaeg’ in the C drive.)
C:\>cd javaeg // change to directory javaeg using cd command
C:\javaeg\>javac Example.java
The javac compiler creates a file called Example.class (in the same directory). This class
contains the bytecode version of the program. This bytecode will be executed by the Java
interpreter using java followed by the class name as shown below.
C:\javaeg\>java Example
Output
This is a simple Java program
Note You can also provide a different name for naming a source file. For example, the above
example can be saved as First.java. But in that case, when you compile the file, the .class
that will be generated will have the name Example.class. So for executing the program, you
have to mention java Example on the command line. This may lead to confusion, so it is
advised that the name of the Java file should match with the name of the class defined in the
file (case-wise also). Also note that in case the source file contains more than one classes
defined within itself, the java file name should match exactly with the class name that contains
the main method.
2.7.3 Explanation
L1 The program begins with the comment:
/* Call this file “Example.java”.*/
The comments are ignored by the compiler. Comments are a good way to induce documentation
in programming.
L2 The next line of code in the program is
class Example {
Getting Started with Java 23
This line uses the keyword class to declare that a new class is being defined followed by the
class name, i.e., Example. The entire class definition, including all its members, will be between
the opening curly brace ({ ) and the closing curly brace ( }).
L3 Another type of comment is used in this line.
// your program starts execution with a call to main()
This type of comment is called a single-line comment, and it begins with a double slash //.
L4 This line shows the main method for the class.
public static void main (String args []) {
This is the line from where the program will start its execution. All applications in Java start
execution from main(). Every complete Java Application must contain a root class where the
execution can begin. A root class must contain a main method defined with the header, as shown
in this line. Let us take a brief look at the attributes of main().
public It is an access specifier used to specify that the code can be called from anywhere.main()is
declared public because it is called by codes outside the class it is a part of. It is called by the JVM.
static It is declared static because it allows main()to be called without having to instantiate
the class. JVM need not create an instance of the class (i.e. object of the class) for calling the
main()method.
void It does not return a value. The keyword void simply tells the compiler that main()does not
return anything back to the caller, i.e., JVM.
String args[]It holds optional command line arguments passed to the class through the java
command line. The curly bracket at the end marks the beginning of the main method and it
ends in L6.
Note The Java compiler will compile classes that do not contain a main () method, but the
Java interpreter has no way to run these classes.
L5 It shows a print statement. If you want to display anything on the standard output, this
statement is used.
System.out.println ("This is a simple Java program");
This line prints the string "This is a simple Java Program" on the standard output. System is
a predefined class. The string (mentioned in double quotes) passed to the println method is
displayed as it is on the standard output. All statements in Java are terminated by a semicolon (;).
Lines other than println()don’t end with a semicolon because they are technically not statements.
L6 The closing curly bracket marks the closing of the main method.
L7 The closing curly bracket marks the closing of the class.
Input/Output
A new class named Console has been added to the java.io package. It contains methods to
access character-based console. New methods have been added to File class.
26 Programming in Java
Extended Utility Class Libraries: Package java.util Supported among others, Enumeration
(an Iterator interface), Hashtable, Vector.
Default Access Specifier Added By default, all the variables, methods, and classes in Java
have default privileges that are different from private access specifier. Private is the default
access specifier in C++.
Note For the installation of JDK 1.7 on Solaris platform (both 32-bit and 64-bit), you can refer to the
installation documentation on Oracle official site:
http://docs.oracle.com/javase/7/docs/webnotes/install/solaris/solaris-jdk.html
Similarly, for installation of JDK 1.7 on Linux operating system (both 32 bit and 64 bit), visit:
http://docs.oracle.com/javase/7/docs/webnotes/install/linux/linux-jdk.html
For JDK installation on MAC OS visit:
http://docs.oracle.com/javase/7/docs/webnotes/install/mac/mac-jdk.html
The JDK for any OS can be downloaded from:
www.oracle.com/technetwork/java/javase/downloads/jdk7u9-downloads-1859576.html.
Refer to www.oracle.com/technetwork/java/javase/downloads/index.html for latest Java SE
releases.
30 Programming in Java
In this book, we intend to provide the details of installation of JDK 1.7 on Windows operating
system only.
JDK has two versions numbers—an external version number 7 and an internal version
number1.7.0_09, i.e., version 7 update 9.
The installation and configuration process can be broken down into the following steps:
1. Run the JDK installer.
2. Update the Path and Classpath variables.
3. Test the installation.
Step 1: Run the JDK Installer
If you have downloaded the JDK software file (JDK installer) instead of running the installer
from the Java website, you should check to see that the complete file is downloaded:
jdk-7u9-windows-i586.exe
Note The JDK documentation can be downloaded from the following URL: www.oracle.com/
technetwork/java/javase/documentation/java-se-7-doc-download-435117.html.
Double-click on the icon of the JDK Installer.exe to run the installer and then follow the
instructions. Figures 2.8(a)–(h) show some of the snapshots of the installation process. The first
Welcome screen is displayed as soon as you double click on the installer.
Fig. 2.8(a)
The welcome screen also tells you that Java FX SDK is now a part of Java 7. Click on Next>,
the installer prompts you to select what all you want to install and where to install them in your
system.
Getting Started with Java 31
Fig. 2.8(b)
By default, the JDK will be installed at the path mentioned in Install to. You can change
the default path by clicking the Change… button. As soon as you click on the Next> button, the
installation starts.
Fig. 2.8(c)
32 Programming in Java
Fig. 2.8(d)
Figure 2.8(e) prompts you to make a selection for installing JRE. As soon as you click on Next>,
the installation of JRE starts.
Fig. 2.8(e)
Getting Started with Java 33
The following snapshot shows you that the JRE is getting registered.
Fig. 2.8(f)
Finally, Java is installed successfully as shown in the snapshot below.
Fig. 2.8(g)
Once you are finished with installation of Java, you get a ‘Thank You’ message (Fig. 2.8(h))
from Oracle Corporation and asking you to register so that you can get alerts, notifications,
special offers, and access to future releases and documentation.
34 Programming in Java
Fig. 2.8(h)
jdk1.7.0
java.exe tools.jar
javac.exe dt.jar bin lib
javap.exe ...
javah.exe
javadoc.
exe java.exe client server ext security applet fonts
Plugin 2 dtPlugin
... java.dll
awt.dll jvm.dll jvm.dll localedata.jar
rt.jar
charsets.jar
Included in the directory structure is a file src.zip. Do not unzip the src.zip file as it contains
all the core class binaries, and is used by JDK in this form.
Getting Started with Java 35
include\ The include directory contains a set of C and C++ header files for interacting
with C and C++.
lib\ This directory contains non-core classes like dt.jar and tools.jar used by tools
and utilities in JDK.
bin\ The bin directory contains the binary executables for Java. For example, Java
Compiler (Java), Java Interpreter (Java) ,rmicompiler (rmic) etc.
jre\ It is the root directory for the Java runtime environment.
db\ Contains Java database.
Step 2: Update Path and Classpath Variables
It is not possible to run a Java program without modifying system environment variables (such
as Path or Classpath) or modifying the autoexec.bat.
Why to Set Path Variable? The PATH environment variable needs to be set if you want to run
the executables (javac.exe, java.exe, javadoc.exe, etc.) from any directory. If you want to find
out the current value of your PATH, then type the following at the DOS prompt:
C:\>path
Classpath—What it does? The Classpath tells the JVM and other Java applications where
to find the class libraries and user-defined classes. You need to set the classpath for locating
class libraries, user-defined classes, and packages.
Setting the Classpath
The same procedure (explained above) can be followed for setting the classpath environment
variable with the exception that now you will not look for the path variable but for the classpath
variable.
Step 3: Testing the Installation
Your computer system is now configured and ready to use the JDK. The Java tools do not have
a GUI, as they are all run from the DOS command line. For testing the installation, type the
following command at the command line:
C:\>javac and C:\>java
If the following screenshots are displayed on typing the command ‘java’ on the DOS prompt, it
means that Java is properly installed and the path is set (Figs 2.10(a) and (b)).
36 Programming in Java
Fig. 2.10(a)
Fig. 2.10(b)
Getting Started with Java 37
Deployment
Web Start Java Plug-in
Technologies
JavaFX
Integration Scripting
IDL JDBC JNDI RMI RMI-IIOP
Libraries
Lang
Lang & util Collections Concurrency JAR Logging Management
and util Utilities
Base Preferences Ref. Objects Regular
Reflection Expressions Versioning Zip Instrument
Libraries API
-Deployment Technologies
-Java API
JRE
-Java Virtual Machine
Basic Tools
extcheck
javac
javap
java
javah
javadoc jar
jdb
appletviewer
apt
appletviewer This small program provides a real Java environment for testing applets. It loads
the HTML file in which the applet has been embedded and displays the application in a browser-
like window.
jar It is used for creating and managing jar (similar to WinZip file) files.
jdb The Java debugger, jdb, enables you to debug your Java classes. Unfortunately, the Java
debugger is a throwback to the pre-GUI debugger dark ages of programming. The Java debugger
is a command-line debugger. You can use the jdb to set breakpoints, inspect objects and variables,
and monitor threads.
javah Because Java is a new language and must fit in a world dominated by C and C++, it
includes the capability to use native C code within a Java class. One of the steps in doing this
is by using the Java header file generator, javah.
javap One of the basic tenets of object-oriented programming is that programmers unfamiliar
with a class need only concern themselves with the public interface of that class. If you want to
use a class, you shouldn’t be concerned with how this class has been written.
Because you should be interested only in the public interface of a class, the JDK includes a
disassembler,javap, that can be used to display the public interface, both methods and variables,
of a class. Additionally, the Java disassembler includes options to display private members or to
display the actual bytecodes for the class’s methods. This last option can be particularly useful
if you want to achieve a greater understanding of the bytecodes used by the Java interpreter.
extcheck It is used for detecting Jar conflicts.
JCreator The light edition of this IDE for Java has support for project management, a syntax
highlighting editor, wizards, class viewer, package viewer, tabbed documents, JDK profiles
(which allows you to work with multiple JDK), a customizable user interface, etc. JCreator runs
on Windows 95, 98, NT, and 2000.
NetBeans It is a cross-platform open source IDE for Java. It comes with a code editor that
supports code completion, annotations, macros, auto-indentation, etc. It integrates with compilers,
debuggers, JVMs, and other tools.
SUMMARY
Java is a programming language invented by James as it uses bytecode—a special type of machine code.
Gosling and others in 1994. Java was originally named Java bytecode executes on a special type of micro-
Oak and was developed as a part of the Green Project processor. As there was no hardware implementation
at the Sun Company. Patrick Naughton, Mike Sheridan, of this microprocessor available when Java was first
and James Gosling were trying to figure out the next released, the complete processor architecture was
wave in computing and that wave came in 1995, when emulated by a software known as the virtual machine.
Java started to be visualized as a language for Internet Java is a robust language, as its two properties, type
applications. checking and interpretation makes Java programs
It is conceived that Java is a pure object-oriented crash-proof. Java has several other features that
language, meaning that the outermost level of data protect the integrity of the security system and
structure in Java is the object. Java is designed to prevent several common attacks. Java is inherently
be platform independent, so it can run on multiple multithreaded, i.e., multiple threads developed in this
platforms. The same runtime code can be downloaded language can be executed concurrently.
on any platform and be executed there, if that platform Other features of Java include automatic memory
supports the Java runtime environment. For this, management, dynamic binding, optimal performance,
Java incorporates elements of both interpretation and built-in networking capabilities, etc. The garbage col-
compilation. lector relieves the programmers from memory deal-
At the heart of Java Runtime Environment lies the location. Java uses references instead of pointers.
Java Virtual Machine or JVM. Most programming Every Java program consists of one or more classes.
languages compile source codes directly into machine A class is nothing but a template for creating objects.
codes, suitable for execution on a particular micropro- In Java, codes reside inside a class. The name of the
cessor architecture. But Java is somewhat different, class must match with the name of the file.
EXERCISES
Objective Questions
1. What was the name of first version of Java? (a) javap (b) java
(a) Oak (b) Mustang (c) javah (d) javac
(c) Tiger (d) Playground 4. What is the name of the tool that is used for
2. What was the name of the team that developed interpreting a Java program?
Java? (a) javap (b) java
(a) Green Team (b) Star Seven (c) javah (d) javac
(c) Sun (d) Java team 5. What process automatically removes objects that
3. What is the name of the tool that is used for are not being referenced?
compiling a Java program? (a) Multithreading (b) Object Reclamation
Getting Started with Java 41
(c) Garbage collection (d) Object collection (c) .class (d) .bytecode
6. What is the name of the tool that is used for 9. Which all are correct for main method?
running Applets? (a) public static void main(String args[])
(a) javap (b) javac (b) private static void main(String args[])
(c) java (d) appletviewer (c) static void main(String args[])
7. What is the extension of the source files in Java? (d) public static void main(String a[])
(a) .jav (b) .java 10. Which of the following are added in Java 7?
(c) .bytecode (d) .class (a) String in switch case
8. What is the extension of the bytecode files in (b) meta data
Java? (c) annotations
(a) .jav (b) .java (d) automatic resource management
Review Questions
1. Why is Java known as a platform-independent 6. Java was used in Internet applications. Cite
language? reasons.
2. Explain the security model of Java that makes it 7. Explain the importance of JVM in JRE.
more secured than other languages. 8. Explain the structure of a Java program.
3. Why is Java known to be multithreading? How 9. Explain the steps for executing a Java program.
does it help Java in its performance?
10. What is the importance of setting environment
4. C++ is an object-oriented language older than
variables such as Path and Classpath?
Java, then why did Java replace C++ in most of
the application development? 11. Discuss the tools available in JDK. How do they
help in application development?
5. Java had middle-tier capabilities. What does this
statement mean?
Programming Exercise
1. Write a program to print ‘Welcome’ followed by your name and ‘How are you?’
3.1 VARIABLES
Variable is a symbolic name refer to a memory location used to store values that can change
during the execution of a program. Java declares its variables in the following manner:
A variable declaration involves specifying the type (data type), name (identifier), and value
(literal) according to the type of the variable. Let us have a look at the three components in detail.
All variables in Java have to be declared before they can be used, that is why Java is termed as
a strongly typed language. There are eight primitive data types in Java, as follows:
byte
short
For whole number
int
long
float
For real numbers
double
char Characters
boolean Boolean
Java is portable across computer platforms. C and C++ leave the size of data types to the machine
and the compiler, but Java specifies everything.
Note All integer (byte, short, int, long) and floating-point types (float, double) are signed in Java.
byte It is a 1-byte (8-bit) signed 2’s complement integer. It ranges from –128 to 127
(inclusive). The byte data type can be used where the memory savings actually matter.
short It is a 2-byte (16-bit) signed 2’s complement integer. It ranges from –32,768 to 32,767
(inclusive). As with byte, you can use a short to save memory.
int It is a 4-byte (32-bit) signed 2’s complement integer. It ranges from –2,147,483,648
to 2,147,483,647 (inclusive). For integral values, this data type is the default choice.
long It is an 8-byte (64-bit) signed 2’s complement integer. It ranges from
–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive). This data
type should be used only when you need a range of values wider than int.
Floating point conforms to the IEEE 754-1985 binary floating point standard.
float It is a single-precision 32-bit floating point. It ranges from 1.401298464324817e–45f
to 3.402823476638528860e+38f.
double This data type is a double-precision 64-bit floating point. It ranges from
4.94065645841246544e–324 to 1.79769313486231570e (+) 308. For decimal
numbers, this data type is the default choice.
boolean It has only two possible values: true and false. The size of this data type is not
precisely defined.
char The unsigned char data type is a single 16-bit unicode character. It ranges from ‘\
u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).
Note Unlike C/C++, where handling of character sequences is tedious, Java provides a class
named “String” for handling character strings enclosed within double quotes. Although it is
not a primitive data type, Java string solves much of the complexity with ease.
44 Programming in Java
3.3 IDENTIFIER
Identifiers are names assigned to variables, constants, methods, classes, packages, and interfaces.
No limit has been specified for the length of a variable name. Identifiers can have letters, numbers,
underscores, and any currency symbol. However they may only begin with a letter, underscore,
or a dollar sign. Digits cannot be the first character in an identifier.
3.3.1 Rules for Naming
1. The first character of an identifier must be a letter, an underscore, or a dollar sign ($).
2. The subsequent characters can be a letter, an underscore, dollar sign, or a digit. Note
that white spaces are not allowed within identifiers.
3. Identifiers are case-sensitive. This means that Total_Price and total_price are different
identifiers.
Do not use Java’s reserved keywords. A few examples of legal and illegal identifiers
are shown below.
Class or Interface Identifiers These begin with a capital letter. The first alphabet of every
internal word is capitalized. All other letters are in lower case.
public class MyClass // class identifier: MyClass
interface Calculator; // interface identifier: Calculator
Variable or Method Identifiers These start with a lower-case letter. The first alphabet of every
internal word is capitalized. All other letters are in lower case.
int totalPay; // variable identifier: totalPay
MyClass.showResult();
// MyClass is the Class Name and showResult() is a method of MyClass.
Constant Identifiers These are specified in upper case. Underscores are used to separate
internal words.
final double TAX_RATE = 0.05; // constant identifier: TAX_RATE
3.3.3 Keywords
Keywords are predefined identifiers meant for a specific purpose and cannot be used for
identifying used defined classes, variables, methods, packages, and interfaces. All keywords
are in lower case. Table 3.1 lists the keywords in Java.
Table 3.1 Keywords in Java
abstract assert boolean break byte
case catch char class continue
default do double else enum
extends final finally float for
if implements import instanceof int
interface long native new package
private protected public return short
static strictfp super switch synchronized
this throw throws transient try
void volatile while const* goto*
*const and goto are reserved keywords.
3.4 LITERALS
A literal is a value that can be passed to a variable or constant in a program. Literals can be numeric
(for byte, short, int, long, float, double), boolean, character, string notations or null literals.
Numeric Literals can be represented in binary, decimal, octal, or hexadecimal notations. These
literals can be assigned to all numeric types in Java including char (based on their respective
range and size).
Binary literals are a combination of 0’s and 1’s. Binary literals can be assigned to variables
in Java 7. Binary literals must be prefixed with 0b or 0B (zerob or zeroB). For example,
46 Programming in Java
In case octal literals have to be specified, the value must be prefixed with a zero and only
digits from 0 to 7 are allowed.
For example,
int x = 011; //value in x is 9
char y=0150; // value in y will be h
float z=0234; // value in z will be 156.0
Hexadecimal literals are prefixed with 0x or 0X; the digits 0 through 9 and a through f (or A
through F) are only allowed. For example,
int y = 0x0001; //value in y is 1
char x=0x45; // value in x will be E
float y=0xA3; // value in y will be 163.0
All integer literals are of type int, by default. To define them as long, we can place a suffix
of L or l after the number for instance:
long l = 2345678998L;
All floating literals are of type double, by default. To define them as float literals, we need to
attach the suffix F or f. For double literals, D or d are suffixed at the end; however, it is optional.
For instance,
float f = 23.6F;
double d = 23.6;
Java 7 onwards the readability of literals can be enhanced by using underscore with numeric
literals. As the number of zeroes increase in a literal, counting the number of zeroes becomes
tedious. In such big literals, underscores can be used as shown below:
int numlit=100_000_000; // value in numlit will be 100000000
Underscores can be used not only with decimal literals but also with hexa, binary, and octal
literals as shown below:
int numlit=0x100_000; // value in numlit1 will be 1048576
int bin=0B1_000_000_000_000_001; // vale in bin will be 32769
float octlit=03_000; // value in octlit will be 1536.0
The following examples show some valid and invalid use of underscores.
int i =_23; // illegal, cannot start a literal with underscore
long f = 3_2_222_2_l; // invalid use of underscore between value and suffix
long f = 3_2_222_2l; // legal
float e = 4_.2_3f; // illegal use of underscore with a dot
Java Programming Constructs 47
For char literals, a single character is enclosed in single quotes. You can also use the prefix
\u followed by four hexadecimal digits representing the 16-bit unicode character:
char c = '\u004E'; char sample = 'A'; char example = 'a';
A single quote, a backslash or a unprintable character (such as a horizontal tab) can be specified
as a character literal with the help of an escape sequence. An escape sequence represents a
character by using a special syntax that begins with a single backslash character. Unicode is a
type of escape sequence (refer Table 3.2). Furthermore, the syntax of unicode escape sequence
consists of \uxxxx (where each x represents a hexadecimal digit).
Table 3.3 Special Escape Sequences
Table 3.2 Unicode Escape Sequences to \\ Backslash
Represent Printable and Unprintable Characters \" Double quote
'\u0041' Capital letter A \' Single quote
'\u0030' Digit 0 \b Backspace
'\u0022' Double quote “ \f Form feed
'\u003b' Punctuation ; \n New line
'\u0020' Space \r Carriage return
'\u0009' Horizontal Tab \t Horizontal tab
For instance, char c = '\t'; // creates a character that represents horizontal tab (Refer
Table 3.3).
Unicode characters can be assigned to strings in Java 7. Unicode 6, which has thousands
of characters, cannot be accommodated in a 16-bit char data type. Increasing the size of char
data type would lead to backward compatibility problems. To maintain compatibility with the
application and standards, the string (“U+hex”) is used to express unicode characters in Java.
A boolean literal is specified as either true or false. By default, it takes the value false (Refer
Table 3.4). The following code fragment demonstrates a boolean literal:
boolean firstRoll = true;
String literals consist of zero or more characters within double quotes. For instance,
String s = "This is a String Literal";
Null literals are assigned to object reference variables (see Chapter 4 for object references).
s = null;
Table 3.4 shows a summary of the data types along with their respective default values, size,
and range.
48 Programming in Java
3.5 OPERATORS
An operator performs an action on one or more operands. An operator that performs an action
on one operand is called a unary operator (+, –, ++, – –). An operator that performs an action
on two operands is called a binary operator (+, –, / , * , and more). An operator that performs an
action on three operands is called a ternary operator (? :). Java provides all the three operators.
Let us begin the discussion with binary operators.
3.5.1 Binary Operators
Java provides arithmetic, assignment, relational, shift, conditional, bitwise, and member access
operators.
Assignment Operators
It sets the value of a variable (or expression) to some new value. The simple ‘=’ operator sets
the left-hand operand to the value of the right-hand operand. The assignment operator has right
to left associativity (discussed in Section 3.7); so the statement a = b = 0; would assign 0 to
b then b to a. Java supports the following list of shortcut or compound assignment operators:
These operators allow you to combine two operations into one: one fixed as assignment plus
another one. These operators will be explained shortly according to their counterparts.
Arithmetic Operators
Arithmetic operators are used for adding (+), subtracting (–), multiplying (*), dividing (/), and
finding the remainder (%).
Java does not support operator overloading. There are certain languages like C++ that allow
programmers to change the meaning of operators enabling them to act in more than one way
depending upon the operands. But there are certain operators which are overloaded by Java itself
Java Programming Constructs 49
like + operator which behaves differently when applied to different operands. For example, if
+ operator is used and one of the operands is a string, then the other operand is converted to a
String automatically and concatenated. It is evident in the following examples in the System.
out.println statement when the String in the quotes is concatenated with the values of the
result or individual primitives. In addition to these operators, arithmetic compound assignment
operators are also provided by Java: +=, – =, /=, *=, %=. For example,
a += b; // evaluated as a = a + b;
a –= b; // evaluated as a = a – b;
a *= b; // evaluated as a = a * b;
a /= b; // evaluated as a = a / b;
a % = b; // evaluated as a = a % b
Let us take an example to demonstrate the use of these operators in Java. A close look at the
program will show us that the + operator can be used for two purposes: concatenation and
addition in the print statements.
//multiplying a with b
System.out.println("Multiplication "+ a +" * " + b +" = " + (a * b));
// Division
System.out.println("Division "+ a +" / " + b +" = " + (a / b));
// Remainder Operator
System.out.println("Remainder "+ a +" % " + b +" = " + (a % b));
Output
C:\Javaprg\>Java ArithmeticDemo
Sum 25 + 10 = 35
Subtraction 25 - 10 = 15
Multiplication 25 * 10 = 250
Division 25 / 10 = 2
Remainder 25 % 10 = 5
Added b to a and stored the result in a 35
50 Programming in Java
Figure 3.2 shows how the ‘+’ operator concatenates and adds the operands
System.out.println("Sum "+ a +" and " + b +" = " + (a + b));
Concatenation
Concatenation Adding
Concatenation
Concatenation
Concatenation
Relational Operators
Relational operators in Java return either true or false as a boolean type. Table 3.6 shows a list
of all the relational operators in Java.
Relational operators in C++ returns an integer where the integer value of zero may be interpreted
as false and any non-zero value may be interpreted as true.
Table 3.6 Relational Operators
equal to ==
Not equal to !=
less than <
greater than >
less than or equal to <=
greater than or equal to >=
Output
C:\Javaprg\>Java RelationalOperatorDemo
Equality Operator: a = = b : false
Not Equal To Operator: a != b : true
Less Than Operator: a == b : true
Greater Than Operator: a == b : false
Less than or equal to Operator: a == b : true
Greater than or equal to Operator: a == b : false
Output
Logical OR: true | false: true
Logical XOR: true ^ false: true
Logical AND: true & false: false
Logical NOT: !a : false
Conditional OR: true || false: true
Conditional AND: true && false: false
Shortcut OR: true | false = true
Bitwise Operators
Bitwise operators include and, or, xor, not, right shift, left shift, and unsigned right shift. In Java,
bitwise operators operate on int and long values. If any of the operand is shorter than an int, it
is automatically promoted to int before the operations are performed (see Section 3.8). Table
3.7 lists the bitwise operators and how they function.
Note It is important to understand how integers are represented in binary. For example, the decimal
number 4 is represented as 100 in binary and 5 is represented as 101. Negative integers are
always represented in 2’s complement form. For example, –4 is 1111 1111 1111 1111 1111
1111 1111 1100.
Bitwise shortcut operators are used in the same way as boolean operators. Bitwise shortcut
operators include the following:
AND: &=
OR: |=
XOR: ^=
Shift Operator: >>=,<<=,>>>=
Output
Bitwise AND: 2&3 = 2
Bitwise OR : 2|3 = 3
Bitwise XOR: 2^3 = 1
Bitwise NOT: ~2 = –3
Shift operators shift the bits depending upon the type of operator. The left shift operator shifts
the numbers of bits specified towards the left. Bits are discarded from the left and added from
the right with the value of bits being zero. The right shift operator shifts the numbers of bits
specified towards right. Bits are discarded from the right and added from the left side with the
value of bits being that of the sign bit. The unsigned right shift shifts the numbers of bits specified
towards right. Bits are discarded from the right and added from the left side with the value of bits
being zero. For example, let us assume x = 4 and this x is to be shifted by the shift distance of 1.
int y = x >> 1;
//y has the value 2, value is halved in each successive right shift
= 00000000 00000000 00000000 00000100 >> 1
= 00000000 00000000 00000000 00000010 (which is 2)
int y = x << 1;
// y has the value 8, value is doubled in each successive left shift
If we provide a negative number to be left or right shifted, then the negative numbers are
represented in 2’s compliment arithmetic and then shifted. If we provide an int negative shift
distance as shown in the following example, first the negative shift distance is ANDed with the
mask 11111 (i.e., 31) and the result is the new shift distance. If we provide a long negative shift
distance as shown in the following example, first the negative shift distance is ANDed with the
mask 111111 (i.e., 63), and the result is the new shift distance.
//negative numbers
54 Programming in Java
Output
Left shift: 5 << 1 = 10
Right shift: 5 >> 1 = 2
Unsigned Right Shift: 5 >>> 1 = 2
Right Shift: −5 >> 1 = −3
Unsigned Right Shift: −5 >>> 1 = 2147483645
Left shift: −5 << 1 = −10
Left shift: 5 << −31 = 10
Bitwise operators are particularly used where bit-level or low-level programming is required
such as writing device drivers, working with embedded systems, compression of data,
encryption and decryption of data, setting mask and flags, and creating networking protocols
for communication.
3.5.2 Unary Operators
Unary operators, as the name suggest, are applied to only one operand. They are as follows:
++, - -, !, and ~. The unary boolean logical not (!) and bitwise logical not (~) have already been
discussed.
Increment and Decrement Operators
Increment and decrement operators can be applied to all integers and floating-point types. They
can be used either in prefix (– –x, ++x) or postfix (x– –, x++) mode.
Prefix Increment/Decrement Operation
int x = 2;
int y = ++x; // x = 3, y = 3
int z = --x; // x = 1, z = 1
If the value of x is less than y, “Y is greater” string is retuned and stored in the variable: greater,
else “X is greater” is retuned and stored in the variable: greater.
3.6 EXPRESSIONS
An expression is a combination of operators and/or operands. Java expressions are used to create
objects, arrays, pass values to methods and call them, assigning values to variables, and so on.
Expressions may contain identifiers, types, literals, variables, separators, and operators (we have
already discussed all these topics). For example,
int m = 2,n = 3,o = 4;
int y = m * n * o;
m=2 is an expression which assigns the value 2 to variable m. Similarly, n=3 and o=4 are expressions
where n and o are being assigned values 3 and 4. m * n * o is also an expression wherein the
values of m, n, and o are multiplied and the result is stored in the variable y.
Here L R indicates associativity from left to right and R L indicates associativity from
right to left.
L4 x = y = z;
L5 System.out.println(" x = y = z: \t" + x);
// First two numbers are added and the added result is concatenated with
// String "Hello"
L9 System.out.println(1+2+" Hello");
}
}
Output
C:\Javabook\programs\chap3>Java AssociativityAndPrecedenceTest
2 + 3 * 2 = 8
Java Programming Constructs 57
2 * 5 / 3 = 3
(2 + 3) * 2 = 10
x = y = z: 1
3 − 2 + 1 = 2
i: 10 j 2 result: 6
Hello 12
3 Hello
Explanation
L1 Shows the precedence of * is more than +, that L7 In this expression, i-- + i / 2 - ++i + j++
is why 3 is first multiplied with 2 and the result (6) + ++j, the decremented value of i will be reflected
is added with 2 and then printed. while evaluating the sub-expression i/2, i.e., i--+i/2
L2 Shows two operators with equal precedence, * will be evaluated as 10 + 9/2 (result of sub-expression
and /. In this case, associativity plays a role instead of is 14). At this point i will have the value 9. While
precedence. As is evident from Table 3.9, * and / have evaluating ++i, the value of i is incremented first
left associativity, so the operators will be evaluated and then added, so the value of i becomes 10 again
from the left side. That is why 2 is multiplied with 5 (result of expression at this point is 14 –10 = 4). The
first and then the result (10) is divided by 3 to give value of j (i.e. 0) is added to the expression first and
the integer quotient 3, which is then printed. then incremented in the sub-expression j++. Now j
L3 Shows the precedence of (nudge) is more than
has the value 1 (result of expression at this point i--
* and + (or any other operator, refer Table 3.9). In
+ i/2 - ++i + j++is 4). In the last sub-expression
this case, operation within parentheses is performed
++j, the value of j (which is 1 now) is incremented
first, that is, 2 is added to 3 and then the result (5) is
first and then added to the expression (value of j is
multiplied with 2 to give 10 which is then printed.
Also note that when no parentheses were used in L1, now 2 which is added to 4 to produce 6 as the result).
the answer was 8. L8 & 9 Show the usage of + operator between
L4 Shows the assignment operator which is right different operands. The important point to note is
associative, so first the value of z is assigned to y that associativity and not precedence will be used
and then the value of y is assigned to x. for evaluating expression. The associativity of +
L6 Portrays the case of same precedence, so operator is from left to right, so the String “Hello”
associativity is used for expression evaluation. Table is concatenated to 1 first and then String “Hello
3.9 shows + and – have left associativity, so 2 is 1” is concatenated to the second number 2. In L9,
subtracted from 3 first and then the result (1) is added the numbers are added first and then the sum is
to 1 to output 2, which is then printed on the screen. concatenated with the String.
hand-side can fit inside the left-hand-side, the assignment is completed. For example, a smaller
box can be placed in a bigger box and so on. A byte value can be placed in short, short in an
int , int in long , and so on (see widening conversion). Any value can be assigned to a double.
Any value except a double can be assigned to a float. Any whole number value can be assigned
to a long; and int, short, byte, and char can all fit inside int. For example,
byte b = 10; // byte variable
int i = b; // implicit widening byte to int
Type conversion or promotion also takes place while evaluating the expressions involving
arithmetic operators. For example,
int i = 10; //int variable
double d = 20; //int literal assigned to a double variable
d = i + d; //automatic conversion int to double
In the previous statement, the int value i is promoted to double and then the two double values
(i & d) are added to produce a double result. The basic rule is that if either of the variables in a
binary operation (involving arithmetic, relational, equality) is double, then Java treats both values
as double. If neither value is a double but one is a float, then Java treats both values as float.
If neither is a float or a double but one is a long, then Java treats both values as long. Finally,
if there are no double, float, or long, then Java treats both values as an int, even if there are no
int in the expression. Therefore, the result will be a double, float, long or int depending on
the types of the operands. For example, consider the following declarations:
byte b = 10;
short s = 30;
The following statement is invalid because while evaluating the expression, byte and short
are automatically promoted to int, so the result is an int and short is used to store the result
which is smaller than int.
short z = b*s; //invalid
int i = b*s; //valid
In case of bitwise and, or, xor, if one of the operand is broader than int, then both operands
are converted to long; else both are converted to int. If bitwise not operator is applied to an
operand shorter than int, it is promoted to int automatically. In case of shift operators, if a single
operand has a type narrower than int then it is also promoted to int, otherwise not.
Let us take an interesting case
float f=3; // legal; int literal assigned to a float variable
The last declaration of a float variable shows that suffix f of F was not used while assigning
value and yet it was considered a legal statement. The reason is because 3 is an int and an int
value can be directly assigned to a float. But if the declaration would have been
float f = 3.0; // illegal;
Java Programming Constructs 59
Note Java treats all real numbers as double so 3.0 is treated as double, which cannot be assigned
directly to a float, as float is smaller than double. There are two possible solutions which can
be applied to the above statement: (a) suffix F or f with the literal i.e. 3.0f (b) cast it.
float f = 3.0f; // legal;
If you want to assign long values to int variables or double values to float variables, then the
compiler will not allow you to do so unless you explicitly tell it that you really want to do so with
the help of a cast. When it is necessary to put a bigger value into a particular smaller type, use a
cast. For example, consider the reverse of the box example. A bigger box has to be placed in a
small box. Then the bigger box has to be chopped so that the bigger box (which has now become
smaller) can be placed in the small box. Casting is not implicit in nature. It has to be explicitly
mentioned by preceding it with the destination type specified in the parentheses. For instance,
int i = (int)(8.0/3.0);
A cast lets the compiler know that you are serious about the conversion you plan to make.
When a value is cast before assignment, the right hand side is chopped down to fit into the left
hand side. For casting a floating-point number to an int or a long, the fractional part is truncated
resulting in an integer. If the resulting integer is small enough to fit in the left hand side, the
assignment is completed. But if the number is too large, then the integer is set to the largest
possible value of its left-hand-side type. If the real number is too small, the integer is set to the
smallest possible value of its left-hand-side type. For byte and short, if the value is small enough
to fit in the byte and short destination, the assignment is completed. The dark side of casting is
that it may result in the loss of sign, magnitude, and precision.
One more point worth mentioning is that if you try to put a long value into float variable,
Java treats this as a legal statement. For example,
long x = 32l;
float y = x; // legal statement
The point worth pondering is that how can a long value, which is of 64 bits, be assigned to a
float variable which is of 32 bits? To understand why this is a legal statement we need to know
how floating point numbers are represented. A float or double value is represented using IEEE
754 binary floating point standard. A floating point number is represented in four components—
sign, mantissa, radix, and exponent. A sign bit is used to denote a positive number or a negative
number. A value of zero in sign bit indicates positive number and 1 in sign bit indicates a negative
number. Mantissa holds the significant digits of the floating point number and exponent is used
for indicating the power (positive or negative) of the radix. The first bit of the exponent indicates
its sign. The format of a floating point number is shown below:
60 Programming in Java
Java uses a radix of 2. A float variable has 23 bits for mantissa and 8 bits for exponent. A
double variable uses 52 bits for mantissa and 11 bits for exponent. The bit representation of
these variables is shown below:
//casting
L1 int i = (int)(8.0/3.0);
// j will have the largest value of its type as 2147483648.0f is too large
L2 int j = (int)2147483648.0f;
System.out.println("i = " +i+ " j = " +j);
//casting: answer will contain 8 low order bits of the int value of 257
L3 byte b = (byte)257;
//casting: answer will contain 16 low order bits of the int value of 65537
L4 short s = (short)65537;
System.out.println("b =" +b+ " s = "+s);
Output
i = 2 j = 2147483647
b = 1 s = 1
Converting int to char K
Conversion to double result is : 4.0
i = 4
Result: 1
Explanation
L1 It shows the casting of a double expression which can be casted back to character. An integer
into an int. The result of dividing a double value by variable can hold a character, e.g. int x ='K'. This
a double value is a double, which is then casted into is a case of automatic promotion; here x will have
an int. the value 75 which is the ASCII value of 'K'.
L2 It shows the casting of a float literal into an L6 It shows the multiplication automatic promotion.
int, which is larger than the maximum value an int The expression involves multiplication that is left
variable can hold. So j is set to the maximum value associative. First, byte variable b is automatically
an int can hold. promoted to int and multiplied with i giving an int
L3 It shows the casting of an int literal into a result (i.e., 2*1 = 2). Then short is automatically
byte. It is again larger than the maximum a byte promoted to an int and multiplied with the previous
can hold. In this case, byte variable will contain the int result to give a new int result (i.e., 2*1 = 2).
value which is present in the 8 low order bit of the Now this int result is automatically promoted to
int literal 257. The int literal 257 has the binary double because it has to be multiplied to a double
value 00000000 00000000 00000001 00000001. literal (i.e., 2.0) giving a double result of 4.0.
After casting, byte will have the low order 8 bits L7 It shows the left shifting of bits in the expression
(00000001), which is the decimal value 1. b << 2. Before shifting, there is an automatic promo-
L4 It shows the casting of an int literal into a tion of byte variable b to an int and then the 32 bits
short, which is larger than the maximum a short can are shifted towards left by two places.
hold. In this case, the short variable will contain the L8 It is commented, as it will not compile.
value that is present in the 16 low order bits of the During evaluation of this expression c and b are
int literal 65537. int literal 65537 has the binary automatically promoted to int and added to produce
value 00000000 00000001 0000000 00000001. an int result. This result cannot be stored directly in
After casting, short will have the low order 16 bits a byte variable.
(00000000 00000001) which is the decimal value 1. L9 It complies because the operator used in this
L5 It shows the casting of an integer into a char. case is a compound operator that automatically casts
Characters are represented by integral ASCII values, the result into the destination type.
if…else
The syntax of if statement is as follows:
if (x = = 0)
{// Lines of code}
else if(x = = 1)
{// Lines of code}
………
else
{// Lines of code}
The arguments to a conditional statement like if must be a boolean value, which is something
that evaluates to true or false. You can have n number of else if (){} statements in your
program, as per your requirement. The if...else condition can also be nested as shown.
if (condition)
{
if (condition)
{//do something based on the condition}
}
The following example shows how if...else conditional statements can be used in Java.
Output
C:\>Java IFElseExample
18 20 22
Explanation
L1 It shows if statement comparing x with y. If L7 If condition on L5 returns false, then the control
x is less than y, then control passes into the enclosing passes on to the else on L7, which means that x is
curly brackets starting from L2. But in our example, less than y (L1) and z is not less than x (L3) and
is not greater than y (L5). So x is the smallest, y is
x is greater than y, so the control passes to the else
the largest, and z lies in between.
statement in L10. L8 It prints the facts of L7.
L3 It uses the nested if statement. This if clause L10 The else of if on L1. The control passes on
is within the if statement on L1. If condition in to this else if L1 returns false, which means x is
L1 returns true, then the condition on this line is not less than y.
checked. The condition checks whether z is less than L11 The starting curly bracket of else.
L12 It checks if z is less than y. If true, z comes
x, which is already less than y from L1. If (z < x)
first, then y, and x is the largest.
is true, then z is the smallest of the three, y is the L13 It prints the facts of L12.
largest, and x lies in between. L14 It checks if z is greater than x. If true, y comes
L4 It prints the facts of L3. first, then x, and z is the largest. In our example,
L5 If condition on L3 returns false, the control this case is executed as the value of x is 20, y is 18,
passes on to L5, which means z is not less than x and z is 22.
L15 It prints the facts of L14.
and in L5, z is compared with y. If z is greater than
L16 If z is not less than y (L12) and z is not greater
y, it means z is the largest, x is smallest, and y lies than x, i.e., z is in the middle, y is the smallest, and
in between. (We already know the fact from L1 that x is the largest.
x is less than y). L17 It prints the facts of L16.
L6 It prints the facts of L5.
Switch-case
Java has a shorthand for multiple if statement—the switch-case statement. Here is how we can
write the above program using a switch-case:
switch (x) {
case 0:
// Lines of code
64 Programming in Java
doSomething0();
break;
case 1:
// Lines of code
doSomething1();
break;
. . .
case n:
// Lines of code
doSomethingN();
break;
default:
doSomethingElse();
}
switch-case works with byte, short, char, and int primitive type. It can also be an enum type
(see Chapter 6) or one of the four special wrapper classes (see Chapter 6) namely: Byte for byte,
Short for short, Character for char, Integer for int. We can use strings also with the switch-case
from Java 7 onwards. It means that x must be one of these int, byte, short, char, enum type,
String or (one of the four) wrapper classes. It can also be an expression that returns an int,
byte, short, char or String. The value in x is compared with the value of each case statement
until one matches. If no matching case is found, the default case is executed.
Once a case is matched, all subsequent statements are executed till the end of the switch
block or you break out of the block. Therefore, it is common to include the break statement at
the end of each case block, unless you explicitly want all subsequent statements to be executed.
The following example shows how switch-case can be used in Java. A switch-case is more
efficient than an if-then-else statement, as it produces a much efficient byte code.
L1 char c='B';
L2 switch(c)
L3 {
L4 case 'A':
L5 System.out.println("You entered Sunday");
L6 break;
L7 case 'B':
System.out.println("You entered Monday");
break;
L8 case 'C':
System.out.println("You entered Tuesday");
break;
L9 case 'D':
Java Programming Constructs 65
Output
You entered Monday
Explanation
L1 It declares a character variable c with the L7 It shows the second case similar to L4. In our
value ‘B’. \ example, the value of the char variable is ‘B’, so
L2 It switches the control the case where a match L2 switches control to this line and the output will
was found. In our case, the control passes to L7. be You entered Monday. After printing the output,
L3 It is the start of switch statement. the control moves out of the switch-case because
L4–6 These show the first case, that is, case ‘A’. a break statement is included in the case.
If the value in the character variable is ‘A’, then this L8–12 These are similar to L7 but will only be
case is executed, and the output will be You entered executed in case the value of the char variable is
Sunday. L6 shows the break statement, to break out ‘C’ (L8), ‘D’ (L9), ‘E’ (L10), ‘F’ (L11), and ‘G’
of the switch-case statement. If the break statement (L12), respectively.
is not included in the code, then subsequent cases L13 It shows the default case. It is executed in case
will also be executed. the char variable takes a value other than A to G.
Note The value of character ‘c’ is fixed as ‘B’ in our example. This value should be set based on
the user’s input. But taking user’s input is not yet discussed; so we have fixed the value of
character ‘c’. We will discuss it in Chapter 9.
3.9.2 Loops
The purpose of loop statements is to execute Java statements many times. There are three types
of loops in Java—for, while, and do-while.
for Loop
The for loop groups the following three common parts together into one statement:
(a) Initialization
(b) Condition
(c) Increment or decrement
66 Programming in Java
To execute a code for a known number of times, for loop is the right choice. The syntax of
for loop is
for (int i = 0; i < 5; i ++)
Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Explanation
L1 It shows the for loop with its three parts: for which the print statement in L2 will be executed
initialization (i is initialized to 1), condition (i is less and likewise for i = 2, 3, 4, and 5.
than or equal to 5) and the third is increment (i++). L2 It prints the square of i (i.e., i*i). This line
The loop will be executed five times. This loop has will be executed five times, once for each value of i.
only one statement. Initially the value of i will be 1,
while Loop
The while loop is used to repeatedly execute a block of statements based on a condition. The
condition will be evaluated before the iteration starts. A for loop is useful when you know the
exact number of iterations. If you want to execute some statements for an indefinite number
of times (i.e., number of iterations is unknown), a while loop may be the better choice. For
example, if you execute a query to fetch data from a database, you will not know the exact
numbers of records (rows or columns) returned by the query. A for loop cannot be used to iterate
the returned records in this case.
Java Programming Constructs 67
Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Explanation
L1 It initializes an int variable i to 1. loop is checked. It goes on until the condition in the
L2 It demonstrates the while loop. In this loop, while returns false (i.e., when value of i becomes
the value of i is checked to be less than or equal 6), in which case the control comes out of the loop.
to 5, which in the first iteration is 1 (less than 5), L3 Curly bracket to denote the start of while loop.
so the control passes into the loop. After executing L4 It prints the square of i.
the statements within the enclosing curly brackets L5 It increments the value of i.
of the while loop, again the condition of the while L6 Curly bracket denoting the end of while loop.
do-while Loop
A do-while loop is also used to repeatedly execute (iterate) a block of statements. But, in a
do-while loop the condition is evaluated at the end of the iteration. So the do-while loop (unlike
the while loop) will execute at least once and after that depending upon the condition.
The general form of a do-while loop is
do
{
Statements to execute once and thereafter while the condition is true
} while (test);
Next-statement;
68 Programming in Java
Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Explanation
L1 It initializes an int variable i to 1. executed at least once and later it depends on the
L2 It shows the starting do statement of the do- condition specified in the while loop on L6. In this
while loop. case, the statements on L4 and L5 will be executed
L4 to 6 The statement on L4 and L5 will be not only once, but five times (value of i loops from
1 to 5 inclusive).
for-each Loop
Java 5 introduced what is sometimes called a for-each statement that accesses each successive
element of an array, list, or set without being associated with iterators or indexing. This new
for statement is called the enhanced for or for-each. This loop is used to access each value
successively in a collection of values (like array). It is commonly used to iterate over an array
or a collections class (e.g., ArrayList). Like for loops, these loops perform a fixed number of
iterations. But unlike them, the for-each loop determines its number of steps from the size of
the collection.
The general form of for-each loop is
for (type var : arr)
{
// Statements to repeat
}
We will return to for-each loop when we discuss arrays and collections in Java.
3.9.3 Branching Mechanism
Java does not offer a go to type of statement as in some older languages, because it leads to
unreadable code. However, Java supports other ways to jump from one statement to another.
Two types of branching statements are available in Java—break and continue.
Java Programming Constructs 69
break Statement
break statement is used in case the user needs to jump out of a loop, while the continue statement
is used where the user wants to go back to the top of the loop. A break statement is used to jump
out of a loop when a particular condition occurs, as shown below:
while (i < 5) {
//do Something;
if(i < 0) break; // jump out of the loop
}
The break will result in the program flow moving out of the loop to the next statement following
the loop statement. The following example is a program statement to choose prime numbers
within a given range.
Output
C:\Javabook\programs\chap3>Java PrimeDemo
Prime numbers between 1 to 30 : 2 3 5 7 11 13 17 19 23 29
Explanation
L1 It creates a for loop which ranges from 1 to by any number in this range (i.e., remainder is 0),
30 (as we need to find primes between 1 and 30). break out of the inner for loop and check (in L4)
L2 It creates an inner for loop which starts from whether the numerator (j) and denominator (k) are
2 (as 1 is not a prime number) to j. same. (Prime numbers are divisible by 1 and itself).
L3–5 Condition to check whether j is divisible
If both are same, it is a prime number.
by any number in the range 2 to j-1. If it is divisible
If, instead, you want the flow to jump out of both the loops, use the labeled break as shown
in the next example.
{
L1 Outer : for(int i = 0; i < 4; i++){
L2 for(int j = 1; j < 4; j++){
L3 System.out.println("i:" + i + " j:" + j);
L4 if(i == 2) break Outer;
}}}}
Output
C:\Javabook\programs\chap3>Java LabeledBreakDemo
i:0 j:1
i:0 j:2
i:0 j:3
i:1 j:1
i:1 j:2
i:1 j:3
i:2 j:1
Explanation
L1 A label named Outer is placed on the outer for L3 Prints the value of i and j.
loop with a colon after the label name. L4 If the value of i is equal to 2, the control comes
L2 An inner for loop is created. out of both the loops and the program terminates.
Continue Statement
Situations can occur where you do not want to jump out of a loop, but simply stop the current
iteration and go back to the top and continue with the next iteration, as shown in the following
code.
Example 3.15 Code Snippet for continue
L1 while (i < 5){
L2 //doSomething1;
L3 if(i < 4) continue;
L4 //doSomething2;
}
Explanation
L1 Beginning of while loop. keeps sending the program flow back to the next
L2 Inside the loop, there are some statements iteration of the loop.
shown in comments (//do something1). Sometimes you may want to jump out of not only the
L3 If i is less than 4, continue to the top of the inner loop but the outer loop as well. In that case, you
loop for next iteration. can put a label (similar to label in break) on the outer
L4 The doSomething2 statement will not execute loop and jump to it and continue its next iteration, as
until i equals 4 because the continue statement in the following example.
Explanation
L1 Labelled continue (i.e., jmp0) on the beginning L3 The if statement inside the inner for loop
of while loop. states to jump to the outer while loop if i is equal
L2 Inner for loop. to 2, else execute the statements (do something).
SUMMARY
Java is an object-oriented programming language that to be used with literals. Apart from this, Java 7 added
can be used to solve problems. All the Java keywords strings to be used with switch case statements.
have a fixed meaning and form the building block for There are several operators in Java that can be
program statements.
classified as arithmetic, relational, logical, assignment,
Variables hold data at memory locations allocated to increment and decrement, conditional, bit-wise, and
them. There are eight basic data types in Java, namely
special. Expressions are formed with variables and
byte, short, int, long, float, double, boolean, and char.
operators. Operators in Java have certain precedence
Java is portable across computer platforms. Java does
not leave the size of data types to the machine and and associativity rules that are followed while
the compiler, but specifies everything. All integer (byte, evaluating expressions. Automatic-type conversion
short, int, long) and floating-point types (float, double) takes place according to a set of rules in expressions
are signed in Java. Java 7 introduced binary literals with mixed types. Explicit type conversion (casting) is
to be assigned to numeric variables and underscores also possible in Java.
EXERCISES
Objective Questions
1. In the following class definition, which is the first 3. What is the output when the following program
line (if any) that causes a compilation error? is compiled and run?
Select the correct answer.
class test {
public class CastTest { public static void main(String args[]){
public static void main(String args[]){ int i,j,k,l=0;
char a; k = l++;
int j; j = ++k;
a = 'A'; //1 i = j++;
j = a; //2 System.out.println(i);
a = j + 1; //3 } }
a++; //4 (a) 0 (b) 1 (c) 2 (d) 3
} 4. What gets printed on the standard output when
} the following class is compiled and executed?
Select the correct answer.
(a) The line labelled 1.
(b) The line labelled 2. public class SCkt {
(c) The line labelled 3. public static void main(String args[]) {
(d) The line labelled 4. int i = 0;
2. Which of these assignments are valid? boolean t = true;
(a) short s = 48; (b) float f = 4.3; boolean f = false, b;
(c) double d = 4.3; (d) int I = ‘1’; b = (t && ((i++) == 0));
72 Programming in Java
Review Questions
1. What are the rules for naming an identifier in 3. What are shift operators? How many types of
Java? shift operators are available in Java?
2. Explain conversion. How is it different from 4. What are the differences between for, while
casting? and do...while loops?
Java Programming Constructs 73
Programming Exercises
1. Write a program Pattern.Java that takes an 6. Write a program that converts inches to centime-
integer, N and prints out a two-dimensional tres.
N-by-N pattern with alternating spaces and 7. Write a program that converts acres to hectares
asterisks, like the following 4-by-4 pattern. and vice versa.
**** 8. Write a program that accepts resistances and
**** outputs the equivalent resistance when they are
**** connected in series. (Assuming the Resistance
**** R1=12, R2=14, R3=15).
2. Write a program that does binary-to-decimal and 9. Write a program that calculates the equivalent
decimal-to-binary conversions. (Do not use the resistance arranged in parallel. The formula for
predefined methods.) calculating the equivalent resistance arranged in
3. Write a program that takes a price and prints out parallel is
the appropriate tax along with the total purchase 1
Re quiv =
price assuming the sales tax in your city is 1 1
12.35%. R1 R2
4. Write a program that takes the number of hours 10. Write a program that calculates how much a
worked by an employee and the basic hourly pay, $10,000 investment would be worth if it increased
and outputs the total pay due. in value by 20% during the first year, lost $500
5. Write a program that takes an integer n and in value in the second year, and increased 16%
calculates n!. in the third year.
4.1 CLASSES
Java is an object-oriented language. In the first chapter, we have learnt the concepts of object-
oriented programming (OOP). Before applying these concepts in Java, we must understand the
basic building blocks of OOP, i.e., classes and objects.
In the real physical world, everyday we come across various objects of the same kind. One
of the many things we come across are motorbikes. In terms of object-oriented language, we
can say that the bike object is one instance of a class of objects known as ‘motorbikes.’ Bikes
have gears, brakes, wheels, etc. They also follow certain behaviors, when functions are applied
on them, e.g., bikes slow down when brakes are applied, they accelerate when geared up and
acceleration is applied, and so on.
Manufacturers produce many bikes from the same blueprint by taking advantage of the fact
that bikes share similar characteristics. It would be very inefficient to produce a new blueprint
for every individual bike they manufactured.
In the object-oriented software, there are many objects of the same kind, i.e., belonging to
the same classes that share certain characteristics. Like the bike manufacturer, we can take
advantage of the fact that objects of the same kind are similar and a blueprint for those objects
can be created. Software ‘blueprints’ for objects are called classes.
Classes and Objects 75
Bike Let us come back to our bike class, which would also declare and provide
implementations for the instance methods or functions that allow the rider to
boolean kickStart
change gears, apply brakes, and accelerate. Figure. 4.1 shows the bike class.
boolean buttonStart
int gears Note A class is a blueprint or prototype that defines the variables and
methods common to all objects of a certain kind. In other words, a
accelerate( )
class can be thought of as a user-defined data type and an object as
applyBrake( ) a variable of that data type that can contain data and methods, i.e.,
changeGear( ) functions working on that data.
4.2 OBJECTS
The object-oriented technology revolves around objects. We see many objects around us
such as table, chair, dog, fan, computer, pen, and car. These objects need not be tangible
ones only, but can be intangible also, e.g., bank accounts, marks, fees, etc. All these real-
world objects have different states and behaviors. The state of an object is defined by the
values of the attributes at any instant. Bikes have attributes (speed, engine capacity, number
of wheels, number of gears, brakes), behaviors (braking, accelerating, slowing down, and
changing gears) and on application of this behavior on attributes, the state of the object will
change. Bike object can be in various states, it can be stationary, moving etc. For example,
when we apply brakes, the speed will reduce and when we accelerate speed increases. A
state will change over time and at any instant a state would be somewhat like current speed
= 60 km/hr and current gear = 4th. Similarly, the state of a fan would be either off or on.
We can conceptualize these real-time objects as software objects. They are similar natured
in the sense they too have states and behaviors. The state in software objects is maintained in
variables and the behavior can be implemented using methods. It is interesting to know that
these real-world objects can be represented using software objects.
Note An object is a software bundle that encapsulates variables and methods operating on those
variables.
You might want to represent a real-world bike as a software object in a gaming application.
Abstract objects representing abstract concepts can also be modeled using
:Bike software objects. For example, a bank account is a common object used in banking
kickStart = false
solutions to represent the details of bank accounts of various customers of a bank.
buttonStart = true
Figure. 4.2 shows a common visual representation of a software object.
It would be correct to say that everything the software object knows (state) and
gear = 4
can do (behavior) is expressed by the variables and methods within that object.
accelerate( ) A software object that models the real-world bike would have variables that
applyBrake( ) indicate the bike’s current state: its speed is 10 mph, its acceleration in terms of
changeGear( ) revolutions per minute is 5000 rpm, and its current gear is 4th. These variables
Fig. 4.2 Bike Object are known as instance variables.
76 Programming in Java
The object bike would also have methods to brake, accelerate, and change gears. These are
known as instance methods. Only relevant fields and behaviors are added into a class. For
example, a bike does not have a surname, and it cannot speak or sleep. A bike class can be
created that declares several instance variables to contain the gears, the brakes, and so on, for
each bike object and every bike will have its own brakes, gears, etc.
It is worth noting here that all object instances have their own copies of instance variables.
This means that if there are five object instances of a bike class, there are five copies of each
instance variable defined in that class. Each object has its own copy of instance variables which
is different from other objects created out of the same class.
The values of the instance variables are provided by each instance of the class. So, after you
have created the bike class, you must instantiate it (create an object of it) before you can use it.
When an instance of a class is created, an object of that type is created and memory is allocated
by the system for the instance variables declared by the class. Then the object’s instance methods
can be invoked to perform operations.
Note Instances of the same class share the instance method implementations (method
implementations are not duplicated on a per object basis).
In addition to instance variables and methods, classes can define their own class variables
and methods. Every object will have its own instance variables but class variables will be shared
by all the objects of the class. You can access class variables and methods using an instance
of the class or using the class name. You need not instantiate a class to use its class variables
and methods. Class methods can only access the class variables directly. They don’t have direct
access to instance variables or methods. A single copy of all class variables is created and all
instances of that class share it. For example, suppose all cars had the same number of gears. In
such a situation, a class variable can be created that defines the number of gears. All instances
of the class will share this variable. If any object manipulates the class variable, then it changes
for all objects of that class.
4.2.1 Difference Between Objects and Classes
Both objects and classes look the same. Yes, it is a fact that the difference between classes and
objects is often the source of some confusion. In the real world, it is obvious that classes are
not themselves the objects that they describe—a blueprint of a bike is not a bike. However, it is
difficult to differentiate between classes and objects in programming. This is partially because
objects in programming are merely the electronic models of real-world objects or abstract
concepts. Classes have logical existence, whereas objects have physical existence, e.g., furniture
itself does not have any physical existence, but chairs, tables, etc. do have.
4.2.2 Why Should we Use Objects and Classes?
Modularity, information hiding, i.e., data encapsulation, can be incorporated using objects.
Classes, being blueprints, also provide the benefit of reusability along with the ease of changing
and debugging code. For example, bike manufacturers reuse the same blueprint over and over
again to build lots of bikes. Programmers use the same class repeatedly to create many objects.
Classes and Objects 77
Here the name of the class is GoodbyeWorld. The class just contains the main() method, which
is responsible for displaying GoodbyeWorld on the screen.
To sum up, all the action in a Java program takes place inside the class. Methods and variables
are defined inside the classes. The class is the fundamental unit of programming in Java. The
class declaration can specify more about the class, like you can:
declare the superclass of a class
For each of the cases above, the class declaration will differ accordingly. We will talk about that
as and when we cover the related concepts. Taking all the possibilities of class declaration in
Java, we can summarize the class declaration syntax as
[modifiers] class ClassName [extends SuperClassName] [implements InterfaceNames]
{ . . . }
The items enclosed inside [ ] are optional. A class declaration defines the following aspects
of the class:
modifiers declare whether the class is public, protected, default, abstract or final
Only the class keyword and the class name are mandatory. Other parameters are optional.
78 Programming in Java
Note The Java compiler assumes the class to be non-final, non-public, non-abstract, subclass of objects
(discussed in Chapter 6) that implements no interfaces if no explicit declaration is specified.
Certain terms in the above syntax such as modifiers, extending superclasses, and
implementing interfaces, which are presently unfamiliar, will be discussed in the later chapters.
Let us see how you can declare instance variables in a class. Example 4.2 shows a sample class
declaration with two instance variables. We will return to the discussion of instance variables
later in the chapter. Please note that if you try to run this example it won’t show any output
because it is not fully functional and there are certain statements/methods that we need to add
so that this program can display any output, which will follow later in the chapter.
Explanation
L1 Class declared with the keyword class followed L3 Declares another float instance variable taxRate
by the name of the class SalesTaxCalculator. to denote the rate of tax on the sale amount.
L2 A instance variable amount is declared to denote L4 End of the class.
the amount on which sales tax has to be calculated.
Classes and Objects 79
The above example shows a class with two instance variables. Instance variables are part of
the instance of the class (object). These instance variables will be created when the instance
is created. In order to be able to access/manipulate these instance variables, we need to create
objects of this class. We have already seen what objects are. Let us see how objects are created
and used in Java.
This statement creates a new SalesTaxCalculator object. This single statement declares,
instantiates, and initializes the object. SalesTaxCalculator obj1 is a reference variable declaration
which simply declares to the compiler that the variable obj1 will be used to refer to an object
whose type is SalesTaxCalculator. The new operator instantiates the SalesTaxCalculator
class (thereby allocating memory and creating a new SalesTaxCalculator object), and
SalesTaxCalculator() initializes the object.
where type is the type of the object (i.e., class name) and name is the name of the reference
variable used to refer the object. Classes are like new data types. So type can be any class such
as the SalesTaxCalculator class or the name of an interface.
Note A variable holds a single type of literal, i.e., 1, bat, 345, etc. An object is defined as an instance
of a class with a set of instance variables and methods that perform certain tasks depending
on what methods have been defined for. A reference variable is used to refer/access an object.
A reference variable is of a specific type name of the class is its type. Unlike normal variable,
reference variables can be static, instance or local variables as well as they can be passed to
or returned from the method.
The above declaration won’t create an object. It will create a variable with a name and specify
its type. For example, SalesTaxCalculator is the type and obj1 is the reference variable.
4.4.2 Instantiating an Object
After declaring a variable to refer to an object, an actual, physical copy of the object must be
acquired and assigned to that variable. This can be achieved by the new operator. The new operator
instantiates a class by dynamically allocating (i.e., at runtime) memory for an object of the class
80 Programming in Java
type and returns a reference to it. This reference is nothing but the address in the memory of the
object allocated by new. This reference or memory address is then stored in the variable declared.
The new operator requires a single argument, i.e., a constructor call. The new operator creates
the object or instantiates an object and the constructor initializes it.
SalesTaxCalculator obj1 = new SalesTaxCalculator()
The above statement just creates an instance of a class, SalesTaxCalculator. In other words, the
new operator creates an object obj1 by allocating memory for its member variables, i.e., amount
and taxRate (Example 4.2) and few other items.
4.4.3 Initializing an Object
By initializing an object, we mean the instance variables are assigned initial values. The instance
variables of a particular object will have different values during the lifetime of an object. But to
start with, initial values are required. If no value is specified for the instance variables, then the
default values will be assigned to those variables based on their respective types. Initial values
can be provided by instance variable initializers and constructors.
Instance variable initializers are values directly assigned to the instance variable outside any
method/constructor but within the class. [As shown in L2 and L3 of Example 4.2(a)].
The best and convenient approach is to create your own constructor. Constructors should be
provided within classes to initialize objects. Constructors have the same name as that of the class.
Constructors are invoked as soon as the object is created. In case you do not create a constructor
for your class, Java compiler provides a default constructor for your class automatically. The
default constructor is a zero argument constructor with an empty body. The implicitly created
default constructor is invoked as soon as the object is instantiated with new keyword as shown
below.
new SalesTaxCalculator()
We will come back to the concepts of constructors along with the examples explaining them in
Section 4.6.
obj1 Null
To sum up, the final object creation can be said as complete, when the objects are initialized,
either with an implicit constructor or an explicit constructor. This object creation can be used in
a programming code in two ways:
SalesTaxCalculator obj1 = new SalesTaxCalculator();
Here all the three operations, object declaration, object instantiation, and object initialization are
done by a single statement. The above process takes place in the following way:
Now that we know how to create a class and objects for that class, we can rewrite Example
4.2 where we can do these things in one program only. The following program displays a class
SalesTaxCalculator, with two instance variable (initialized to some values) and two objects of
the class SalesTaxCalculator, obj1 and obj2 (created inside the main method). Instance variable
initializers are used in this example to initialize objects: obj1 and obj2 (Fig. 4.3).
Output
D:\javabook\programs\chap4\java SalesTaxCalculator
Amount in Object 1: 100.0
Tax Rate in Object 1: 10.2
Amount in Object 2: 100.0
Tax Rate in Object 2: 10.2
Explanation
L1 Class declaration. allocates memory to these objects according to the size
L2 & L3 Instance variable have been declared with of instance variables (plus a few more bits for some
their initializer. more items). Note that no constructor has been created
L4 Main method declared. in this class, so the Java compiler will automatically
L5 & L6 Two objects of this class are created in provide a default constructor for this class which
these lines. As already discussed, the new keyword is being invoked while creating object in these
82 Programming in Java
statements. The default constructor is empty, so it is L7 Is a print statement that prints the value of
the responsibility of the Java compiler to ensure that the instance variable present in obj1. The variable
the instance variable are initialized to their respective can be accessed through the object followed by the
values (amount = 100.0f and taxRate = 10.2f) dot operator from main method or outside the class
according to their initializer (mentioned in L2 and (depends on access and scope of the object).obj1.
amount will return the value of amount stored in
L3) by the JVM at runtime. (How does it ensure
the instance obj1. The value of the variable can be
this? We will discuss it later in the chapter). For
changed by using the following syntax:
instance, we will consider that the instance variable
obj1.amount=200.0f;
initializers are used by the Java compiler to initialize
these instance variables. L8, 9 & 10 Similar to L7.
Note Setter methods can also be used for assigning or modifying values of instance variables (i.e.,
set X() or set Y() where x and y are the names of the instance variables) They are declared
inside a class, as shown in Examples 4.3 and 4.5 (methods will be discussed in the next section).
The above program has a limitation that all objects created will have the same value for amount
and taxRate. Later on it can be changed using object references. But it would be wiser to let all
objects have their own different amount and tax rates as soon as they are created. This problem
will be solved using constructors (Section 4.6).
4.5 METHODS
The word method is commonly used in object-oriented programming. It is similar to a function
in any other programming language. Many programmers use different terms, especially function,
but we will stick to the term methods. None of the methods can be declared outside the class.
All methods have a name that starts with a lowercase character.
4.5.1 Why Use Methods?
To Make the Code Reusable If you need to do the same thing or almost the same
thing, many times, write a method to do it and then call the method each time you have
to do that task.
To Parameterize the Code You will often use parameters to change the way the method
behaves.
For Top-down Programming You can easily solve a bigger problem or a complex one
(the ‘top’) by breaking it into smaller parts. For the same purpose, we write methods.
The entire complex problem (functionality) can be broken down into methods.
To Simplify the Code Because the complex code inside a method is hidden from other
parts of the program, it prevents accidental errors or confusion.
4.5.2 Method Type
There are two types of methods in Java: instance methods and class methods. Instance methods
are used to access/manipulate the instance variables but can also access class variables. Class
Classes and Objects 83
methods can access/manipulate class variables but cannot access the instance variables unless
and until they use an object for that purpose.
4.5.3 Method Declaration
The combined name and parameter list for each method in a class must be unique. The
uniqueness of a parameter is decided based on the number of parameters as well as the order
of the parameters. So,
int methodOne (int x, String y)
is unique from
int methodOne (String y, int x ).
The parameters enclosed within square brackets [ ] are optional. The square brackets are
not a part of the code; they are included here to indicate optional items. We will discuss only
those parts that are required at the moment and leave the rest for the later chapters. The method
declaration includes
M odifiers If you see the syntax of the method declaration carefully, there is an optional part
of it, modifiers. There are a number of modifiers (optional) that can be used with a method
declaration. They are listed in Table 4.1.
Table 4.1 Optional Modifiers used While Declaring Methods
Modifier Description
public, protected, Can be one of these values. Defines the scope—what class can invoke
default or private which method?
static Used for declaring class methods and variables. The method can be invoked
on the class without creating an instance of the class.
abstract The class must be extended and the abstract method must be overridden
in the subclass.
native The method is implemented in another language (out of the scope of this
book).
synchronized The method requires that a monitor (lock) be obtained by calling the code
before the method is executed.
Return Type It can be either void (if no value is returned) or if a value is returned, it can
be either a primitive type or a class. If the method declares a return type, then before it exits,
it must have a return statement.
Method Name The method name must be a valid Java identifier. We have already discussed
sequence of statements that are executed sequentially. The method body can also be empty.
In Example 4.2(a), we have stored data: amount and taxRate but we have not calculated the
tax amount based on the rate. We need to calculate the tax amount. This operation would require
some calculation (operations) to be performed on the data variables. These operations will be
performed inside a method so we need to add a method to that class and revise the class. The
method added is calculateTax()(L4) which calculates the taxed amount. This method is invoked
in L10 and 11 by the two objects using the dot operator. Note that the answer in both cases is the
same because the data in both cases is same, i.e., amount and tax rate are same for both objects
so the taxed amount is same.
Output
The Taxed Amount is: 10.2
The Taxed Amount is: 10.2
Let us take a different example to explain the concepts in more detail. The following example
has a couple of instance methods, setRadius() and calculateArea(), declared inside the class,
Circle. The word instance has been particularly used to distinguish between instance and
class methods. The modifier static has not been used while declaring methods so the methods
become instance methods.
Classes and Objects 85
Explanation
L1 Class declaration. L8 Declares another instance method. The instance
L3 & 4 Instance variable declaration. method calculateArea() has been declared to return
L5 Declares an instance method popularly known a value of type float.
as setter or mutator methods (note that static L9 “{” signifies the start of the method body.
modifier is not used in this declaration). They are L10 Instance variables pi and radius are multiplied
known as setter or mutator methods because they set to calculate the area of the circle. As shown, instance
or change (mutate) the values of instance variables.
variables can be used by instance methods directly
The data type void indicates that this method will not
to produce result. An important point to note is that
return any value. The name of the instance method
is setRadius()and it accepts a float parameter different Circle objects will have different values
rad. This method is used to assign a value to the of radius and obviously the calculated area will
instance variableradius. The method argument be different but the instance methods remains the
rad is assigned to the instance variable radius same. In other words, instance methods are not
in this method on L7. It also shows that instance implemented on a per object basis as is the case with
methods can access instance variables directly. instance variables. The area of the circle is stored in
Instance methods are invoked using objects, so data the local variable, area, declared as float.
residing in objects can be easily accessed (set or get) L11 The value stored in the variable area is returned
by instance methods. by the return statement.
L6 The body of the method starts with the left L12 The first right brace “}” signifies the end of
brace, “{”.
method, calculateArea(), and the second brace “}”
L7 rad is assigned to an instance variable radius
signifies the end of class, Circle.
of type float. The right brace “}” signifies the end
of the method.
Note The responsibility of providing initial values is that of constructors, and constructors are called
only once, i.e., during object creation. If the value of instance variables has to be changed,
setter methods should be used and that too can be invoked any number of times.
86 Programming in Java
Output
Area of Circle = 28.26
Explanation
L6 Creates an object of Circle class. setRadius() the help of a dot operator. A value 3.0f (f to
and calculateArea() are instance methods of the indicate float value) is passed as an argument in the
class, Circle. So an instance is required to invoke setRadius() method invocation. This value 3.0f
these instance methods and that instance must be is assigned to the local float variable rad, which is
of the class the methods are a part of, i.e., Circle actually an argument in the method declaration (see
(Example 4.3). That’s why an object of the Circle
Example 4.3, L5). The calculateArea()method
class named circleobj is created.
L7 & 8 Using the instance created in L6, we call calculates the area and returns the value which is
the methods setData() and calculateArea() with captured in a float variable area1.
Note The number and type of the actual and formal parameters should be same for a method. Also
note that the class having the main() method is to be executed first by the Java interpreter.
In Example 4.3, we have created a class ( Circle ) and two methods in that class.
Example 4.4 shows how the methods of Circle class (Example 4.3) are called from another
class, i.e., CallMethod. The methods can also be called from within the class, as shown in
Example 4.5.
Explanation
The example is entirely same as that of Example 4.3 has been squeezed out and inserted in the class Circle
up to L10. (The output is entirely same as that of the as shown in the lines 11–15.
previous program.) L12 An object of the Circle class, named
L11 The execution begins at main(). Because circleobj, is created using the new operator.
main() is defined in this class, it can execute on L13 setRadius() is called with the help of an
its own and there is no need of a separate class like object of the
Circle class and a float argument is
passed to it.
CallMethod (Example 4.4) for invoking the methods
L14 calculateArea()is called using the object
of the Circle class. The main method from that class created in L12.
Note In Java, all values are passed by value. This is unlike some other programming languages that
allow pointers to memory addresses to be passed into methods. When a primitive type value
is passed to a method, the value is copied. The copied value, if changed inside the method,
does not affect the original value. When an object is passed, only the reference is copied.
There is just one object that has two references now on it. The changes made to the object
through one reference will be reflected when the object is accessed through other references.
more methods with the same name, but each with a different parameter list. This is a powerful
feature of the Java language called method overloading. Overloading allows you to perform
the same action on different types of inputs. In Java whenever a method is being called, first
the name of the method is matched and then, the number and type of arguments passed to that
method are matched.
In method overloading, two methods can have the same name but different signatures, i.e.,
different number or type of parameters. The concept is advantageous where similar activities
are to be performed but with different input parameters. Example 4.6 shows an example of
overloading a method max() in order to calculate the maximum value for different combinations
of inputs.
Output
C:\javabook\programs\chap4>java OverloadDemo
max method with long argument invoked
23 is greater
max method with long argument invoked
3 is greater
max method with double argument invoked
54.0 is greater
max method with float argument invoked
43.0 is greater
Explanation
L1 Method max is defined inside class OverloadDemo upon the number and type of arguments). In our case,
with two arguments of type float. we have only two arguments in all the overloaded
L2 Marks the beginning of the method. methods. So the decision is taken according to the
L3 Shows a print statement describing the method type of arguments. In this particular statement, two
that has been invoked. long arguments are passed. First of all, Java tries to
L4 if statement is used to check whether the float find an exact match, i.e., a method named max in class
argument a is greater than b. If a is greater, then L5 OverloadDemo which accepts two long arguments.
prints a is greater, else L7 prints b is greater. Java finds the method in L10. The method is called. If
L8 & 9 Overloaded method max is defined in these an exact match could not be found (say for example,
lines. This overloaded version of the method accepts the method max with long arguments is not present
two arguments of type double . This is different in the OverloadDemo class), then Java looks for a
from the max method defined in L1. The processing method named max which has the arguments to
inside this method is entirely similar to the previous accommodate these long values (Remember: long
method with the exception that now the maximum values can be accommodated implicitly only in float
will be chosen from two double values instead of and double). This example has max methods with
float values. both float and double arguments. So which method
L10 & 11 Another version of overloaded method will be called? The max method with float arguments
max is defined in these lines. This overloaded version will be called (long values are promoted to float and
of the method accepts two arguments of type long. passed). And in case the max with float arguments
This is different from the max method defined in is also not available, then the method with double
lines L1 and L8. The processing inside this method arguments will be called (long values are promoted
is entirely similar to the previous method with the to double and passed).
exception that now the maximum will be chosen from L16 max method is called with two int arguments
two double values instead of float values. passed to it. In OverloadDemo class, Java does not find
L12 main method has been defined. Execution a method which accepts two int arguments, but it
starts from main method. finds a method max that accepts two long arguments.
L13 Marks the beginning of the main method. These two int arguments are automatically promoted
L14 An object of the class is created to invoke the to long and passed to the method with the name
instance methods. max accepting two long arguments (automatic type
L15 Shows the invocation of the method, max, and promotion has taken place here).
two arguments that are passed to it. The question L17 Shows the invocation of max method with a
arises, which version of the max method will be double argument and a float argument. In this case,
invoked? (Remember: The invocation will be based Java does not find an exact match, as there is no such
90 Programming in Java
method named max that accepts a double argument cannot be called, as both the arguments are bigger
and a float argument. So, automatic promotion takes than long. So, the max method with both double
place in this case also. The question arises that which arguments will be called, as the first argument is a
overloaded method will be called? The max method perfect match and the second will be automatically
with both float arguments cannot be called, as promoted to double (see output).
the first argument that is being passed is a double. L18 The max method with both float arguments
Similarly, the max method with both long arguments will be called in this case.
Note As a general rule, automatic type promotion takes place while passing parameter values to
methods. In overloading, the decision of choosing which method to invoke is resolved by the
Java compiler at compile time (early-binding) rather than delaying it till runtime because
(a) Java is a strongly typed language.
(b) Resolving all these issues at compile time will avoid unnecessary exceptions at runtime.
(c) Enhanced performance.
4.6 CONSTRUCTORS
Whenever an object is created for a class, the instance variables of the class needs to be initialized,
i.e., they need to be given initial values. It can be done through instance variable initializers
(as shown in L2 and L3 [Examples 4.2 and 4.2(a)], L3 (Example 4.3) and L2 (Example 4.5)) and
instance initialization blocks. An instance initialization block is a block of statement enclosed
in parenthesis with initialization placed in it as shown below:
class Rectangle
{
// Instance initialization blocks
{
length=10;
width=10;
}
}
But Java has a simple and concise method of doing it. It has a mechanism for automatically
initializing the values for an object, as soon as the object is created. The mechanism is to use
constructors.
Constructors have the same name as the class they reside in and they are syntactically similar
to a method. Constructors are automatically called immediately after the object for the class is
created by a new operator. Constructors have no return type, not even void, as the implicit return
type of a constructor is the class type itself.
In Section 4.4.3, we discussed a little about constructors, promising that we would come
back to this topic. Now it is time to recall that section on object creation. An implicit or default
constructor is used as a parameter to the new operator, just as shown below.
SalesTaxCalculator r1 = new SalesTaxCalculator ();
Here, the new operator is calling the SalesTaxCalculator() constructor. If the constructor is
explicitly defined within the class just as shown in Example 4.7, it is known as explicit constructor,
otherwise Java automatically creates a default constructor as soon as the object is instantiated
by the new operator. They are known as implicit or default or no-argument constructors. In
Classes and Objects 91
earlier examples, no constructor was explicitly provided, so Java provided them with a default
constructor. But in case you define your own constructor within the class (Example 4.7), the
default constructor will not be provided by Java. In that case, the constructor defined within the
class will be called.
The default constructor, provided by Java compiler, is a no-argument constructor with empty
body. The only question that would arise now is that if the default constructor is an empty
constructor, then how are the variables initialized to the user specific values or default values
and who does it? For example in case of Examples 4.2, 4.2(a), and 4.2(b), when instance variable
initializers are used and no constructors has been defined in the SalesTaxCalculator class, how
are the objects obj1 and obj2 initialized with the values specified in instance variable initializers
as the default constructor is an empty constructor. What happens in the background is that Java
compiler creates a special method known as <init> method for each of the constructors specified
in the class. The code explicitly written in the constructors is placed within the <init> method
after some operations like calling the superclass constructor, instance variable initializers and
instance initialization blocks in the order in which they appear in the source code. When no
constructors have been specified, the Java compiler creates a default constructor and an <init>
method for the default constructor. This method will also include a call to superclass constructor
as well as the instance variable initializers and instance initialization block (if any mentioned in
the class and in the order mentioned in the source code).When no constructors and no instance
variable initializer or block have been specified, the Java compiler creates a default constructor
and <init> method for the default constructor, which initializes the instance variables with their
respective default values.
Note <init> is a special method, meant for the JVM (to initialize objects) and not the programmer.
So you cannot create a method by this name in your program. Also note that the arguments of
this method would be same as that of the constructors and the return type would be void. This
init mechanism was created in Java to ensure that memory allocated is initialized properly
and any bugs should not arise due to garbage values in memory as in the case of other
languages like C and C++.
Let us take an example to illustrate the usage of constructor. L3 of Example 4.7 defines an
explicit default constructor that does not accept any argument but initializes the instance variables
to the specified values.
Output
D:\javabook\programs\chap 4>java Room
The volume of the room is 1680.0
The volume of the room is 1680.0
Explanation
L3 A constructor with the name of the class, Room, end of the method with the help of return keyword.
is defined. It should be noted that the constructor Please note that if a method specifies a return type
declaration is very much like a method declaration then it must return a value of that type using a return
but does not have a return type. keyword.
L4 & 6 Various instance variables are initialized L14 & 15 Two objects, r1 and r2, are created
with certain values. or instantiated using new operator. As soon as
L9 & 12 Instance method volComp()is defined this is done, the constructor Room()on L3 is called
and implemented for calculating and returning the automatically, which in turn initializes all the
volume of the room to the caller. The return type of variables that it is defined for. The default constructor
the method is specified as double. Return values will not be provided by Java because we have defined
are expected from methods when you would like to a constructor for our class. So when we create object
perform more operations on the returned values or our defined constructors will be invoked which would
want to pass them further. Here volume is returned initialize the objects. Obviously, in the background
specifically to denote how values are returned from this task will be achieved using <init> method.
methods. The volume calculated is stored in the L16 & 17 The volume of both the objects of the
instance variable volume, which is returned at the room class is printed. Note that, volComp()is called
Classes and Objects 93
by their respective objects, in order to return the value for the volume calculation. It is so because both the
of volume. Here, the volume for both the instances objects are initialized with the same set of values,
will be same, because both the objects call the method while being instantiated by the new operator.
volComp(), which uses the same set of dimensions
Note Instance method, volComp(), directly uses the instance variable: length, breadth, height,
and volume. A very common mistake that many novice OOP programmers make, is to pass
arguments to methods, multiply them and return the result. Although this might produce
correct result but would not be correct OOPs approach as you are working with local variable
rather than instance variables. Suppose if you create the volComp() method as shown below:
double volComp (double length, double breadth, double height){
volume = length * breadth * height;
return volume;
}
In this case, you are using local variables for calculating volume. The purpose is to calculate
the volume of the room whose dimensions are already encapsulated in the Room object. So
for that we need to access the instance variables as shown in Example 4.7 and not local vari-
ables. The usage of local variables defeats our purpose.
r1.length = 30
and then invoke the method volComp for calculating volume of the Room. But there should be a
mechanism for specifying different values of instance variables for different objects of a class,
as soon as the object is created. For example, if different dimensions can be specified for a Room
then each Room will have its own volume. For this, the instance variables should be assigned a
different set of values for different objects of the class. Hence we need to create a parameterized
constructor that accepts arguments to initialize the instance variables with the arguments. Let us
take an example to see how parameterized constructors can be used.
Explanation
Here we will explain only the relevant lines of the L14 Second instance r2 of class Room2 is created.
above example. Another set of values for the parameters is passed
L3–7 The constructor Room2 is defined, which has to the constructor in L3, with the invocation of the
three arguments: l, b, and h, of type double. These explicit constructor.
are assigned to instance variables, length, breadth
L15 & 16 The volumes for both the instances of
and height, respectively.
Room are printed. You can see in the output that both
L13 Instance r1 of class Room2 is created. The values
for the parameters are passed to the constructor in L3, the volumes are different, because different sets of
with the invocation of the explicit constructor. parameters are used to calculate the volumes.
Note In the above program, we have created a parameterized constructor. If we create an object
as shown below:
Room2 r3 = new Room2();
Instead of
Room2 r1 = new Room2(14, 12, 10);
The compiler will not compile this program. The obvious reason is that we have created a
parameterized constructor in this class and we are trying to call the default constructor. Java states
that if you provide a constructor for your class, the (automatically created) default constructor
will not be provided to your class. And here we are invoking a no argument constructor which
is neither explicitly created in our class nor will it be implicitly provided by Java.
4.6.2 Constructor Overloading
Just like methods, constructors can also be overloaded. Constructors are declared just as we
declare methods, except that the constructors don’t have any return type. Constructors for a class
have the same name as that of the class, but they can have different signatures, i.e., different
types of arguments or different number of arguments.
Such constructors can be termed as overloaded constructors. Constructors are differentiated
on the basis of arguments passed to them.
In the example below, we have used two overloaded constructors, each having a different
number of arguments, so that the JVM can differentiate between the various constructors.
Classes and Objects 95
Here we have two different classes, Rectangle and ConstOverloading. The Rectangle class
has two constructors, both with the same name but different signatures. Each constructor is used
for the initialization of instance variables.
Explanation
L3–5 Explicit default constructor is defined for the Rectangle class, which accepts two integer
the Rectangle class. This constructor initializes the values for initializing two instance variables.
instance variables with integer values. L11–14 An instance method area() is defined to
L7–10 An overloaded constructor is defined for return the area of the rectangel.
Example 4.10 shows the second class ConstOverloading, which has the main()method inside it. While
creating different instances of the Rectangle class, different overloaded constructors of the class are in-
voked with different number of parameters passed through the constructors. The values passed through
the various constructors are used to initialize different instances of the Rectangle class.
Explanation
L3 The Rectangle object is created and the default L5 Another Rectangle object is created and the
constructor (i.e., no argument constructor, explicitly parameterized constructor is invoked. If there are a
provided) is called. number of parameterized constructors in the class,
96 Programming in Java
then which constructor will be invoked will depend integer arguments are passed, so a constructor is
upon the exact matching of the number of argument searched which accepts two integer arguments which
and the type of arguments in order. In our case, two is already defined in L7, Example 4.9.
The above example shows a case of overloaded constructors with differing number of arguments.
Another case would be where different type of arguments can also be passed into the overloaded
constructors.
4.7.2 Finalization
Before an object gets garbage collected, the garbage collector gives the object an opportunity to clean
up itself through a call to the object’s finalize() method. This process is known as finalization.
All occupied resources (sockets, files, etc.) can be freed in this method. The finalize()
method is a member function of the predefined java.lang.Object class. A class must override
the finalize()method to perform any clean up if required by the object.
4.7.3 Advantages and Disadvantages
There are many advantages of using garbage collection apart from freeing the programmer from
worrying about deallocation of memory. It also helps in ensuring integrity of programs. There
is no way by which Java programmers can knowingly or unknowingly free memory incorrectly.
The disadvantage of garbage collection is the overhead to keep track of which objects are being
referenced by the executing program and which are not being referenced. The overhead is also
incurred on finalization and freeing memory of the unreferenced objects. These activities will
incur more CPU time than would have been incurred if the programmers would have explicitly
deallocated memory.
Note No variable can have an undefined value. Instance or class variables are implicitly initialized
to their respective default values, whereas local variables are not implicitly initialized to a
default value and must be explicitly initialized in Java.
In effect, what we are really doing is that this instance variable, var, no matter how many
objects are created, should always reside in the same memory location, regardless of the object.
This then simulates like a ‘global variable.’ We usually declare a variable as final and static as
well, since it makes sense to have only one instance of a constant. It is worthwhile to note that
people refer to static instance variables as ‘class variables.’ Before proceeding further, let us
take an example to depict how static variables are declared.
All instances of the class share the static variables of the class. A class variable can be
accessed directly with the class name, without the need to create an instance.
Without the ‘static’ keyword, it is called an ‘instance variable’ and each instance of the class
has its own copy of the variable.
//setter methods
L4 void setX (int n) {x = n;}
L5 void setY (int n) {y = n;}
//getter methods
L6 int getX() { return x;}
L7 int getY() { return y;}
}
We could have another class Test2 having the main()function where the use of static variable
declared in the class Test1 can be shown:
Classes and Objects 99
Output
Instance variable of object t1 : 9
Instance variable of object t2 : 10
Value of y accessed through class Name: 0
Changed value of y accessed through class Name: 7
Value of y accessed through object t2: 8
Explanation
L7 Output printed is 9, i.e., the instance variable is L11 Output printed is 7.
printed with the help of the object. L12 Instance method setY() is invoked using the
L8 Output printed is 10, i.e., another instance object t1, where the value of static variable, y (i.e., 7),
variable is printed with the help of the object. accessed through class name Test1 is incremented
L9 Output printed is 0. It is important to note that by 1 and passed as argument.
here, we need not have an object for class Test 1 to L13 Output printed is 8, as t2.getY()returns the
access the static variable of Test 1 (refer to L3 of value set by t1.setY()in L12. This is done to show
class Test 1). that the value of y is being shared by all the objects
L10 Static variable is assigned a value 7 using the
of the class, as it is a static variable.
class name itself.
class Test {
int x = 3;
static int returnX(){
return x;
}
public static void main(String args[])
{
System.out.println(returnX()); // static method invoked directly
}}
The above class Area has a class variable declared in L2 and a static method, computeArea()
with two arguments in L3.
Output
12
Explanation
L3 The method computeArea() of class Area this method has been declared as static in L3 of class
is being called without referencing it through any Area. The return value of the method is printed using
object/ instance. Instead, it can be invoked using that System.out.println().
class name only, which it belongs to. It is so because
The static executes as soon as the class loads even before the JVM executes the main method.
There can be any number of static blocks within the class and they will be executed in the
order in which they have appeared in the source code.
Note In case the static keyword is dropped from this block, it becomes an instance initialization
block and all code placed inside this block is placed inside the constructors before the source
code written in the constructor by the Java compiler. Actually the code of instance initialization
block is placed in the <init> method, which is created for every constructor by the compiler,
before the source code mentioned by programmer in the constructor.
Let us take an example to see how static block, instance initialization block, instance variable
initializes and constructor executes. The program clearly shows that static block executes even
before main method. This program also includes an instance variable instance initialization
blocks with a constructor. Both the instance block and the constructor code gets invoked as
soon as the object of the class is created. How? As already stated, the code of initializer instance
initialization block is placed within the constructor, before the constructors own code, by Java
compiler. This is evident by seeing the output, the print statement in the instance initialization
block executes before statement mentioned in the constructor. The static block also shows
declaration of a variable which is local to the block.
Example 4.15 Static Initialization Block, Instance Initialization Block and Constructor
class StaticBlockDemo
{
102 Programming in Java
StaticBlockDemo()
{
System.out.println(“Within Constructor”);
System.out.println(“Instance variable printed using constructor: “+x);
}
public static void main(String[] args)
{
System.out.println(“In main”);
StaticBlockDemo st = new StaticBlockDemo(100);
System.out.println(“------------------------------------------”);
StaticBlockDemo st1 = new StaticBlockDemo();
}
}
Classes and Objects 103
Output
D:\javaprg>java StaticBlockDemo
In static block
In main
In Instance Initialization block
Printing Instance variable Initializer value through Block: 10
Within Constructor
Instance variable printed using constructor: 10
Instance variable initialized using constructor: 100
------------------------------------------
In Instance Initialization block
Printing Instance variable Initializer value through Block: 10
Within Constructor
Instance variable printed using constructor: 10
Here, the use of this does not do anything differently than the earlier code in Example 4.8. It
is perfectly legitimate to use it in the way it has been done. Inside Room2, this will always refer
to the current object, of Room2. The obvious question that would arise is when and why should
we use this in an application?
The exact purpose of this is to remove ambiguity between local and instance variables. In
Example 4.8, we had three instance variables declared in L2. Look carefully. The formal (local
variables) parameters of Room() in L3 have different names, (l, b, and h) from the instance
variables (length, breadth, and height).The values of these formal parameters are passed to the
instance variables. If a like names are provided for both the parameters (formal and instance
variables) then the instance variables will be hidden (or shadowed) by the local variables.
Suppose the formal parameters had been named as length, breadth, and height, which are also
the names of the instance variables used in the class, then it is difficult to distinguish between
local variable and instance variable as shown below:
104 Programming in Java
It is an ambiguous situation for the JVM as it does not understand what has to be done;
whether instance variables have to be initialized with formal parameters or vice versa. The
problem arises because JVM cannot clearly distinguish which is a local variable and which is
an instance variable. In this case the local variables shadow or hide the instance variables. If
you try to access or print the length variables in the constructor Room2, the local variable length
will be printed and not the instance variable: length, this allows you to solve the problem of
a variable’s scope, because it lets you refer to the object directly. this keyword makes a clear
cut distinction between local and instance variable. this.length refers to the length instance
variable of the current object. The above block of code can be re-written as follows.
Room2 (double length, double breadth, double height){
this.length = length;
this.breadth = breadth;
this.height = height;
}
In the above code it is clearly evident local variable length value should be assigned to the
instance variable length of the current object and soon for other variables.
Hence, the names of instance variables and the formal parameters can be kept similar because
this has made it possible for the JVM to differentiate between instance and local variables.
Still, one can argue that a programmer can very well use different variable names for instance
and local variables.
Constructor Chaining It means a constructor can be called from another constructor. Let us
revisit Example 4.8.
/* First Constructor */
Room2( )
{
// constructor chained
this(14,12,10);
}
/* Second Constructor */
Room2 (double l, double b, double h)
{
length = l;
breadth = b;
height = h;
}
In the above code, two constructors have been created: one without arguments and another with
three arguments. In the first constructor, we have used this keyword to call the second constructor
and passed the required arguments in the call to second constructor.
Classes and Objects 105
the first constructor will be invoked which is chained to the second constructor.
4.10 ARRAYS
Till now, we have discussed how to declare variables of a particular data type, which can store
a single value of that data type. The allocation of memory space, when a variable is declared,
cannot further be sub-divided to store more than one value. There are situations where we might
wish to store a group of similar type of values in a variable. It can be achieved by a special kind
of data structure known as arrays.
An array is a memory space allocated that can store multiple values of same data type in contiguous
locations. This memory space, which can be perceived to have many logical contiguous locations,
can be accessed with a common name. For example, we can define an array as ‘marks’ to represent
a set of marks of a group of students. Now the next question is how to access a particular value from
a particular location? A specific element in an array is accessed by the use of a subscript or an index
used inside the brackets, along with the name of the array. For example, marks[5] would store the
marks of the fifth student. While the complete set of values is called an array, the individual values
are known as elements. Arrays can be two types:
one dimensional array
multi-dimensional array
4.10.1 One-dimensional Arrays
In a one-dimensional array, a single subscript or index is used, where each index value refers to
an individual array element. The indexation will start from 0 and will go up to n –1, i.e., the first
value of the array will have an index of 0 and the last value will have an index of n –1, where n
is the number of elements in the array. So, if an array named marks has been declared to store
the marks of five students, the computer reserves five contiguous locations in the memory, as
shown in Fig. 4.4.
Suppose, the five marks to be assigned to each array element are 60, 58, 50, 78, and 89. It
will be done as follows:
Marks[0] = 60;
Marks[1] = 58;
Marks[2] = 50;
Marks[3] = 78;
Marks[4] = 89;
106 Programming in Java
60 58 50 78 89
Creation of Array
Creating an array, similar to an object creation, can inherently involve three steps:
Declaring an array
Creating memory locations
Initializing/assigning values to an array
Declaring an Array Declaring an array is same as declaring a normal variable except that you
must use a set of square brackets with the variable type. There can be two ways in which an
array can be declared.
type arrayname[];
type[] arrayname;
So the above marks array having elements of integer type can be declared either as
int marks[];
or
int[] marks;
Creating Memory Locations An array is more complex than a normal variable, so we have to
assign memory to the array when we declare it. You assign memory to an array by specifying
its size. Interestingly, our same old new operator helps in doing the job, just as shown below:
Arrayname = new type [size];
So, allocating space and size for the array named as marks can be done as,
marks = new int[5];
Both (declaration of array and creation of memory location), help in the creation of an array.
These can be combined as one statement, for example,
type arrayname[] = new type[];
or
type[] arrayname = new type[];
It is interesting to know what the JVM actually does while executing the above syntax.
During the declaration phase, int marks[];
marks Null
Figure 4.6 shows the marks array after memory is allocated to the array on execution of the
following statement:
marks = new int[5];
Here is an example to show how to create an array that has 5 marks of integer type.
Classes and Objects 107
We have just discussed how to create a list of parameters to be assigned in an array. Example
4.16 shows how to set the values for an array of 5 marks (Fig. 4.6).
Arrays can alternately be assigned values or initialized in the same way as the variables, i.e.,
at the time of declaration itself. The syntax for the same can be,
type arrayname[] = {list of values};
will print the number of elements in the marks array, i.e., 5. Example 4.18 shows how to use a
for loop to set all the values of an array to 0 which, you will see, is much easier than setting all
the values to 0 separately.
Explanation
L3 Creates an array marks, having five locations and iterates by 1 up to the last location of the array,
to store five elements. which is returned by marks.length.
L4 i signifies the subscript of the array, which is Various operations can also be performed on the
values of an array, which can again be assigned to the
always an integer type. The for loop starts with the array. For example, the following code increments
first location of the array, it stands at the 0th subscript all the marks in the class by 5.
To access a particular value in the array, we use the name of the array, followed by an open bracket,
followed by an expression that gives the index, followed by a close bracket. For example, here
is a simple code to print all the marks in the array of marks declared above.
Sorting an Array Let us take an example where we apply all the concepts of array that we
have learnt until now. If we have been given a set of marks and we have to sort the marks in
ascending order.
Output
c:\javabook\programs\chap4>java SortArray
The list of marks is: 3 5 1 2 4
List of marks sorted in descending order is: 5 4 3 2 1
Explanation
L1 Class SortArray declared. L7–9 for loop is used to print the values of the
L2 main()declared and its body starts with left {. original list, i.e., marks.
L3 Array named marks created with initialized L10 Defines for loop which iterates from 0 to
values. length of the array –1.
L4 Instance variables, temp and n declared to be L11 A nested for loop is declared which iterates
integer type. from i + 1 to n –1. L12–16 are part of the inner for
L5 Length of the array is stored in n. loop, and these statements are executed for each
110 Programming in Java
value of i from 0 to n –1 and j from 1 to n–1 as to marks at marks at ith index (L15) and marks in
shown in Fig. 4.7 below. temporary variable are assigned to marks at the jth
L12–16 In the first iteration, value of i is 0 and j position. Thus the value of jth position is swapped
is 1. The marks at the 0th index are compared with with the value at ith position. Figure 4.7 illustrates
the marks at the first index. If marks at 0th index are how the outer and inner loops execute for each value
less than marks at the 1st index they are swapped. of i and j. It also shows when the values of the array
For swapping, a temporary variable named temp is are swapped.
created (L13). Marks at ith index (first iteration value L20–22 Display the sorted array. The array has
of i is 0) are assigned to temp (L14). The marks at been sorted in descending order.
jth (first iteration value of j is 1) index are assigned
When i = 0
j = 1 marks[0] < marks[1] Yes, so they are swapped
(3) (5) New Array is 5, 3, 1, 2, 4
j = 2 marks[0] < marks[2] No, not swapped
(5) (1) New Array is 5, 3, 1, 2, 4
j = 3 marks[0] < marks[3] No, not swapped
(5) (2) New Array is 5, 3, 1, 2, 4
j = 4 marks[0] < marks[4] No, not swapped
(5) (4) New Array is 5, 3, 1, 2, 4
When i = 1
j = 2 marks[1] < marks[2] No, not swapped
(3) (1) New Array is 5, 3, 1, 2, 4
j = 3 marks[1] < marks[3] No, not swapped
(3) (2) New Array is 5, 3, 1, 2, 4
j = 4 marks[1] < marks[4] Yes, swapped
(3) < (4) New Array is 5, 4, 1, 2, 3
When i = 2
j = 3 marks[2] < marks[3] Yes, swapped
(1) < (2) New Array is 5, 4, 2, 1, 3
j = 4 marks[2] < marks[4] Yes, swapped
(2) < (3) New Array is 5, 4, 3, 1, 2
When i = 3
j = 4 marks[3] < marks[4] Yes, swapped
(1) < (2) New Array is 5, 4, 3, 2, 1
When i = 4
j = 5 Inner for loop does not execute.
When i = 5, Outer for loop exits
Now if we want to add a second dimension in the form of roll no of the student. This is possible
only if we follow a tabular approach of storing data, as shown in Table 4.4.
You can easily notice that Table 4.3 can store only subject names and the marks obtained by
one student, while Table 4.4 can store the details of multiple students. There can be enumerable
such situations where we can use a two-dimensional structure. Java provides a solution for the
storage of such a structure in the form of two-dimensional arrays.
If you want a multidimensional array, the additional index has to be specified using another
set of square brackets. The following statements create a two-dimensional array, named as marks,
which would have 4 rows and 5 columns, as shown in Table 4.4.
Table 4.3 One-dimensional Marks Array
Subjects Marks
Physics 60
Chemistry 58
Mathematics 50
English 78
Biology 89
This is done in the same way as it has already been explained while discussing one-dimensional
arrays. The two statements, used for array creation, can be merged into one as,
int marks[][] = new int[4][5];
This statement just allocates a 4 × 5 array and assigns the reference to the array variable marks.
The first subscript inside the square bracket signifies the number of rows in the table or matrix
and the second subscript stands for the number of columns. This 4 × 5 table can store 20 values
altogether. Its values might be stored in contiguous locations in the memory, but logically, the
stored values would be treated as if they are stored in a 4 × 5 matrix. Table 4.5 shows how the
marks array is conceptually placed in the memory by the above statement.
112 Programming in Java
This declaration shows that the first two rows of a 2 × 4 matrix have been initialized by the
values shown in the list above. It can also be written as,
int marks[][] = {(2, 3, 6, 0), (9, 3, 3, 2)};
In the above declaration, subscripts need not be shown, as it is evident from the manner in
which the list of values have been presented. Here, the list of values has two different sets of
values, separated by a comma, each standing for a row.
It is important to understand how Java treats 2-D arrays. 2-D arrays are treated as 1-D array.
For example, the above declaration of 2 × 4 array will create three 1-D array. One for storing the
number of row arrays (i.e. 2) and the other two arrays will be used for storing the contents of the
rows. The size of these two arrays will be 4. As shown in Fig. 4.7, the size of row array is the
number of rows and each field in the row array points to a 1-D array that contains the column
values for the rows. So marks[0][0]will have the value 2, marks [0][1] will have 3, marks[1]
[0] with 9, and so on.
Assigning and accessing the values in a two-dimensional array is done in the same way, as was
done in a one-dimensional array. The only difference is that, here you have to take care of the
positional values of the array using two subscripts (shown in square brackets), while in a one-
dimensional array, only one subscript was used for the purpose. Table 4.5 shows the positional
values of a two-dimensional array.
(2nd array)
marks[0] 2 3 6 0
marks[1] [0] [1] [2] [3]
Row array
(1st array)
(3rd array)
9 3 3 2
[0] [1] [2] [3]
Contents of the row array
All that you need to do to create and use a 2-D array is to use two square brackets instead of
one.
Output
C:\javabook\programs\chap4>java DemoArray1
2 3 6 0
9 3 3 2
Explanation
L3–4 Shows the declaration of a 2-D integer determine the columns in a row (separate 1D array
array having two rows. The number of columns is will be created for each row). Each index in a row
not specified but the reverse declaration is illegal as array will point to a column array.
shown in L4. L6 A for loop is created. This for loop is used
L5 Shows a declaration of a 2-D array with values for iterating through the row array and that is why it
assigned to it. No number has been specified in the iterates from 0 to the length of the array m.
row and column square brackets of array m. The L7 An inner for loop is created for iterating the
rows and columns are decided on the basis of how columns in a row array. The inner for loop iterates
the values are passed to the array. m is having 2 rows from 0 to the length of the 1D array pointed by the
and 4 columns. The number of inner curly bracket individual fields in the row array. That is why the
(opening and closing) determines the number of rows loop iterates up to m[i].length.
(row array) and the number of individual values in L8 Prints the individual items of the array at all
a particular curly bracket (opening and closing) will row and column combinations.
Let us take a more complex but useful example of matrix multiplication. Two matrices are
to be multiplied, so two arrays capable of holding the same number of rows and columns as
matrices are required.
114 Programming in Java
Output
Matrix 1:
3 7
6 9
Matrix 2:
5 4
3 6
Multiplication of both matrices:
36 54
57 78
Classes and Objects 115
Like 2-D arrays, we can define any multidimensional array having n dimensions. While declaring
an n-dimensional array, n number of square brackets will be used. All the operations in any type
of multidimensional array will be similar to that of a one-dimensional or two-dimensional array.
4.10.3 Using for-each with Arrays
The enhanced for loop, i.e., for-each was introduced in Java 5 to provide a simpler way to
iterate through all the elements of an array or a collection. The format of for-each is as follows:
for (type var : arr){
// Body of loop
}
For example, we can use for-each loop to calculate the sum of elements of an array as follows:
int[] arr = {2,3,4,5,6};
int sum = 0;
for(int a : arr) // a gets successively each value in arr
{
sum += a;
}
The disadvantage of for-each approach is that it is possible to iterate in forward direction only
by single steps.
4.10.4 Passing Arrays to Methods
Arrays can be passed to methods as well. The following example shows a two-dimensional array
being passed to a method. The static method displays the contents of that array.
Output
D:\javabook\programs\chap4\PassingArray
1 2
2 3
Explanation
L1 Class declaration. L9 Prints the individual elements of the array based
L3 Declares a static method ‘show’ that accepts on the values of indexes set by the values of i and j.
an argument i.e., a two-dimensional array. L10 Marks the closure of the inner for loop.
L5 Shows a for loop that would loop from 0 to the L11 Is a simple print statement used for formatting
length of array. This for loop is basically used to the output. This will move the cursor to new line.
refer to the first dimension of the 2D array. Basically it is used to show the individual elements
L6 Marks the beginning of for loop defined in L5.
of the array on a new line.
L7 Shows another for loop that would represent
L12 Marks the closure of the outer for loop.
the second dimension. Our 2D array has only
L13 Ends the method show.
two elements as each array item. So the index for
L14 Main method declaration.
referencing any individual element would be a[0][0]
or a[0][1] for the first row of the Array. Subsequently L16 An int array is defined and initialized with
The next row items can be referenced as a [1][0] values.
and a [1][1] and so on (a [2][0], a [2][1] etc.). As is L17 Static method show is invoked and array is
evident, the second index does not go beyond 1, so passed as an argument to it. As show is a static method
we have declared a for loop, in this statement, that it can be invoked directly.
iterates for less than 2 times. L18 & 19 Ends the main method and the class.
class ReturningAnArray
{
// static method declared to return a 2D Array
static int[][] show(){
int a[][]={{1,2},{2,3}};
return a;
}
public static void main(String args[])
{
int a[][]=show(); // return value is captured in a 2D Array
for(int i=0;i<a.length;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(" " +a[i][j]);
Classes and Objects 117
}
System.out.println();
}
}
}
Output
D:\javabook\programs\chap4\ReturningAnArray
1 2
2 3
Explanation
This program is almost the same as that of previous iterate the two-dimensional array is same as that of
program. The difference is that the show method now previous program with a change i.e., now they belong
returns a two-dimensional array. The logical steps to to main method instead of show method.
Output
D:\javabook\programs\chap 4\java VarArgs
SUM = 14
SUM = 9
In this case, each of the elements in the array named args (including the elements at position
zero) is a reference to one of the command-line arguments, each of which is a string object.
Suppose, you have a Java application, called sort, that sorts the lines in a file named Sort.
text. You would invoke the Sort application as, java Sort Example.txt.
When the application is invoked, the runtime system passes the command-line arguments to
the application’s main()method via an array of strings. In the statement above, the command-line
argument passed to the Sort application contains a single string, i.e., Example.txt. This String
array is passed to the main() method and it is copied in args.
You must be wondering how many arguments you can supply through a command line. As
we have discussed in Section 4.10, the number of elements in an array can be obtained from
the length property of the array. Therefore, in the signature of main(), it is not necessary in
Java to pass a parameter specifying the number of arguments. Example 4.27 explains the use of
command-line arguments.
After compiling the program, when it is executed, you can pass the command-line arguments
as follows:
C>java Echo A B C
Classes and Objects 119
Output
A
B
C
Note that there is one space between each of the three arguments passed to the Echo application
through the command line. If you have to pass a string of characters as an argument, then you
must use quotes (" ") to mark that string. For example,
C>java Echo "A is first alphabet" "B is second" "C is third"
Output
A is first alphabet
B is second
C is third
Explanation
L2 main()is declared, with an array variable, args, the length of the array.
referring to an array of strings, passed as command line L4–5 for loop is iterated from 0 to the length of
arguments to the program. the array and the value obtained from each iteration
L3 An integer-type variable, x is declared to hold is printed in a separate line.
Local classes
Anonymous classes
Output
Compilation
D:\javabook\programs\chap 4>javac InnerClassTest.java
D:\javabook\programs\chap 4>dir
InnerClassTest.java
InnerClassTest$InnerClass.class
InnerClassTest.class
Classes and Objects 121
Execution
D:\javabook\programs\chap 4>java InnerClassTest
Within Non static Inner Class
Can Access Inner class variable 10
Can Access Outer class variables 20
Can Access Outer class static variables 30
Inner class instance accessed using this: InnerClassTest$InnerClass@f72617
Outer class referred from inner class using InnerClassTest.this:
InnerClassTest@1e5e2c3
Outerclass Instance method Called from Inner class
Outerclass static method Called from Inner class
Explanation
L1 Class declaration (outer). and therefore it has access to other parts of the outer
L2 Declares an instance variable of the outer class. But this being a special part, the outer class
class. members (e.g., methods) cannot directly access the
L3 Declares a static (class) variable of the outer inner class members. For example, the show method
class. can access the variable y of the outer class directly.
L4 Shows the declaration of inner class. L11 Similar to the previous statement. The inner
L5 An instance variable of the inner class is class can access any members of the outer enclosing
defined here. class. This line shows a print statement which prints
L6 Shows the declaration of class constants. the static variables of the outer class.
Constant in Java can be created by applying final L12 Shows the use of this keyword within inner
keyword to the variable declaration. Non-static class to refer to an instance of inner class. It can also
be verified from the output. this keyword is used as
inner classes can have static constants but not
an argument to the println method of System.out
static variables because inner classes operate within
object. The result printed on screen shows the class
the context of its enclosing (outer class) instance
of the instance (object) @ followed by a number, i.e.,
therefore allowing static variables or methods will
InnerClassTest$InnerClass@ f72617. Java internally
be contradictory as static members apply to class
uses the following notation for referring to inner classes
(or all objects of class) rather than be constrained
instance i.e., OuterclassName$InnerclassName as is
within a single object.
L7 Declares the instance method named show of evident from the output. As soon as the Java file (i.e.,
InnerClassTest.java in our case) is compiled, the
the inner class.
L8 Print statement which gets executed as and Java compiler generates two class file; one for the
when the instance method show of the inner class outer class (InnerClassTest.class) and one for the
is called. inner class (InnerClassTest$InnerClass.class)
L9 Prints the value of the instance variable of the using the above notation. This number is an unsigned
inner class. Since show is an instance method of hexadecimal representation of the hash code of the
the inner class, it can directly access the instance object. The hash code returns the internal memory
variables of the inner class address of the object in hexadecimal.
L10 Prints the value of the instance variable of L13 Outer class instance can be accessed from within
the outer class. A non-static inner class instance is inner class using this keyword as outerclassname.
closely associated with an instance of the outer class this. Please note that notation should be used from
that is reason why inner class methods can directly the method of an inner class.
access any of the members (fields or methods) of its L14 Shows outer class instance methods (on L18)
enclosing outer class. It is a part of the outer class can be called from within inner class.
122 Programming in Java
L15 This, if used, in show method of inner class would L21 Object of inner class is created within this
refer to an instance of inner class. InnerClassTest. instance method (L20) and show method of the inner
this refers to an instance of outer class. So L14 shows class is invoked. Note that an object of inner class can
another way of invoking outer class methods. This line be created only from within the instance method (L20)
is commented deliberately as it shows another way of of the outer class or through an instance of the outer
achieving the same output as in L13. class as shown in L24. Because, as already explained,
L16 Shows outer class static methods can be called every instance of a non-static inner class exists (or is
(on L19) from within inner class. encapsulated) within the outer class instance. Also
L17 Inner classes cannot have static methods note that, a single outer class instance can have many
similar to static variables. The reasons are same inner class instances associated with it.
as that of static variables that inner class instances L22 main method declaration.
operate within the context of a particular outer class L23 An object of outer class InnerClassTest is
instance. So creating static methods does not make created.
any sense which applies to all instances of the class. L24 Using the outer class instance, method
L18 Instance method of outer class has been createInnerObject (L20) of outer class is called.
defined. L25 Shows another way of creating an instance
L19 Class method of outer class has been defined. of inner class using new keyword on the outer class
L20 Another instance method named createIn- instance and invoking the method of inner class
nerObject of the outer class is created. simultaneously.
Note The static classes defined in a class are termed as static nested class and not inner classes
as inner classes do have an instance scope and static nested classes have class scope.
}
L12 static void nestedClassStaticMethod()
{
L13 System.out.println("Within Static method of Inner Class ");
L14 //outerClassInstanceMethod();
L15 outerClassStaticMethod();
}
} // static nested class ends here
Output
Compilation
D:\javabook\programs\chap 4>javac StaticNestedClassTest.java
D:\javabook\programs\chap 4>dir
StaticNestedClassTest.java
StaticNestedClassTest.class
StaticNestedClassTest$StaticNestedClass.class
Execution
D:\javabook\programs\chap 4>java StaticNestedClassTest
Accessing static variable of outer class within Static Inner Class 100
Outer Class Static method
Within Static method of Inner Class
Outer Class Static method
Explanation
L1 Outer class declaration. named StaticNestedClass.
L2 Defines the instance variable y of the outer L5 Declares an instance variable of the static
class. nested class.
L3 Defines the class variable z of the outer class. L6 Shows the declaration of static variable within
L4 Shows the declaration of the static nested class the static nested class. Static variables, unlike inner
124 Programming in Java
classes, can be created in static nested classes. invoked from within the static nested class.
L7 Declares non-static method of the nested class. L16–17 Shows the declaration of static method of
L8 Comment that states instance variables of the the outer class with a print statement within itself.
enclosing class cannot be accessed inside the static L18–19 Shows the declaration of instance method
nested class directly. However, it can be accessed by of the outer class with a print statement within itself.
creating an object of the outer class. L20 Main method begins.
L9 Prints the static variables of the outer class. L21 The object of static nested is created as shown
Static nested classes can directly access the static below:
members of its enclosing class. StaticNestedClassTest.StaticNestedClass
L10 Commented because instance methods cannot object = new
be directly invoked from a static nested class. StaticNestedClassTest.StaticNested-
Class();
L11 Invokes the static method on L16 of outer
class directly. The generic notation for creating object is
L12–15 Shows the declaration of a static method
<OuterClass.StaticNestedClassName>
in the static nested class. L14 is commented because <reference variable name> = new
instance methods of outer class cannot be called from <OuterClass.StaticNestedClassName>();
within the static nested class. L15 executes because
static method of the outer class (on L16) can be L22–23 Invokes the different methods of static nested
class using object created in previous line, L21.
Note Unlike inner classes, an instance of outer class is not needed for creating an object of static nested
class. Moreover, creating an instance of outer class does not create an instance of static nested
class. Also note that a static nested class can be private, default, protected, public, final and even
abstract. (We will discuss these keywords in detail in the chapters to follow)
Local inner classes are declared within a block of code and are visible only within that block,
just as any other method variable. These classes are declared within a function. They can use
only final (constant) local variables and parameters of the function
An anonymous inner class is a local class that has no name.
4.12.3 Why do we Create Nested Classes?
Nested classes let you turn logic into their own classes which normally you would not turn into
thus allowing even more object orientation into your programming as nested classes lets you
encapsulate logic into classes. Inner classes provide a structured hierarchy.
Inner member classes and anonymous classes allow callbacks to be defined conveniently.
Callback allows an object to call back the originating object at a later point in time. Nested
classes are very effective in implementing event handling in Java.
Another advantage of nested classes would be to group classes that would be required at one
place only. If you are certain that a class will be useful to only one class then it is better to embed
a class into another.
The obvious advantages would be ease of readability and ease of maintaining the code.
complex number? A complex number is a number that can be represented in the form a + bi,
where a and b are real numbers and i is the imaginary part. In the expression a + bi, a is the real
part and b is the imaginary part of the complex number. Complex numbers are used in situations
where some part is predictable (real) and some part is unpredictable (imaginary – to be assumed).
Complex numbers are used in a variety of areas like electrical analysis, stress analysis of bridges
and buildings, electronics etc. We will create a program to add and subtract two complex numbers.
The further task of multiplying two complex numbers is left as an assignment to you.
L23 imaginary=c1.imaginary+c2.imaginary;
}
L24 void subtract(Complex c1,Complex c2)
{
L25 real=c1.real-c2.real;
L26 imaginary=c1.imaginary-c2.imaginary;
}
Output
D:\javabook\programs\chap 4>java Complex 1 2 3 4
First complex number is = 1+2i
Second complex number is = 3+4i
Addition of two complex numbers = 4+6i
Subtraction of two complex numbers = -2-2i
Classes and Objects 127
Explanation
L1 Class declaration. complex number objects. Not only variables, object
L2 Shows two integer instance variables have been references can also be passed as arguments to
defined A complex number comprises of two parts: methods. For adding two complex numbers, we need
real and imaginary. So a complex number object to add the real parts of these two numbers separately
should have two instance variables. and imaginary parts separately and encapsulate the
L3 A no-argument constructor is created to resultant real and imaginary parts in a complex
initializes these variables. This can be termed as annumber object because the result of addition of two
explicit default constructor. complex numbers will also be a complex number.
L4 & 5 Instance variables are initialled to zero. The two complex numbers to be added are passed
L6 The constructor is overloaded to accept different as arguments to the add method. The add method is
values for real and imaginary part of a complex invoked using a third complex number object (L47),
number. If the previous constructor is used while which will store the resultant real and imaginary part
creating objects, then real and imaginary part will after addition.
have a value of 0. If this constructor is used duringL22 Real part of both the complex numbers objects
object creation, then objects can pass on different are accessed, added and stored in real part of the
values as argument to the constructors which can object which invoked the add method. The complex
be assigned to instance variables. So every complex number object that invoked add method will also have
number can have different real and imaginary values. real and imaginary instance variables.
L7 this keyword is used to differentiate between L23 Imaginary part of both the complex numbers
objects are accessed, added and stored in imaginary
instance variable and local variable as both variables
bear the same name and clearly specify that value of part of the object which invoked the add method.
the argument (local variable) has to be assigned to L24–26 We need to subtract two complex numbers.
instance variable. Instance method subtract is created which accepts
L8 Same as previous statement. two complex number objects. The two complex
L9–11 Defines the setter method for the instance numbers to be subtracted are passed as arguments
variable: real. As the name suggest, these methods to the subtract method. The subtract method is
are used to set the value of the instance variable: invoked using a third complex number object (L50),
real and hence the name setReal. The purpose which will store the resultant real and imaginary part
of setter method is to set the values. So the setter after subtraction.
methods accept an argument which is assigned to the L27–31 Display method is created to display the
complex numbers in the format a+bi.
instance variable. Basically setter methods (or getter
methods) are created for depicting clean structured L32 Main method declaration.
programming and these are basic fundamental used L35–39 Command line arguments are used to
in Java Beans or component architecture. These capture integer real and imaginary parts of two
methods are also very useful while working with IDE. complex numbers. These numbers will be captured
L12–15 Defines the getter method for the instance in the String array argument of the main method.
variable: real. As the name suggests, these method The numbers entered through command line will
are used to return the value of the instance variable:
become strings. These numbers have to be added/
real and hence the name getReal. subtracted so they have to be converted to integers
L16–18 Setter method for imaginary part has been and hence we use the predefined static method of
defined. Integer class as shown:
L19–20 Getter method for imaginary part has been
Integer.parseInt(args[0])
defined.
L21 We need to add two complex numbers. L40–42 Three complex number objects (c1, c2, and
Instance method, add is created which accepts two d) are created. We need to add/subtract two complex
128 Programming in Java
numbers so two objects (c1 and c2) of Complex class method can access the instance variable of c1 directly
are created so that add and subtract operations can be and display the real and imaginary parts of c1.
applied on them. The third object is used to invoke L46 The display method is called to display the
the instance method add and subtract and store the second complex number.
result within itself. L47 The add method is invoked through the third
L44 The display method is called through c1 to object d and c1 and c2 are passed to this method.
display the first complex number. Complex numbers L48–49 Statements display the object d.
have to be displayed in their format: a+bi. As the L50–52 The subtract method is invoked similar
display method is invoked through c1, the display to the add method and later on the result is displayed.
Note A common mistake that is committed by many students is that they pass two real and two imaginary
integer values to the add method, add the real and imaginary values differently and print them.
void add(int real1, int imaginary1, int real2, int imaginary2)
{
int real=real1+real2;
int imaginary=imaginary1+imaginary2;
System.out.println(real+"i"+imaginary);
}
The answer may be correct but the approach is wrong. We have to add two complex numbers
and not two integers. So for adding two complex numbers, complex number objects have to
be passed to the add method.
SUMMARY
In this chapter, we have discussed many fundamental A special type of variable whose value remains the
principles of the object-oriented model, used while same across all the objects of a class is known as
implementing Java constructs. We discussed how class or static variable. Likewise, a method can also be
classes and their objects can be created in Java. We declared as static, which sticks to a particular location
have also seen how these objects are used in a Java in the memory no matter how many times it is called
program and what these are actually made of. from multiple objects. Both static variables and static
A class provides a sort of template or blueprint methods can be called directly from anywhere inside
for an object. An object is a software bundle that a class, without or with specifying any object name.
encapsulates variables and methods operating on In Java, the objects are automatically freed after
those variables. A Java object is defined as an instance their use. The garbage collector periodically frees the
of a class. A class can have many instances of objects, memory used by objects that are no longer needed.
each having its own copy of variables and methods.
All resources held by the object can be also be freed
The variables declared inside a class (but outside a
explicitly through the finalize() method. A class must
method) are termed as instance variables. Attributes
override the finalize() method in order to perform
of a class are defined by instance variables, while its
any clean up required by the object.
behavior is defined by methods.
Methods in Java, just like C++, can be overloaded,
We have discussed the use of methods in depth.
where different methods can have the same name
These methods declared as part of one object can be
but different signatures. This concept of method
invoked or called from another object. The methods
or variables belonging to a particular class can be overloading will come into play , when there is a need
accessed by specifying the name of the object to which to perform same kind of functions on different input
they belong to. parameters. In Java, when a value is passed into a
Classes and Objects 129
method invocation as an argument, it is passed by arrays is used to store a set of values of the same
value. A special type of method having the same name data type. Command line arguments were also dis-
as the class is used to initialize object values. These cussed and practical examples were undertaken to
are known as constructors. Like ordinary methods, show how user input can be passed to the program.
these constructors too can be overloaded. A very interesting concept of Nested classes along
A variable can hold only a single value of a particu- with different types has been discussed in this chapter.
lar data type. An important data structure known as Nested classes are classes within classes.
EXERCISES
Objective Questions
1. Given a one-dimensional array arr, what is the args[]){
correct way of getting its number of elements? if(args.length> 0)
(a) arr.length (b) arr.length – 1 System.out.println(args.
(c) arr.size (d) arr.size – 1 length);
2. Which of these statements are legal? }
(a) intarr[][] = new int[5][5];
(b) int []arr[] = new int[5][5]; }
(c) int[][] arr = new int[5][5]; (a) The program compiles and runs but does not
(d) int[] arr = new int[5][]; print anything
3. Which of the following statements are legal (b) The program compiles and runs and prints 0
declarations and definitions of a method? (c) The program compiles and runs and prints 1
(a) void method() {} (d) The program compiles and runs and prints 2
(b) void method(void) {}; 6. What is the output when you try to compile and
(c) method() {}; run the following?
(d) method(void) {}; class Demo
4. What is the outcome of compiling and running {
void Demo()
the following class?
{
class Demo {
System.out.println("In Demo");
public static void main(){ }
System.out.println("Demo"); public static void main(String
} args[])
} {
(a) The program does not compile as there is Demo d=new Demo();
no main method defined }
(b) The program compiles and runs generating }
an output of “test” (a) Compile time error: Illegal Constuctor
(c) The program compiles and runs but does not declaration
generate any output (b) Run Time error
(d) The program compiles but does not run (c) Compiles and prints “ In Demo”
5. What happens when the following program is (d) None of the above
compiled and executed with the command 7. What is the output when you try to compile and
-java Demo. run the following?
class Demo{ class Demo
public static void main(String {
130 Programming in Java
Review Questions
1. What are classes and objects? 6. What are command-line arguments and how are
2. What is method overloading? Explain with the they used?
help of a program. 7. What are inner classes? What is the need for
3. What are constructors used for? Can constructors creating an inner class?
be overloaded? Write a program in support of
8. Explain static keyword with all its usages.
your answer.
9. What are the possible ways in which multiple
4. Explain the difference between instance variables
and class variables. values can be returned from a method?
5. Explain the keyword this with the help of a 10. Explain static nested classes with help of a
program. program.
Programming Exercises
1. Modify Example 4.2(a) to accept instance 2. Overload the constructor in the previous example
variable values using a constructor with no and then try to execute it.
arguments and execute it.
Classes and Objects 131
3. Make use of this keyword in the previous defaults to 0. It has methods that calculate the
example to show its usages. perimeter and area of the rectangle. It has set
4. Write a program to implement Money class. This and get methods for both length and width. The
class should have fields for initializing a rupee set method should verify that length and width
and paisa value. The paisa value will be in the are floating-point numbers larger than 0.0 and
range from 0–99 with the paisa being the same less than 20.0.
sign as that of rupees. The class should have all 7. Modify the Circle class in Example 4.5 to
reasonable constructors, addition and subtraction calculate:
methods, and a main() method that provides a (a) circleCircumference() –compute the
thorough test of all the methods in the class. circumference of a circle
(b) arcLength()– compute the length of the arc
5. Modify the complex number practical problem to
for a given angle
multiply two complex numbers, and return the
result. Within the main() method of the class named
Circle, create an object of the class Circle.
6. Create a class Rectangle. The class has two
Compute Circle’s circumference when the radius
attributes, length and width, each of which
is 10 and arc length when the angle is 45.
contains an ignition system and starter motor (Fig. 5.2). Basically it is different from inheritance
in the sense that there exists a whole-part relationship in aggregation, car being the whole and
engine being its part.
Note The test for inheritance is that there exists an ‘is-a-kind-of-relationship’ among classes. For
example, Manager is a kind of Employee. The test for aggregation is that there exists an ‘is-
a-part-of ’ relationship among classes.
Multilevel inheritance
Multiple inheritance
Hierarchical inheritance
Hybrid inheritance
Single Inheritance In single inheritance, classes have only one base class. Consider the
relationship shown in Fig. 5.3.
Multilevel Inheritance As shown in Fig. 5.4, C not only inherits from its immediate superclass,
i.e., B, but also from B’s superclass, A. Thus, class C will have all the attributes and behavior
that A and B possesses in addition to its own. There is no limit to this chain of inheritance
(known as multilevel inheritance) but getting down deeper to four or five levels makes the code
excessively complex.
Car A A
Engine B
Fig. 5.2 Aggregation Fig. 5.3 Single Inheritance Fig. 5.4 Multilevel Inheritance
134 Programming in Java
Multiple Inheritance In multiple inheritance, a class can inherit from more than one unrelated
class, as shown in Fig. 5.5. Class C inherits from both A and B.
A B
Note Java does not support multiple inheritance amongst classes. It can still be achieved with the
help of Interfaces.
Hierarchical Inheritance In hierarchical inheritance, more than one class can inherit from a
single class, as shown in Fig. 5.6. Class C inherits from both A and B.
Hybrid Inheritance Hybrid inheritance is any combination of the above defined inheritances
as shown in Fig. 5.7.
A A
B C
C D
Car Bike
Fig. 5.8 UML Notation for Car and Bike Class Along with their Parent Class MotorVehicle
Now let us frame classes for the above diagram and see how inheritance is actually done in
Java. First of all, let us frame the parent class MotorVehicle, shown in Example 5.1.
Explanation
L1 Class MotorVehicle has been declared. initialize the instance variables declared in L2 to L5.
L2–5 Instance variable maxSpeed (of type int), L8–11 The instance variables declared in L2 to L5
modelName (of type String), modelYear (of type int) are being initialized with the arguments passed in the
and numberOfPassangers (of type int) are declared constructor. The keyword this has been used, as
in these lines. the name of both the instance variable and the local
L6 Default constructor. variable (arguments in the constructor declaration)
L7 Parameterized constructor declaration to are same.
Now let us frame the subclasses, as shown in Fig. 5.8. The example below shows one of the
subclasses, i.e., Bike.
The subclass Bike will have all the features that its parent class possesses. In addition to that,
it can have its own features, as shown in Example 5.2.
}
L6 public static void main(String args[]) {
L7 Bike b = new Bike ();
}}
Explanation
L1 Usage of extends keyword to show inheritance. L6 main() method.
L2 and 3 Declaration of two boolean variables: L7 Bike object is created and the default constructor
kickStart and buttonStart. of the parent class is called first of all and after that,
L4 Default constructor. the subclass constructor is called because the parent
L5 Overloaded constructor. needs to be initialized before the child.
Output
The value of i is: 24
138 Programming in Java
Explanation
L1 Class declaration. This is actually what inheritance is all about. Objects
L2 Instance variable declaration. of the subclass need not define their own definition
L3 Method declaration with an integer argument of data and methods which are generic in nature. The
passed to it. generic behavior is left for the super classes.
L4 Instance variable being assigned with the value L8 Print statement.
of the arguments. L9 main()method.
L5 Subclass declaration. L10 Object of the subclass B is created.
L6 Method is overridden, as the name and signature L11 When we create an instance of class B, an
of the method match. invocation of the method doOverride() will result
L7 The variable i is being initialized with a value in a call to the doOverride() code in class B rather
twice to that of the argument passed in the method than A because it is actually the instance that matters
doOverride. Also note that we have not declared
when we call any instance method and the instance
the variable i in the subclass B, it is the parent class
in this case is B.
variable i that is being referred to in the subclass.
A superclass reference variable can be assigned a subclass object. This is illustrated by the
following code:
A a1 = new B ();
/* Create an instance of class B but uses reference of type A . */
a1.doOverride();
/* Though the A type reference is used, the doOverride() method of
class B will be called. */
Note Remember when you write two or more classes in a single file, the file will be named upon
the name of the class that contains the main method. For example, if you write the complete
Example 5.3 in a notepad editor file, the file will be named as B.java.
Here we see that even though the superclass type variable a1 references the subclass object,
the subclass’s overridden method will be executed rather than the superclass’s instance method.
This is very useful when, for example, an array of the superclass type contains references to
various subclasses. The overridden method in the subclass will be called rather than the method
of the superclass.
Explanation
Considering A as the superclass of class B and C. L5 In the first iteration, the value of i is 0, so a[0]
L1 An array of superclass A is defined with a size refers to B class object, so B’ s doOverride() method
of two elements. will be executed even though the array is of the super-
L2 The first element of the array is assigned an class A, the code used for the doOverride()method
object of class B. An array of int contains integers; an will be that of the actual object that is referenced,
array of characters contains characters in its various not of the method in the base class A. The same
elements, and so on. An array of superclass A will
applies for the second iteration. The only difference
either contain objects of type A or its subclasses
with the second iteration is that the object will be of
because a superclass variable can refer to a subclass
object. So basically, it is an array of objects. class C. The reason why subclass methods are being
L3 The second element of the array contains the invoked is because these methods are overridden
object of class C. and overridden methods are dynamically binded.
L4 for loop is used to iterate through various array Dynamic Binding occurs at runtime and methods
elements. Value of i will vary from 0 to a.length are called based on the object from which they have
which is 2. been invoked.
Note Binding is the process of connecting a method call to its body. When binding is performed
before a program is executed, it is called early binding. When multiple methods with the same
name exist within a class (i.e., case of method overloading) which method will be executed
depends upon the argument (number, type or order of arguments) passed to the method. So,
this binding can be resolved by the compiler (at compile time) and hence overloaded methods
are early binded.
When a method with the same name and signature exists in superclass as well as subclass
(i.e., a case of Method overriding) which method will be executed (superclass version or
subclass version) will be determined by the type of object from which it has been called
(Example 5.3) and so it cannot be done by compiler. Objects exist at runtime, and hence late
binding is done by the JVM at runtime for resolving which overridden method will be executed.
It is also known as dynamic binding or runtime binding.
A superclass reference variable can refer to a subclass object but vice versa is not possible
because a superclass can have many subclasses and all of these subclasses can have their
additional (different) members (fields and methods) not present in the superclass and its
peer classes. Hence a variable of type subclass can expose more details and can perform
more operations than a variable of type superclass. So every superclass can refer to its
subclass object but every subclass cannot refer to its superclass object. Consider the case
of Furniture class and its subclasses Table and Chair. We can say that every table or chair
is furniture but we cannot ascertain that all furniture is table or chair, etc. Consider another
example of animal and its subclasses like elephant, tiger, dog, cat, etc. Tiger is an animal,
elephant is an animal but we cannot say that animal is a tiger or elephant because it is not
true in all cases. Let us take an example to see how fields are accessed when we refer to
subclass objects using a reference variable of superclass.
140 Programming in Java
Output
D:\javabook\programs\chap 4>java SubClass
Superclass Instance variable: 10
Superclass static variable: 20
Subclass Instance variable: 12
Subclass static variable: 25
Explanation
L1 Class declaration. This binding is made by the compiler at the compile
L2 Instance variable defined. time which checks whether the instance variable
L3 Class variable defined. belongs to class Superclass through which it is being
L4 Subclass declaration. accessed and if yes the binding is made, no matter
L5 Instance variable of the subclass has been which object the reference refers to.
declared with the same name as that of superclass L10 Same as L9. The only difference is it is for
(shadowing). class variables.
L6 Class variable of the subclass has been declared L11 A reference variable st of subclass is declared
the with same name as that of superclass (shadowing). to hold an object of subclass.
L7 Main method declaration. L12 The instance variable is printed using st
L8 A reference variable s of superclass is declared (created in L11). The value that is printed (see output)
to hold an object of subclass. will be of subclass as the reference is of subclass. As
L9 The instance variable is printed using s (created already stated, this binding is made by the compiler at
in L8). The value that is printed (see output) will the compile time which checks whether the instance
be of superclass as the reference is of superclass. variable belongs to class Subclass through which it
Inheritance 141
is being accessed and if yes, the binding is made, no L13 Same as L12. The only difference is it is for
matter which object the reference refers to. class variables.
In the following topics, we will revisit method overriding combined with some new topics.
Output
Superclass show method
Subclass show method
Explanation
As discussed earlier in Example 5.3, methods will L9 Shows calling the methods of class A through
be called on the basis of the objects from which they the object created in L8.
are called. L10 and 11 The object being used is that of class B.
L8 Shows the creation of an object of class A.
142 Programming in Java
Problem and Solution In Example 5.5, two methods (show()and overridden show()) are being
called by two different objects (A and B), instead the job can be done by one object only, i.e., by
using the keyword super. Example 5.5 can be reshaped as shown below:
Example 5.5 (b) Usage of super Keyword for Calling Parent Class Methods
L1 class ANew {
L2 void show()
{
L3 System.out.println("Superclass show method");
}
}
L4 class BNew extends ANew { // Method Overriding
L5 void show()
{
L6 super.show(); //call to show method of the super class A
L7 System.out.println("Subclass show method");
}
L8 public static void main (String args[]) {
L9 BNew s2 = new BNew();
L10 s2.show(); // call to show method of Subclass B
}}
Output
Superclass show method
Subclass show method
Explanation
L5 Method show() is defined. to show() in L5 and the statements within the
L6 Shows how super is used for calling the method are executed. L6 gets executed which is
parent class method which has been overridden in super.show() and the control passes to ANew.show
the subclass. If this line is omitted, only the subclass method. Lines of show()in Anew class are executed
method will be called; we have used super in this and the control passes back to L7, which is a print
line so that both the version (parent and subclass) of
statement. After executing the print statement (L7),
methods can be called by one object only.
the control passes back to the main method which
L9 BNew object is created.
L10 The method show()of class BNew is called has no more statements to execute, so the program
using the object created in L9. The control passes automatically terminates.
Example 5.6 Usage of super Keyword for Accessing Parent Class Variables
L1 class Super_Variable {
L2 int b = 30; //instance Variable
}
L3 class SubClass extends Super_Variable {
L4 int b = 12; // shadows the superclass variable
L5 void show()
{
L6 System.out.println("subclass class variable:" + b);
L7 System.out.println("superclass instance variable:" + super.b);
}
L8 public static void main (String args[]) {
L9 SubClass s = new SubClass();
L10 s.show(); // call to show method of Subclass B
}}
Output
subclass class variable: 12
superclass instance variable: 30
Explanation
L1 Superclass declaration Super_Variable. of subclass variable b is printed. In L7, with the help
L2 Instance variable declaration band it is assignedof super keyword, we have accessed the value of the
the value 30. superclass instance variable b and in this case, it prints
L3 Subclass declaration SubClass.
L4 Instance variable b (same name as that of super- the value of the superclass variable. If the variable
class instance variable) within the subclass definedb in L4 is not defined, then both print statements
and assigned the value 12. would have printed the same value, i.e., value of the
L5 Show () method defined within the subclass. superclass variable b. In our case, both the super and
L6 and 7 In the above example, specifically we the subclass contain the variable with the same name,
have kept the names of two instance variables in
so to differentiate between the two and to access the
the super and subclass same, i.e., b. In L6 when we
print the value of b by simply writing b, the value value of the superclass variable from the subclass, we
use the keyword super.
}}
L4 class Constructor_B extends Constructor_A {
L5 Constructor_B() {
L6 System.out.println("Constructor B");
}}
Output
Constructor A
Constructor B
Constructor C
Explanation
L1 Parent class declaration Constructor_A. of Constructor_C class results in the explicit default
L2 Default constructor of class Constructor_A. constructor of this class being called on L8. An
L4 Subclass declaration Constructor_B of the <init> method is created for every constructor for
class defined in L1. the class and this <init> includes a call to the super-
L5 Default constructor of class Constructor_B. class default (no argument) constructor, any instance
L7 Subclass declaration Constructor_C of class variable initializer provided in the class followed by
defined in L4. the code written in the constructor. So when an object
L8 Default constructor of class Constructor_C is of class Constructor_C is invoked, the superclass
declared explicitly. constructor is invoked automatically. Also its parent,
L10 main method declaration. i.e., Constructor_B needs to be initialized before
L11 An object of class Constructor_C is created the child class can be initialized and instantiated.
here. If the class does not provide any constructor, The same case applies for Constructor_B which in
the default constructor (no argument constructor) itself is inherited from Constructor_A. Therefore,
provided by Java is implicitly called when an object first of all, the constructor of class Constructor_A
of the class is created. All three classes define their gets executed, then Constructor_B and lastly,
respective no argument constructors. Object creation Constructor_C.
Example 5.7 (a) Usage of super Keyword for Calling Parent Class Constructor
L1 class Constructor_A_Revised {
L2 Constructor_A_Revised()
{
L3 System.out.println("Constructor A Revised");
}}
L4 class Constructor_B_Revised extends Constructor_A_Revised {
// this constructor is commented
/* Constructor_B_Revised() {
System.out.println("Constructor B");
Inheritance 145
}
*/
L5 Constructor_B_Revised(int a)
{
a++;
L6 System.out.println("Constructor B Revised " +a);
}}
L7 class Constructor_C_Revised extends Constructor_B_Revised {
L8 Constructor_C_Revised()
{
L9 super(11); // if omitted compile time error results
L10 System.out.println("Constructor C Revised");
}
L11 public static void main (String args[]){
L12 Constructor_C_Revised a = new Constructor_C_Revised();
}}
Output
Constructor A Revised
Constructor B Revised 12
Constructor C Revised
Explanation
(Only the changes are being explained) it with a default constructor. An implicit call to the
L5 The parameterized constructor of class parent class default constructor of Constructor_C_
Constructor_B_Revised is defined with an integer Revised results in an error, because the default
argument. (no argument) constructor is neither provided nor
L6 The integer argument is being post incremented. it will be implicitly available through Java, as a
L9 s u p e r keyword for calling constructor, parameterized constructor is provided in the class
followed by the argument to be passed to the parent
Constructor_B_Revised.
class constructor.
The solution for this is either to explicitly provide a
L12 An object of Constructor_C_Revised is
created due to which the default constructor of this default (no argument) constructor in Constructor_B_
class will be invoked. But as already explained, it is Revised (shown in comments) or use super in the
inherited, so its parent’s (i.e.,Constructor_B_Revised) constructor of the subclass Constructor_C_Revised
default constructor will be called automatically. But (as shown in L9) for making an explicit call to the
instead of the default constructor in Constructor_B_ parameterized constructor in its immediate super-
Revised, a parameterized constructor is provided. If class and in this case, the compiler will not show you
a class does not provide any constructor (default or an error. The constructor of class Constructor_A_
parameterized), it will be provided with an implicit Revised is normally called as the default constructor
default constructor automatically by Java. In case the is provided in the class.
class does provide a constructor, Java will not provide
Note It is mandatory for a super statement in a constructor to be the first statement within the
constructor. As the parent must be initialized before its child, an explicit call to the parent must
be done before any initialization within the child constructor begins.
146 Programming in Java
L8 /* void show(){
System.out.println("Subclass show method");
}*/
Output
C:\examples\> java Final_Demo_1
Superclass show method: 12
Explanation
Explanation
L1 Abstract class declared with the keyword are initialized with the arguments passed to the
abstract used before the class declaration. constructors in L4.
L2 and 3 Two string variables declared, named L7 A non-abstract method has been defined, just
name and species. like other normal methods.
L4 Parameterized constructor to initialize the L8 Print statement.
instance variable. L9 Abstract method declared. Note that this method
L5 and 6 Instance variables, name and species, does not have any body.
The abstract keyword is used for defining both abstract methods and abstract classes. Any
animal that wants to be instantiated must override the sound()method, otherwise it is impossible
to create an instance of that class. Let us take a look at the Lion subclass that inherits the Animal
class.
Output
Asiatic Lion likes to have flesh
Lions Roar! Roar!
Explanation
L1 Subclass declaration of the abstract class L7 The object of Lion class is created.
Animal. L8 The eat() method (Example 5.9(a)) of the
L2 Default constructor created for Lion class. parent class will be called with the help of the object
L3 The keyword super used to set up an explicit
created
call to the parent class constructor.
L4 It is mandatory for the subclass Lion to override in L7.
the sound() method because the sound()method has L9 The sound() method is called which has
been declared abstract by the parent class. been declared in L4.
Inheritance 149
{
L12 Shadowing s=new ShadowingTest();
// invokes the Superclass display as they are
// early binded at Compile time.
L13 s.display();
Output
D:\javabook\program\java ShadowingTest
In Static Method of Superclass
The Overridden instance Method in Subclass
In Static Method of Subclass
The Overridden instance Method in Subclass
Explanation
L1 Class declaration overridden, they are early binded. The compiler
L2–3 Declares a static method with a print creates this binding at compile time based on the type
statement within itself. of reference through which method has been invoked.
L4–5 Declares a instance method with a print As the reference is of superclass, the superclass static
statement within itself. method is invoked.
L6 Subclass (ShadowingTest) of the class, declared L14 The instance method is invoked using this
in L1, is declared. object created in L12. But as instance methods are
L7–8 Declares a static method within the subclass overridden, they are dynamically (late) binded. The
with the same name and signature as the static compiler delays this binding till runtime and JVM
method of superclass with a print statement within invokes the methods based on the type of object
the method.
through which method has been invoked. As the
L9–10 The instance method of the superclass is
object is of subclass, the subclass instance method
overridden with a print statement within it.
is invoked.
L11 main() method.
L15 An object of subclass is created. (A reference
L12 A reference variable of super (shadowing)
variable of subclass (ShadowingTest) class is declared
class is declared to hold an object of subclass
to hold an object of subclass (ShadowingTest)).
(ShadowingTest).
L13 The static method is invoked using this L16 Same as L13 (refer output).
object created in L12. But as static methods are not L17 Same as L14 (refer output).
Inheritance 151
Explanation
L1 Circle class has been defined. L7 The instance variable is differentiated from the
L2 The float instance variable radius has been local variable with the help of this keyword and
defined. initialized with the value passed as an argument to
L3 The final float instance variable PI has been the constructor.
defined (similar to , i.e., PI of mathematics) and L8 Instance method declaration getArea()with a
initialized with the value 3.141f (f for float). Why return type float.
we have created it as final will become clear in the L9 The keyword return is used to return the area
next topic. of the circle back to the caller.
L4 Default constructor of class Circle. The next step is to create a subclass Cylinder of
L5 Instance variable radius has been initialized. the Circle class. The Cylinder class will override
L6 The overloaded constructor has been declared the getArea()method of the Circle class which will
with an argument of type float, to initialize the return the surface area of a cylinder. The Cylinder
instance variable radius. class is defined in Example 5.11(b).
L5 this.height = height;
}
// overridden method returns the cylinder surface area
// Surface Area = (2r²) + (2r.height)
// where (2 r²) is the surface area of the "ends" and
//(2r.height) is the area of the "side"
// superclass method being invoked using super keyword
L6 float getArea() {
L7 return 2 * super.getArea() + 2 * PI * radius * height;
}
Output
C:\examples\chap 5>java Cylinder
The Area of Circle is: 7.0672503
The Surface Area of Cylinder is: 47.114998
Explanation
L1 Cylinder class inherits Circle class. Surface area = (2 r²) + (2 r height)
L2 Instance variable height has been defined by where (2r²) is the surface area of the “ends” and
the subclass Cylinder. (2r. height) is the area of the “side”, and r² is
L3 Parameterized constructor to initialize radius the area of the circle, and we already have created
and height. a method for calculating the area of the circle in the
L4 The keyword super is used to pass the radius parent class. For this reason, we have called the super
accepted as an argument in the subclass constructor class getArea method (reuse of code).radius has
(L3) to the Circle class, i.e., the parent constructor. already been passed in L4 using the super keyword.
It shows the reuse of code, as radius is defined only The return value from the parent class getArea()
once and being used by the subclass. method is multiplied by 2 and added to the area of
L5 The instance variable height is initialized with the sides (2 rh).
L8 main() method.
the local variable height(argument).
L9 The object of Circle class is created with a
L6 getArea()of Circle class has been overridden,
radius of 1.5f.
because the Cylinder class wanted the name of the
L10 Calling the method getArea()with the help of
method to be same as that of the superclass, i.e., Circle class object. The return value is concatenated
getArea() but perform a different function, i.e., with the string present in the println method and
return the surface area of the cylinder. printed on the screen as can be seen in the output.
L7 getArea() of the superclass has been called L11 Creation of an object of Cylinder class with
with the help of super, i.e., super.getArea() because a radius of 1.5f and height of 3.5f.
if you look at the formula for calculating the surface L12 The getArea() method is invoked with the
area of the cylinder, it says: help of Cylinder class object.
Inheritance 153
SUMMARY
The concept of inheritance is derived from real life, of the superclass. Abstract classes are used to force
wherein children inherit the good/bad qualities from the subclasses to override abstract methods and pro-
their parents and add to that their own identity and vide body and code for them. The difference between
behavior. This has been absorbed by object-oriented overriding and shadowing is also discussed with ex-
programming, wherein the properties and methods amples. Shadowed methods are binded early by the
of a parent class are inherited by the children or compiler whereas overridden methods are dynamically
subclasses. The subclasses can implement the binded by JVM.
inherited methods in a different way using method The final keyword is used to create constants and
overriding, keeping the method names and signatures disallow inheritance. The keywords abstract and
same as that of the parent class. final cannot coexist because final is used to prevent
The super keyword can be used to access the over- inheritance and abstract is used to allow subclasses
ridden methods, variables, and even the constructors to inherit it and override methods.
EXERCISES
Objective Questions
1. What will happen when you attempt to compile 3. Which is the keyword used for deriving classes?
and run the following class? (a) implements (b) extends
(c) throws (d) inherits
class Demo{
Demo(inti){ 4. What will happen when you attempt to compile
System.out.println("Demo"); and run the following class?
}} class Base{
class Inner extends Demo{ void Base()
public static void main(String {
args[]){ System.out.println("In Base");
Inner s = new Inner(); }
} Base(inti)
void Inner(){ {
System.out.println("Inner"); System.out.println("In Base: "+i);
}} }}
(a) Compilation and output of the string “Inner” (a) Compile time error
at runtime (b) Compiles but gives runtime error
(b) Compile-time error (c) Compiles and executes successfully but
(c) Compilation and no output at runtime does not show any output
(d) Compilation and output of the string “Demo”. (d) Compiles and prints “In Base”
2. Which of the following statements are true? 5. What will happen when you attempt to compile
(a) If a class has abstract methods, it must be and run the following class?
declared as abstract.
(b) If the abstract methods are not overridden, abstract class Demo
the subclass need not be declared as {
abstract. abstract void show();
(c) A final class cannot be subclassed. }
(d) All methods in an abstract class must be class Demo_1 extends Demo
declared as abstract. {
154 Programming in Java
Review Questions
1. What is inheritance? How is it different from 4. Explain final keyword with all its usages. Support
aggregation? explanation with a program.
2. What is method overriding? Explain with an 5. What is an abstract class? Can an abstract class
example. have constructors? Explain.
3. Explain super keyword with all its usages. 6. What is shadowing of instance variables?
Support explanation with a program. 7. What is the difference between shadowing and
overriding?
Inheritance 155
8. Overloaded methods are early bound whereas 9. Why subclass reference variables cannot refer
Overridden methods are late bound. Comment.? to a superclass object?
Programming Exercises
1. Define a class MotorVehicle as described (b) display() to display rate of interest with
below: new balance and full account holder
Data members: details
(a) modelName (b) modelNumber Create another subclass of the Accounts class,
(c) modelPrice i.e. CurrentAccount with the following:
Methods: Data members:
(a) display() method to display the name, (a) overdraftLimit
price, and model number. Method:
Define another class named Car that inherits the (a) display() to show overdraft limit along
class MotorVehicle and has the following: with the full account holder details
Data members: Create objects of these two classes and call their
(a) discountRate methods. Use appropriate constructors.
Methods: 3. Create a class named Employee with the
(a) display() method to display the Car following details:
name, Car model number, Car price, and Data members:
the discount rate. (a) name (b) address
(b) discount() method to compute the (c) age (d) gender
discount Create the classes MotorVehicle
Method:
and Car with suitable constructors and (a) display() to show the employee details
test it.
Create another class FullTimeEmployee that
2. Create an abstract class Accounts with the
inherits the Employee class:
following details:
Data members:
Data members: (a) salary (b) designation
(a) balance
Method:
(b) accountNumber
(a) d i s p l a y ( ) to show the salary and
(c) accountHoldersName
designation along with other employee
(d) address
details
Methods:
Create another class PartTimeEmployee that
(a) withdrawl() – abstract
inherits the Employee class:
(b) deposit() – abstract
(c) display() to show the balance of the Data members:
account number (a) workingHours (b) ratePerHour
Create a subclass of this class SavingsAccount Methods:
and add the following details: (a) calculatePay() to calculate the amount
Data members: payable
(a) rateOfInterest (b) display() to show the amount payable
along with other employee details
Methods:
Create objects of these classes and call their
(a) calculateAmount()
methods. Use appropriate constructors.
Answers to Objective Questions
1. (a) 2. (a), (c) 3. (b) 4. (b)
5. (a), either abstract is to be used with Demo_1 or override show in Demo_1 6. (a)
7. (b) and (d), use super for constructor call in Test _1 or provide default constructor in Test
8. (a) 9. (a)
10. (a), Local variable shadows instance variable in the constructors
Interfaces,
Packages, and
Enumeration
6
The greater our knowledge increases, the more our ignorance unfolds.
John F. Kennedy
understand the concept behind packages and how they are used
understand enumerations
6.1 INTERFACES
Interfaces in Java are like a contract or a protocol which the classes have to abide with. Interfaces
are basically a collection of methods which are public and abstract by default. These methods do
not have any body. The implementing objects have to override all the methods of the interface
and provide implementation for all these methods. There is no code at all associated with any
method of the interface. The best part of an interface is that a class can inherit any number of
interfaces, thus allowing multiple inheritance in Java, provided the class now has to override all
the methods of all the interfaces it inherits. Java does not support multiple inheritance among
classes, but interfaces allow Java to support this feature.
Interfaces are declared with the help of a keyword interface. Note that none of the methods
have a body. It is the responsibility of the implementing class to override the methods and provide
the implementation for these methods.
interface interfacename
{
returntype methodname(argumentlist);
...
}
class classname implements interfacename{}
Interfaces, Packages, and Enumeration 157
Example 6.1(a) shows a very simple calculator program. There are a few basic operations that
do not change for any calculator: be it a normal, scientific, or a programmable calculator. The
basic operations (add, subtract, divide, and multiply) can be squeezed out of various implementing
classes and put into an interface. Now all the implementing objects will have to keep the name
and signature of the methods exactly same as has been defined in the interface, that is why we
have created an interface and this is what we actually wanted for all the subclasses to follow.
We do not want the classes to follow their own set of rules like their own created method names
and their signatures. We wanted the classes to follow the rules set up by the interfaces and it
will be a binding upon them, but these rules will be implementation independent. That is, the
objects have to code according to their own requirement within the overridden methods. For
simplicity, we have created an interface named Calculator and four methods have been defined
in it to denote four basic operations of a calculator and these methods perform operations only
on integers. You can later on extend this program to accept different kinds of arguments such as
double, float, and byte.
Classes, while inheriting other classes, use the keyword extends; whereas while inheriting an
interface, they use the keyword implements, as shown in Example 6.1(b).
Explanation
L1 The keyword interface has been used to with the return type int that accepts two arguments
declare an interface followed by the name of the of type int.
interface and opening curly brackets to denote the L4 A method named multiply has been declared
starting of interface. with the return type int that accepts two arguments
L2 A method named add has been declared with of type int.
the return type int that accepts two arguments of L5 A method named divide has been declared
type int. with the return type int that accepts two arguments
L3 A method named subtract has been declared of type int, followed by the closing curly bracket
of the interface.
{
L9 return a / b;
}
L10 public static void main(String args[]) {
L11 Normal_Calculator c = new Normal_Calculator();
L12 System.out.println("Value after addition = "+c.add(5,2));
L13 System.out.println("Value after Subtraction = " +c.subtract(5,2));
L14 System.out.println("Value after Multiplication = " +c.multiply(5,2));
L15 System.out.println("Value after division = " +c.divide(5,2));
}}
Output
C:\javabook>java Normal_Calculator
Value after addition = 7
Value after Subtraction = 3
Value after Multiplication= 10
Value after division = 2
Explanation
L1 Class Normal_Calculator has been declared L11 An object of the class Normal_Calculator is
and it inherits the interface Calculator with the help created.
of implements keyword. L12–15 Print statements to print the result
L2 Method add has been overridden and the body of addition/subtraction/multiplication/division.
of the method has been provided. Respective methods have been called in these lines
L3 The keyword return is used to return the result with the object created in L11 like c.sum(5 ,2) .
(to the caller) of addition of two arguments passed These method calls return the result and the result is
into the add method followed by the closing curly concatenated with the strings passed as an argument
bracket. to the println method and displayed on the screen
L4–9 The methods substract , multiply , and (see output).
divide are overridden and the results are returned.
Note It is mandatory to add the access specifier public to the method declaration, otherwise the
compiler will not compile the program. As already discussed, all the methods in the interface
are public, so when the implementing classes override the methods defined in the interface,
they have to tag it as public.
Not making it public or leaving the access specifier blank (default) will reduce the privileges from
public to default, which is not allowed in overriding. Either you have to increase the privileges
or keep it intact. Widening conversion in case of overriding takes place automatically, i.e., from
default to public (lesser privileges to more privileges), but narrowing conversion is not allowed.
It is recommended to create two java files in a directory: (a) Calculator.java for defining the
interface and (b) Normal_Calculator.java for declaring the class implementing the Calculator.
java interface. The compiler upon compilation of Normal_Calculator.java will create two class
files automatically: Calculator.class and Normal_Calculator.class.
6.1.1 Variables in Interface
Just like methods in an interface (by default public and abstract; no need to tag them), variables
defined in an interface also carry a default behavior. They are implicitly public, final, and static
Interfaces, Packages, and Enumeration 159
and there is no need to explicitly declare them as public, static, and final. As they are final, they
need to be assigned a value compulsorily. Being static, they can be accessed directly with the
help of an interface name and as they are public, we can access them from anywhere. Example
6.2 shows the usage of variables in an interface.
Output
C:\javabook\>java Variable_Test
23 lie in between 0 and 100
233 does not lie in between 0 and 100
Explanation
L1 We have created an interface Limit_Test , in between the limits defined by the interface. Note
wherein we will set the upper and lower limits. that the static variable’s LOWERLIMIT and UPPERLIMIT
L2 and 3 The upper and lower limits are being have been accessed with the help of the interface
set with the help of two variables in the interface, Variable_Test.
i.e., UPPERLIMIT and LOWERLIMIT. They have to be L9 print statement to print that the argument does
not lie in between the limits defined by the interface
assigned a value, as they are implicitly final.
(same as in L7).
L4 Class Variable_Test inheriting the interface L11 An object of the class Variable_Test is
Limit_Test. created.
L5 Method findNumberWithinLimits is declared L12 and 13 Commented statements to modify
with an argument. This argument will be checked the variables: LOWERLIMIT and UPPERLIMIT. If
by the method whether it is within the limit or not. uncommented, these statements will result in a
L6 A simple if condition to check whether the compile-time error because the variables defined
argument passed in the function (L5) is greater than in an interface are final, and final variable values
the LOWERLIMIT and lesser than the UPPERLIMIT. If cannot be modified.
the condition satisfies, L7 is executed, else L9. L14 findNumberWitihinLimits() is called through
L7 print statement to print that the argument lies the object of Variable_Test, and an argument of 23
160 Programming in Java
is passed. This argument is checked by the method the object of Variable_Test, and an argument of 233
to be within the lower limit and the upper limit and is passed. This argument is checked by the method
if yes, the value is printed on screen. to be within the lower limit and the upper limit and
L15 findNumberWitihinLimits() is called through if it is not, print on screen.
Output
C:\javabook\>java InDemo
Overriden method of Interface A
Overriden method of Interface B
Explanation
L1 An interface named A has been declared. L4 Method showB() has been defined in interface B.
L2 Method showA() has been defined in interface A. L5 Class declaration shows that it inherits the
L3 Interface B is defined and we have used extends interface B.
in its declaration to indicate that the parent interface L6 Shows the overridden method showA(). Note that
of B is A. Any class that inherits B will have to while overriding, public access specifier is added.
override all the methods of interface A as well as B. L7 Shows the overridden method showB().
6.2 PACKAGES
You must have encountered situations wherein you try to organize too many files in folders/
directories and subdirectories. Similarly, if you have too many classes at your disposal, some
sort of grouping is required. Java package is one such mechanism for organizing Java classes
into groups. In fact, a package is indeed a directory for holding Java files. Java has many such
predefined packages which can be used in programs. Some of the predefined packages in Java
are applet, awt, lang, util, event, io, swing, etc. Programmers are also permitted to develop
their own packages in order to organize classes belonging to the same category or providing
similar functionality.
Note A package can be defined as a collection used for grouping a variety of classes and interfaces
based on their functionality.
It is also possible to house these Java packages, as these can be stored in compressed files called
JAR files (a JAR file or Java ARchive is used for aggregating many files into one) allowing
classes to download faster as a group rather than one at a time.
A package declaration resides at the top of a Java source file. All source files to be placed in
a package have a common package name.
162 Programming in Java
1. Remember the file must be saved with the name of the class, i.e., ClassinPackage and
placed in the directory named exactly the same as the package, i.e., packexample. The
file is compiled from within the package and the class file generated after compilation
is stored in the same directory (package). For executing the file, move up the current
directory and execute the file by mentioning the name of the package() followed by
the class name. For example, suppose the package packexample is within the directory
pack. The sequence of statements would be:
// compiling the class
L1 C:\pack\packexample\> javac ClassinPackage.java
Note Classes that reside inside a package cannot be referred by their own name alone. The
package name has to precede the name of the class of which it is a part of. All classes are
a part of some or the other package. If the keyword package is not used in any class for
mentioning the name of the package, then it becomes a part of the default/unnamed package.
In that case, we execute the classes as shown earlier.
2. This Java source file could be saved in any directory. During compilation time, you need
to specify an option of the Java compiler –d which specifies the destination where you
want to place your generated compiled files. After successful compilation, you would
see that your package has been already created in your specified path and the .class
file has been placed in that package. For executing the class, same steps need to be
followed as explained above. Let us consider, the ClassinPackage.java file is stored
in the javaeg directory.
//-d option used with javac for specifying destination c:\pack
// syntax: javac –d destination directory followed by java source file
L1 C:\javaeg\>javac –d c:\pack ClassinPackage.java
Note In both the cases, the execution takes place from the parent directory of the package where
the class files are placed as shown in L2. If we want to execute the package from any of the
directories, the classpath should be set.
%Classpath% is used to keep the existing path intact and append our new path to it. Now
L3 of both the above cases will execute.
Note Setting classpath at the DOS prompt will have to be done each time you open the DOS
prompt, as closing the prompt resets the classpath to its original value. To make the changes
permanent, edit the environment variable in the control panel.
Do not delete the existing classpath; edit the variable to append your classpath to the
environment variable.
2. Use classpath option –classpath or –cp of javac/java tools to override the user-defined
classpath and find the user-defined specific package/classes used in the Java source
files.
//syntax: javac –cp path of the directory/package used in java source file
followed by name of the java source file
C:\pack\packexample> javac –cp c:\javaeg DemoClass.java
-cp specifies that the user-defined package/classes used in DemoClass.java will be found
at c:\javaeg.
Subpackages
Subpackages can be designed in hierarchy, i.e., one package can be a part of another package.
This can be achieved by specifying multiple names of the packages at various levels of hierarchy,
separated by dots. For example,
package rootpackage.subpackage1;
As related classes can be collected in a package, related packages can also be collected in a
larger package. In the above statement, subpackage1 is designed to be a part of rootpackage. Of
course the hierarchical packages have to be stored in a hierarchical structure of directories and
subdirectories. For example, the above package subpackage1 (which is a part of rootpackage)
will be stored within the directory rootpackage.
Note The names of the packages and the directories have to be same, and the names being used
should be carefully selected.
This statement will do fine only if you import the class beforehand, i.e., at the start of the
program itself.
Now the question is how to import the classes belonging to the various packages. Classes in
a package like java.lang are automatically imported. For all other classes, you must supply an
import statement to either import a specific class
import java.awt.Rectangle;
Let us try and implement the things we have discussed till now. In the following example,
we have created two packages packexample and packexample1. The packexample has a class
ImportExmaple which will be used in the class UseImportExmaple of another package packexample1.
L1 package packexample;
L2 public class ImportExample{
L3 public int fact(int a){
L4 if(a == 1)
L5 return 1;
L6 else
L7 return a*fact(a-1);
}}
Explanation
Output
factorial of 4 is 24
Explanation
L1 Package packexample1 is defined. of the class ImportExample, i.e., packexample. If
L2 We wanted to access the class ImportExample we do not use the import statement, the compiler
in our class, so we need to import the package would complain about using ImportExample in L6.
Note You can also set the classpath using the set command at the DOS prompt or set it permanently
in the environment variables in the control panel so that you don't have to use the – cp option
again and again with the JDK tools.
Static Import
In Section 4.7, we have already discussed about the static fields and methods of a class. We
invoked the static fields and methods of a class preceding each with the class name and a dot
(.). Static import a feature was introduced in Java 5. It enables programmers to use the imported
static members as if they were declared in the class itself. The name of the class and a dot (.)
are not required to use an imported static member. The following statement shows how to use
static import:
import static pkgName.[subPkgName].ClassName.staticMemberName;
Interfaces, Packages, and Enumeration 167
pkgName is the name of the package containing the class whose static members need to
be imported.
subpkgName is the name of the subpackage to which the class belongs. The square brackets
indicate that it is optional.
ClassName is the name of the class whose static members need to imported.
staticMemberName is the name of the static field or method. But the above statement
would import only the mentioned static member of the class.
If you want to import all the static members of the class, then use the following:
import static pkgName.ClassName.*;
Note Static import imports only static members of the class. Normal import statements should be
used to import the classes used in a program.
Output
C:\javabook>java ExampleStaticImport
power of 2 raise to 2 is: 4.0
ceil(-10.2)is: -10.0
floor(-10.2)is : -11.0
ceil(10.2)is: 11.0
floor(10.2)is: 10.0
maximum of 23 and 24 is: 24
minimum of 23 and 24 is: 23
value of PI is: 3.141592653589793
Value of E is: 2.718281828459045
Explanation
L1 It is a static import declaration that imports all without preceding the field name or method names
static fields and methods of the class Math from the with the class name Math and a dot as we had used
package java.lang. import static at the top. If we use normal import
L4–12 Show a few static methods (pow, floor, instead of static import, then each function and field
ceil, min, and max) and fields PI and E being accessed has to precede with the class name.
168 Programming in Java
Fig. 6.2 UML Representation of Package and Classes to Show Access Protection
Interfaces, Packages, and Enumeration 169
This method abc() is accessible from A, B, and C, but neither from D nor E. protected methods
are also accessible outside the package, but only to the subclasses outside the package. For
example, the method xyz() is accessible from classes A, B, C, D, but not from E. This is
pictorially shown in Fig. 6.2. The method pqr() is accessible from all the classes, as it is a public
method in a public class.
Note Access of any element, such as variable and method, is also governed by its container. For
example, suppose a default access level class has a public method. This method is available
to all the classes within the package, but not outside it, as the class in which the method has
been defined is not accessible outside the package.
Note Remember we have been using String and the System class from the first example in this
book, but we have not imported any package for using these classes, as both these classes
lie in the lang package. There are various classes in the lang package and it is not possible to
discuss all the classes, but we will discuss some of the very important ones.
Output
C:\javabook\chap 6>java Demo
My Demo Object created
Explanation
L2 toString() method of the Object class has explicitly invoked with the help of an object.
been overridden with the return type as String. This L3 Returns a string "My Demo Object created".
method is basically used for returning a String that L5 Within the print statement, an object of class Demo
identifies an object. This method is automatically is created and whenever an attempt to print an object
invoked when we try to print an object. It can also be occurs, the toString() method is called automatically.
Note You may now rewrite the complex number program to add the toString() method to it instead
of display method of that class.
As we have said earlier, an instance of a wrapper contains or wraps a primitive value of the
corresponding type. Wrappers allow for situations where primitives cannot be used but their
corresponding objects are required. For example, a very useful tool is the ArrayList class (see
Chapter 10), which is a list that can grow or shrink, unlike an array. So if one wants to use an
ArrayList to hold a list of numbers, the numbers must
Table 6.4 Wrapper for Primitive Types be wrapped in an integer instance. Mostly you will
Primitive Wrapper use wrapper class methods to convert a numeric value
boolean java.lang.Boolean to a string or vice versa.
byte java.lang.Byte Table 6.4 lists the primitive data types and their
char java.lang.Character
corresponding wrapper classes.
You can easily make out that except for integer;
double java.lang.Double
the wrappers come with the same name as the
float java.lang.Float
corresponding primitive type except that the first
int java.lang.Integer
letter is capitalized. Wrappers are normal classes that
long java.lang.Long extend the Object as a superclass like all Java classes.
short java.lang.Short The wrapper constructors create class objects from
void java.lang.Void the primitive types. For example, for a double floating
point number “d”:
double a = 4.3; Double wrp = new Double(a);
Here a Double wrapper object is created by passing the double value in the Double constructor
argument. In turn, each wrapper provides a method to return the primitive value.
double r = wrp.doubleValue();
Each wrapper has a similar method to access the primitive value: intValue() for integer,
booleanValue() for boolean, and so on.
Features of Wrapper Classes Some of the sound features maintained by the wrapper classes
are as under:
All the wrapper classes except Character and Float have two constructors—one that
takes the primitive value and another that takes the String representation of the value.
Character has one constructor and float has three.
Just like strings, wrapper objects are also immutable, i.e., once a value is assigned it
cannot be changed.
Wrapper Classes: Constructors and Methods
The wrapper classes have a number of static methods for handling and manipulating primitive
data types and objects. The methods along with their usage are listed below:
Constructors Converting primitive types to wrapper objects.
Integer ValueOfInt = new Integer(v) // primitive integer to integer object
Float ValueOfFloat = new Float(x) // primitive float to float object
Double ValueOfDouble = new Double(y) // primitive double to double object
Long ValueOfLong = new Long(z) // primitive long to long object
172 Programming in Java
Here v, x, y, and z are int, float, double, and long values, respectively. There is one more way
of converting a primitive value to a wrapper, the valueOf() method, which we will discuss later.
Ordinary Methods
Converting Wrapper Objects to Primitives All the numeric wrapper classes have six non-static
methods, which can be used to convert a numeric wrapper to their respective primitive numeric
type. These methods are byteValue(), doubleValue(), floatValue(), intValue(), longValue(),
and shortValue(). Some of them are used as follows:
int v = ValueOfInt.intValue(); // Converting wrapper object to primitive integer
float x = ValueOfFloat.floatValue(); // Converting wrapper object to primitive float
long y = ValueOfLong.longValue(); // Converting wrapper object to primitive long
double z = ValueOfDouble.doubleValue(); // Converting wrapper object to primitive double
Converting Primitives to String Object The method toString() is used to convert primitive
number data types to String, as shown below:
String xyz = Integer.toString() // Converting primitive integer to String
String xyz = Float.toString() // Converting primitive float to String
String xyz = Double.toString() // Converting primitive double to String
String xyz = Long.toString() // Converting primitive long to String
Parser Methods
Converting Back from String Object to Primitives The six parser methods are parseInt,
parseDouble, parseFloat, parseLong, parseByte, and parseShort. They take a string as the
argument and convert it to the corresponding primitive. They throw a NumberFormatException
if the value of the String does not represent a proper number. Parser methods can be used as
shown below:
int v = Integer.parseInt(xyz)
// For converting String containing int values like “10” to primitive integer
long y = Long.parseLong(xyz)
// For converting String containing long values like “123456” to primitive integer
Converting Primitive Value Represented by String Object to Wrapper Object All wrapper
classes define a static method called valueOf(), which returns the wrapper object corresponding to
the primitive value represented by the string argument as shown below. valueOf() is overloaded:
one version accepts integer values and another accepts a String. String argument method generates
a NumberFormatException in case the value in a String does not contain a number.
Double ValueOfDouble = Double.valueOf(xyz);
// For converting String containing double values to wrapper objects
Float ValueOfFloat = Float.valueOf(xyz);
// For converting String containing float values to wrapper objects
Integer ValueOfInteger = Integer.valueOf(xyz);
// For converting String containing int values to wrapper objects
Interfaces, Packages, and Enumeration 173
The integer value 8 is converted to its binary equivalent using toBinaryString(), i.e., 1000, and
32 is converted to its hexadecimal equivalent, i.e. 20.
Autoboxing and Unboxing of Wrappers
Java 5.0 introduced a new feature for converting back and forth between a wrapper and its cor-
responding primitive. The conversion from primitives to wrappers is known as boxing, while
the reverse is known as unboxing.
In the previous section, we have already seen boxing and unboxing being enforced by the use
of a certain amount of clumsy code. Before J2SE 1.5, Java had primitive data types with wrappers
around them, so programmers had to convert from one type to another programmatically.
public void manualConversion()
{
int a = 12;
Integer b = Integer.valueOf(a);
int c = b.intValue();
}
If you are dealing with a lot of instances of wrappers and conversions, you will need to deal
with a lot of method invocations. The to and fro conversion between primitives and wrappers
is simplified by the use of autoboxing and unboxing. Behind the scenes, the compiler creates
codes to implicitly create objects for you.
public void autoBoxing()
{
int a = 12;
Integer b = a; // wrapping
int c = b;
}
174 Programming in Java
Here, the wrapping is done automatically. There is no need to explicitly call the integer
constructor. Autoboxing means a primitive value is automatically converted into the wrapper
object. The reverse process, i.e., automatic conversion back from wrapper object to primitive
value, is known as unboxing.
To sum up the complete essence of autoboxing and unboxing, we take the following piece of code:
Integer wrap_int = 5; //primitive 5 autoboxed into an Integer object
int prim_int = wrap_int; //automatic unboxing of Integer into int
There is one thing that you must remember: boxing and unboxing too many values can put undue
pressure on the garbage collector.
6.3.3 String Class
Strings are basically immutable objects in Java. Immutable means once created, the strings
cannot be changed. In fact there is a class named String in the java.lang package for creating
strings. Whenever we create strings, it is this class that is instantiated. In Java, strings can be
instantiated in two ways:
L1 String x = "String Literal Object";
L2 String y = new String ("String object is created here");
Explanation
L4 A new object is created which is different from L15 As already discussed, Strings created with the
a, b, and c as well. help of new are not allocated memory from the pool,
L5 A new string object is created with a different but are interned. The method java.lang.String.
literal this time "Hello, how are you?". This object intern() is used for this purpose. The intern()
is also different from all the objects that we have method creates a string object in the pool with the
created till this point in our example. same String literal as that of the invoking String
L6 Equality operator (= =) is used in the if object and returns a reference of the newly created
statement to check whether both references a and object in the pool. In this Line, f points to the newly
b are pointing to the same location or not. Equality created object in the pool because the string literal
operator is not used for matching the contents of the object Hello, how are you? does not exist in the
strings, i.e., literals. The two references that are being pool. The intern method is called from the string
matched are a and b and as both point to the same object which needs to be interned, i.e., the previous
location, L7 is executed. If a and b do not point to String object will be garbage collected as it is no
the same location, L8 would be executed. longer in use.
L7 Print statement to show that references point L16 Checks whether f and e point to the same
to the same object. object in the pool or not. They actually point to
L8 Print statement to show that references point different locations and that is why L18 gets executed.
to different objects.
String Manipulation
Strings in Java are immutable (read only) in nature. That is, once the Strings are defined, they
cannot be altered. Let us have a look at the following lines of code:
L1 String x = "Hello"; // ok
L2 String x = x +"World"; // ok, but how?
Java does not support operator overloading, but the ‘+’ operator is already overloaded to accept
different operands and it acts accordingly. If at least one of the operand is a string, it concatenates.
The question that arises is that if strings are immutable, then how L2 gets executed? Actually
L2 gets converted into the following statement:
String x = new StringBuffer().append(x).append("World").toString();
A new StringBuffer object is created which is used for the mutable set of characters. Mutable
characters can change their values. The append (add at the end) method of the StringBuffer
object is used to append the string Hello contained in x into the newly created StringBuffer
object. Again the append method is used to append the string World to existing Hello in the new
object. The method toString() converts StringBuffer object back to String and x points to this
newly created String object. No references exist for the existing object Hello; it will be garbage
collected.
String Methods
The String class provides a lot of methods. Table 6.5 lists a few common methods of the String
class.
Interfaces, Packages, and Enumeration 177
// int declaration
int i = 20;
// finding the length of String
L1 System.out.println("Length of String = " +x.length());
/* equals method of Object class has been overridden by the String class for per-
forming different function i.e., equating two string objects by matching strings
character by character */
L2 System.out.println("x and y are equal = " +(x.equals(y)));
// comparison of Strings
L3 if((x.compareTo(y)) < 0)
L4 System.out.println("x is less than y");
L5 else if((x.compareTo(y)) > 0)
L6 System.out.println("x is greater than y");
L7 else
L8 System.out.println("x is equal to y");
// Region Matching within Strings
L9 System.out.println("x region matches with y : " + ((x.regionMatches(0,y,0,11)));
// finding index of Characters
L10 System.out.println("index of \" i\" in String x is: " +x.indexOf("i"));
// finding index of particular String
L11 System.out.println("index of \"is\" in String x is: " +x.indexOf("is"));
Output
C:\javabook\ chap 6>java StringDemo
Length of String = 21
x and y are equal = false
x is less than y
x region matches with y : true
index of "i" in String x is: 2
index of "is" in String x is: 2
Last index of "i" in String x is: 18
Last index of "is" in String x is: 5
Substring of String x from character 4 is: is a Demo String
Substring of String x from character 4 to 15 is: is a Demo
character at position 6 is: s
UpperCase: THIS IS A DEMO STRING
LowerCase: this is a demo string
x starts with "Th" : true
x ends with "Th" : false
converts int to String: 20
Explanation
As discussed earlier, all instance methods of the name. Table 6.4 describes these functions in brief.
String class are invoked with the help of String Figure 6.4 pictorially depicts how are the methods
objects and class methods through the String class of String class invoked.
<x.equals(y)>
Output
C:\javabook>java StringBufferDemo
Initial Capacity : 16
String appended : Dogs bark at night
String replaced : Dogs bark during night
String reversed : thgin gnirud krab sgoD
Current Capacity : 34
character at position 3 is: i
sb after setting "a" at 3: thgan gnirud krab sgoD
Explanation
The description of the methods used in the program is available in Table 6.6.
reverse()) return StringBuilder objects rather than StringBuffer objects. The line below shows
the creation of a StringBuilder object.
StringBuilder s=new StringBuilder();
/* construct a StringBuilder object with an initial capacity of 16 characters.
Similar to that of StringBuffer.*/
Output
C:\javabook>java StringTokenizerDemo
Splitting String Using StringTokenizer class
Token 1 :Never
Token 2 :look
Token 3 :down
182 Programming in Java
Token 4 :on
Token 5 :anybody
Token 6 :unless
Token 7 :you’re
Token 8 :helping
Token 9 :him
Token 10 :up
Splitting String Using split() method
Never
look
down
on
anybody
unless
you’re
helping
him
up
Splitting String Using Pattern class
Never
look
down on anybody unless you’re helping him up
Explanation
L1 Importing the package j a v a . u t i l . * is the output).
mandatory because StringTokenizer is a part of L10 This statement prints the first Token. In the
this package. first iteration, the method nextToken() points to
L2 Importing the subpackage java.util.regex.* the first token which is printed on the screen and the
is mandatory because the class Pattern is a part of cursor moves to the new line afterwards.
this subpackage regex. An important point to note L11 The value of i is incremented. In the next
here is that importing any package does not mean iteration, the value of i will be 2, and so on.
that the sub-packages are also implicitly imported. L12–15 Show another way of splitting the string
The sub-packages need to be imported explicitly. using the split()method.
L5 Integer i declared and initialized to 1. L13 split() method of the String class is used
L6 String to be split has been declared, str. for splitting the string, str. It accepts one arguments,
L7 An object of StringTokenizer class is created. i.e., regex.
The constructor accepts two arguments: (a) str and The regular expression, regex, can be a character, a
(b) the delimiter, i.e., whitespace in our example. The group of characters, or a word which is to be searched
string str is cut into tokens wherever the specified in a string. Here we want to split the string on the
delimiter, i.e., the white space is encountered and the basis of regex which is a whitespace. So wherever
tokens are stored in the StringTokenizer object tr. a whitespace is encountered in the str, it is split and
This tr object is iterated for retrieving the tokens stored in the String array tk as the next array item.
one by one. L14–15 In each iteration, the String tokens are
L8 The condition in the while loop checks whether assigned successively a value from ‘tk’ and printed.
the StringTokenizer object has more tokens or not L16–19 Show another way of splitting the string
with the help of hasMoreTokens(). which returns using the Pattern class.
a boolean value to indicate whether tr has more L16 Shows how the Pattern class of the regex
tokens or not. sub-package is used for splitting a string. The Pattern
L9 Statement to print “Token” followed by the class provides a static method named compile()
value of i, i.e., Token 1 (for the first iteration, see to compile the regular expression to a pattern. The
Interfaces, Packages, and Enumeration 183
For example, the following statement assigns the enumerated value TENNIS to the variable G:
G = Games.TENNIS;
Output
First game is CHESS
Second game is TENNIS
First game's ordinal is 2
second game's ordinal is 4
G1.equals(G2) returns false
G1.toString() returns Chess
G1.compareTo(G2) returns -2
Explanation
L2 An enumerated type is defined, having the compareTo from an enumerated object reference
ordered list of games. variable. G1.equals(G2)returns true if G1 and G2
L4 and 5 Variables G1 and G2 are declared as the have the same ordinal value. G1.compareTo(G2)
Games type and assigned enumerated values. returns the difference between G1’s ordinal value
L8 Since G1’s value is Chess, its ordinal value is 2. to G2’s. The enum type has a toString() method
L9 Since G2’s value is Tennis, its ordinal value is 4. defined that returns the string values. So it is easy
L10–12 An enumerated type is a subclass of the to print these values without any special conversion
Object class and the Comparable interface, so you effort. For example, System.out.println(G1)will
can invoke the methods equals , toString , and print CHESS.
Example 6.13 Alternative Way of Using Enumerated Type
L1 public class EnumExample{
L2 public static void main(String[] args){
L3 Games G1 = Games.Chess;
L4 Games G2 = Games.Tennis;
L5 System.out.println("G1's name is " + G1.name());
L6 System.out.println("G2's name is " + G2.name());
L7 System.out.println("G1's ordinal is " + G1.ordinal());
L8 System.out.println("G2's ordinal is " + G2.ordinal());
L9 System.out.println(" G1.equals(G2) returns " +G1.equals(G2));
L10 System.out.println (" G1.toString() returns " +G1.toString());
L11 System.out.println (" G1.compareTo(G2) returns " +G1.compareTo(G2));
L12 }}
L13 enum Games {Cricket, Football, Chess, Basketball, Tennis, Badminton};
Interfaces, Packages, and Enumeration 185
Output
C:\javabook\PROGRA~1>java EnumExample
G1's name is Chess
G2's name is Tennis
G1's ordinal is 2
G2"s ordinal is 4
G1.equals(G2) returns false
G1.toString() returns Chess
G1.compareTo(G2) returns -2
An enumerated type defined inside a class behaves as an inner class, as shown in the L2 of
Example 6.11, or standalone as shown in the L13 of Example 6.12. When an enumerated type
is declared inside a class, it is a member of the class and cannot be declared inside a method.
The enumerated type is always static. So, the static keyword in L2 of Example 6.11 may be
omitted. After Example 6.11 is compiled, a class named EnumDemo$Games.class is created. After
Example 6.12 is compiled, a class named Games.class is created.
6.4.1 Using Conditional Statements with an Enumerated Variable
An enumerated type holds a set of values. If you need to perform a specific action depending on
the value, then you can use if or switch-case for the same. For example, if the value is Games.
CRICKET, book ticket; if the value is Games.FOOTBALL, bunk the class; and so on. You can use an
if statement or a switch statement to test the value in the variable, as shown below.
If statement
if (G1.equals(Games.CRICKET)) {
// action to be performed}
} else if (G1.equals(Games.FOOTBALL)) {
// action to be performed}
else ....
Switch statement
switch (Games){
case CRICKET: // case CRICKET and not Games.CRICKET
// action to be performed;
case FOOTBALL:
// action to be performed;
...
}
You can use a for loop to process all the values in the array.
for (int i = 0; i < G.length; i++)
System.out.println(G[i]);
186 Programming in Java
Example 6.14 (a) Defining an Enumerated Type with Attributes and Methods
L1 public enum Desc {
L2 CRICKET ("Sachin Tendulkar"), CHESS("Vishwanathan Anand"), TENNIS ("Sania Mirza");
L3 private String description;
// Constructor
L4 private Desc(String description){
L5 this.description = description;
L6 }
L7 public String getDesc(){
L8 System.out.print("Indian Delight: ");
L9 return description;
L10 }}
Explanation
L1 An enumeration named Desc is declared. L4–6 The constructor Desc is declared. This
L2 The enumerated values are listed with their constructor is invoked whenever an enumerated value
description (mentioned in double quotes). This is accessed. The value (description) is passed to the
declaration must be the first statement in the class, constructor, which is then assigned to description.
otherwise a compile-time errors results. L7–9 getDesc() has been declared with the return
L3 A datafield named description is declared to type String to return the description.
denote an enumerated description.
Output
C:\javabook\PROGRA~1>java UseDesc
Indian Delight: Sania Mirza
Explanation
L3 An enumerated value Desc.TENNIS is assigned L4 The methods in enumerated type are invoked
to the variable player (L3). Accessing Desc.TENNIS in the same way as the methods in a class. player.
causes the JVM to invoke the constructor with the getDesc() returns the description for the enumerated
argument SaniaMirza. value.
Interfaces, Packages, and Enumeration 187
Note The constructor for an enumerated type should be private to prevent it from being invoked
directly.
/*Account No*/
private String accountNo;
/*The methods are declared abstract so that the subclasses can code them according
to their respective needs keeping their names in tact*/
package banking;
{
super(b,acno);
}
/*explicit default constructor*/
SavingAccount()
{
super(0,"");
}
/*display method to print account no, balance and interest rate. The super class
display method already prints the account no and balance so it is invoked using the
super keyword.*/
package banking;
class CurrentAccount extends Account
{
/* borrowed amount, cannot be greater than the limit */
float overdraftborrowed;
/* Maximum credit limit */
float overdraftlimit;
/*Constructor to initialize the current account. every current account holder
will have a different overdraft limit. so while creating current account object
we have to pass the limit as well*/
CurrentAccount(float b,String acno, float od)
{
super(b,acno);
overdraftlimit = od;
}
/*limits may change over time so an option is provided to change the limit*/
void setOverdraft(float o)
{
overdraftlimit = o;
}
/*credit method is used to deposit the amount in the current account. if the
customer has borrowed some amount from the bank, then first the borrowed
amount is returned to the bank and the rest is added to the balance. */
public void credit(float amount)
{
System.out.println("Amount to be credited: "+amount);
System.out.println("Old Balance: "+balance);
System.out.println("Overdraft Borrowed: " + overdraftborrowed);
/*checks whether amount to be deposited is greater than overdraftborrowed,
deducts it by overdraftborrowed thus making the overdraftbor-
Interfaces, Packages, and Enumeration 191
rowed nil and add the rest amount in balance. otherwise the overdraft-
borrowed is reduced by the amount making no changes to the balance */
if(amount > overdraftborrowed)
{
amount = amount – overdraftborrowed;
overdraftborrowed = 0;
balance = balance + amount;
}
else if(amount<overdraftborrowed)
{
overdraftborrowed = overdraftborrowed-amount;
}
System.out.println("New Overdraft Borrowed: " + overdraftborrowed);
System.out.println("New Balance: "+balance);
}
/* deducts the amount from the balance. If amount to be deducted is less than
balance; the amount is deducted from balance. But, if amount is greater than
balance but less than the limit, then the shortfall will be fulfilled by the
bank by setting the overdraftborrowed for the customer. Hence overdraftbor-
rowed is set to shortfall (amount-balance) and balance will be nil. If amount
is greater than balance as well as the ODlimit then the
request is denied */
public void debit(float amount)
{
System.out.println("Amount to be debited: "+amount);
System.out.println("Old Balance: "+balance);
if(amount <= balance)
balance = balance – amount;
else if((amount > balance) && (amount < (balance + overdraftlimit)))
{
overdraftborrowed = amount – balance;
balance = 0;
System.out.println("Overdraft Borrowed: " + overdraftborrowed);
}
else
System.out.println("Request Denied");
System.out.println("New Balance: "+balance);
System.out.println("Overdraft Borrowed: "+overdraftborrowed);
}
public void display()
{
super.display();
System.out.println("Overdraft limit: "+overdraftlimit);
}
public String toString()
{
return "Current Account No: "+getAccountNo()+ " Balance :"+balance+"
Overdraft limit: "+overdraftlimit;
}
}
Now let us create a Customer class that will own any one of these accounts.
192 Programming in Java
// customer id
String custId;
/* every customer of the bank is assigned an Account which is its private attribute.
So an instance variable of type Account is defined here. A customer can either have
a saving account or a current account. That is why we have added an attribute of
type Account in this class and not SavingAccount or CurrentAccount. Account refer-
ence variable can refer to objects of both its subclasses: SavingAccount and Curren-
tAccount. So whatever account the customer wishes to open, its object can be saved
into this instance variable of type Account */
/* deposit method declared to add amount to the balance. Here we have to call the
appropriate method according to the type of the account. So first e check what is
the type of account held by the customer using the instanceof keyword and based on
that we call the credit method of the respective classes.*/
/* credit method belongs to the SavingAccount class or the CurrentAccount class and
not the Account class. So if the method is invoked as account.credit(amt), the com-
piler will not compile the program. The reason is that the compiler looks for credit
method in the Account class (as the type of account reference variable is Account)
which is not there. The account variable is casted into SavingAccount or CurrentAc-
count and then the credit method is invoked. The cast is possible as the classes are
subclasses of the Account class. The account refernce variable will actually hold
objects of either SavingAccount or CurrentAccount class*/
((SavingAccount)account).credit(amt);
((CurrentAccount)account).credit(amt);
}
void depositInterest()
Interfaces, Packages, and Enumeration 193
/* withdrawal method declared to deduct amount from the balance. Here we have to
call the appropriate method according to the type of the account. So first we check
what is the type of account held by the customer using the instanceof keyword and
based on that we call the debit method of the respective classes.*/
Let us now create a Bank class to test all the classes that we have created. First of all we will
create a Bank class in which we will be creating Customers. These customers will be holding
accounts on which we will be performing deposit, withdrawal, and display operations.
package banking;
{
/* Customer objects created and put in the individual array elements.
Constructor of the Customer class accepts three arguments: Customer name, Customer
id and an object of type Account.*/
/* Banks can change its interest rate for all Saving Account holders by invoking
this method*/
void changeInterestRate(float i)
{
/*SavingAccout class contains the attribute for interest rate. A setter method is
created for setting the interest rate. This interest rate is applicable for all sav-
ing bank account holders. The static method ‘setInterest" of the SavingAccount class
is used to change the interest rate.*/
SavingAccount.setInterest(i);
}
/*Invokes its demo method- which deposits and makes withdrawals from the cus-
tomer accounts*/
b.demo();
c[1].display();
Output
To run the example you have to set the classpath with the path up to the directory that contains
the banking package. For example, if banking package (directory) is within “chap 6” then the
command to edit the classpath would be
set classpath = %classpath%;d:\javabook\chap 6;
D:\javabook\chap 6>java banking.Bank
Customer Name: Rahul
Customer Id: C001
Account Number: A001
Account balance: 12000.0
Interest rate: 6.0
Saving Account No: A001 Balance : 12000.0
Amount to be credited: 1000.0
Old balance: 12000.0
New balance: 13000.0
Amount to be debited: 15000.0
Old balance: 13000.0
Request Denied
Customer Name: Ram
Customer Id: C002
Account Number: A002
Account balance: 12000.0
Interest rate: 6.0
Saving Account No: A002 Balance : 12000.0
196 Programming in Java
SUMMARY
Java does not support multiple inheritance among other classes like Object, String, StringBuffer,
classes. The only exception to this is interfaces. and StringBuilder class have been discussed, as
Multiple inheritance can be done using interfaces. these classes are frequently used in programming. All
A class can inherit any number of interfaces. The classes, whether predefined or user-defined, inherit
only fact mandatory for a class to follow is that it has ultimately from the Object class implicitly. So String,
to override and provide implementation for all the StringBuffer, and StringBuilder also have objects
methods of all the interfaces it inherits. Such classes as their parents.
can be grouped together to form a package. Package Strings in Java are immutable, i.e., one cannot
is a collection of Java files similar to a directory. As change a string once it is defined. StringBuffer
subdirectories exist within a directory, subpackages and StringBuilder are both used for mutable set of
can exist within a package. characters. StringBuilder (added in Java 5) is much
There are a number of predefined packages in more efficient in terms of performance as compared to
Java—one of them is discussed in this chapter: java. StringBuffer because the former is not synchronized
lang package. This is a fundamental package. For all and the latter class is. At the end of the chapter, we
the primitive data types, wrapper classes have been have discussed enumerations. Enum type is a kind of
defined in this package. These wrappers encapsulate class and is basically useful when we know the type
the functionality of the primitive data types. A few along with the possible set of values in that type.
Interfaces, Packages, and Enumeration 197
EXERCISES
Objective Questions
1. What will happen if the following line is present }
in a program? }
Review Questions
1. What is an interface? How is it different from an 5. Explain the following:
abstract class? (a) public (b) private
2. What are packages? How are they created and (c) default (d) protected
used? (e) import (f) static import
3. What are wrapper classes?
6. Explain the difference between String and
4. What is enum type? Explain with the help of a StringBuffer.
program.
Programming Exercises
1. Design an interface named Stack with the 4. Write a program to count the number of words
following methods: and characters in a string.
(a) Push and pop elements from the stack. 5. Design an enumeration for weekdays and print
(b) Check whether the stack is empty or not. their corresponding description according to the
Implement the stack with the help of arrays traditional rules:
and if the size of the array becomes too small
to hold the elements, create a new one. Test Description Weekdays
this interface by inheriting it in its subclass Sun Sunday
StackTest.java. Moon Monday
2. Design an interface named Queue with the Mars Tuesday
following methods:
(a) To add and remove elements from the queue. Mercury Wednesday
(b) Check whether queue is empty or not Jupiter Thursday
Implement the queue with the help of arrays Venus Friday
and if the size of the array becomes too small
Saturn Saturday
to hold the elements, create a new one. Test
this interface by inheriting it in its subclass 6. Design an interface with a method reversal.
QueueTest.java This method takes a string as its input and
3. Create a class within this package “AmountIn- returns the reversed string. Create a class
Words” to convert the amount into words. (Con- StringReversal and implement the method [Do
sider the amount to be not more than 100000.) not use predefined methods].
7.1 INTRODUCTION
Exceptions in real life are rare and are usually used to denote something unusual that does not
conform to the standard rules. For example, Abraham Lincoln was an exception who, despite all
hurdles in his life, rose to become the sixteenth president of the USA. In computer programming,
exceptions are events that arise due to the occurrence of unexpected behavior in certain statements,
disrupting the normal execution of a program.
Exceptions can arise due to a number of situations. For example,
Trying to access the 11th element of an array when the array contains only 10 elements
(ArrayIndexOutOfBoundsException)
Division by zero (ArithmeticException)
Accessing a file which is not present (FileNotFoundException)
Failure of I/O operations (IOException)
Illegal usage of null (NullPointerException)
There are predefined classes (mentioned in the parenthesis above) for all exception types
representing each such situation. The topmost class in the hierarchy is java.lang.Throwable. This
class has two siblings: Error and Exception. All the classes representing exceptional conditions
are subclasses of the Exception class. Whenever an exception occurs in a method, the runtime
environment identifies the type of Exception and throws the object of it. If the method does not
200 Programming in Java
employ any exception handling mechanism (discussed later in the chapter), then the exception
is passed to the caller method, and so on. If no exception handling mechanism is employed in
any of the call stack (also known as runtime stack, i.e., the sequence of method calls from the
current method to the main method) methods, the runtime environment passes the exception
object to the default exception handler available with itself. The default handler prints the name
of the exception along with an explanatory message followed by the stack trace at the time the
exception was thrown and the program is terminated.
Note Stack trace is a record of the active stack frames generated by the execution of a program. It
is used for debugging.
Output
C:\javabook\programs\chap 7>java ExDemo
IN Method 1, Calling Method 2
IN Method 2, Calling Method 3
IN Method 3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExDemo.method3(ExDemo.java:23)
Exception, Assertions, and Logging 201
at ExDemo.method2(ExDemo.java:16)
at ExDemo.method1(ExDemo.java:10)
at ExDemo.main(ExDemo.java:5)
Explanation
L1 Class declaration. halts at this point. The JVM throws an object of class
L3 main method declaration. ArithmeticException for an exception handler
L5 Call to method1(). Control passes to method1(). to catch it. No exception handler is provided with
Call stack populated by pushing method1() call to method3(). So the caller methods are looked upon to
top of the stack. see if they can handle this particular exception. None
L7 method1() declaration. of the caller methods, method2(), method1(), and
L9 Prints IN Method 1, Calling Method 2 (as main() employ any exception handling technique, so
shown in the output). the JVM passes the exception to the default exception
L10 Call to method2(). Control passes to method2(). handler which in turn prints Exception in thread
Call stack again populated by pushing method2() call "main" followed by the name of the exception along
to the top of the stack above method1() call. with an explanatory message. In the next line, it
L11 Prints Returned from method 2 if successfully prints the stack trace to help programmers debug the
returns from method 2. program and finally terminates the program. Take a
L13 method2() declaration. look at the stack trace shown in Fig. 7.1.
L15 Prints IN Method 2, Calling Method 3 (as ExDemo.method3(ExDemo.java:23)
shown in the output).
L16 Call to m e t h o d 3 ( ) . Control passes to
method3(). The call stack is again populated by
pushing method3()call to the top of the stack above class method File Line number where
method2() call. name name name execution halted
L17 Prints Returned from method 3 if successfully method3 was called by method2 (line 16) and method2
returns from method3().
by method1 (L10). method1() was called by main (L5).
L19 method3()declaration.
As you can see in the output, the call stack is printed
L21 Prints IN Method 3.
L22 Two integer variables initialized with a value as it is from top to bottom. Also note the line numbers
of 20 for a and 0 for b. are printed in the output.
L23 An integer variable is being divided by zero. method3
We have intentionally written this statement to
method2
show you what happens when an exception occurs.
method1
Normally, in practice, nobody would attempt such a
thing. You cannot divide a number by zero. It results main
in an ArithmeticException in Java. The execution Fig. 7.1 Call Stack
Figure 7.2 shows the exception hierarchy in Java. Not all the Exception and Error subclasses
have been depicted in the figure. The dots in the diagram are an indicator that there are other
classes also within the immediate superclass. Example 7.1 can be modified to handle the exception
generated in method3.
java.lang.Throwable
Error Exception
StringIndex ArrayIndex
OutOfBounds OutOfBounds
Exception Exception
7.2.1 try…catch
The try/catch block can be placed within any method that you feel can throw exceptions. All
the statements to be tried for exceptions are put in a try block and immediately following the
try is the catch block. catch block is used to catch any exception raised from the try block. If
exception occurs in any statement in the try block, the following statements are not executed
and control immediately passes to the corresponding catch block.
Output
C:\javabook\programs\chap 7>java ExDemo1
IN Method 1, Calling Method 2
IN Method 2, Calling Method 3
IN Method 3
Exception Handled
Returned from method 3
Returned from method 2
204 Programming in Java
Explanation
L28 Exception occurred. No handling mechanism is encountered in the try block, statements following
in method3(), so the control passes to the try…catch the statement on which the exception occurred are
block in method2(). not executed. The runtime environment creates an
L29 It is not executed, as the statements following object of class representing the exception and throws
the occurrence of an exception are not executed. it. Control passes to the appropriate catch block (first
L16 try block declared. The statements to be
appropriate catch in case multiple catch clauses
monitored for exceptions should be placed in the try
are present) where the thrown object is caught and
block within a method.
L17 A call to method3() is placed within the try assigned to e, i.e., the Exception reference variable.
block. L20 Prints ExceptionHandled.
L18 catch clause defined with an argument of L22 Prints Returned from method3(). After the
type Exception (parent class) so that the exception exception has been caught (try…catch mechanism
objects thrown from the try block can be caught implemented), execution resumes as normal. This
here. A superclass reference variable can refer to was not possible in Example 7.1. After this, the
a subclass object. The try block is immediately control passes back to method1() from where
followed by a catch block. As soon as an exception method2() was called and L11 gets executed (see
output).
A single try can have multiple catch clauses, for catching specific exceptions. As soon
as an exception is thrown, the first appropriate catch clause responsible for handling that
exception is located and the exception is passed to it. By first appropriate catch, we mean, if
ArrayIndexOutOfBoundsException is generated, then the control passes to the first catch that either
specifies the ArrayIndexOutOfBoundsException or the IndexOutOfBoundsException superclass
of the ArrayIndexOutOfBoundsException or Exception. All exceptions can be caught by the
Exception class. Example 7.3 shows how multiple catch clauses are incorporated in a program.
L19 {
L20 System.out.println ("Arithmetic Exception Handled: " +ae);
L21 }
L22 catch(Exception e)
L23 {
L24 System.out.println("Exception Handled");
L25 }
Explanation
L16 try block defined. ArithmeticException class to print its own string
L17 Call to method3(). rather than that of the Object class.
L18 The first catch clause defined with an L22 The second catch clause defined with an
argument of type ArithmeticException class. argument of type Exception class. This has been
L20 Prints Exceptionhandled concatenated with specified intentionally because if any other exception
the output of ae.toString(). Remember toString() is thrown apart from ArithmeticException, then
is called automatically when you try to print any that exception will be caught in this particular catch
object. toString() method is overridden in the clause.
Note While specifying multiple catch clauses for exception handling, the catch clause having the
Exception type as its argument should be the last catch block in your program. This is because
if the catch having the reference variable of type Exception class is placed as the top catch
clause, then all the exceptions thrown from the try block will be caught in the first catch and the
control will never pass onto the lower catch blocks, leading to an unreachable code.
An unreachable code in Java is easily recognized by the Java compiler and it complains about
it during compilation. For example, if the catch clauses in Example 7.3 are reversed, as shown,
the program will not compile.
catch(Exception e){}
catch(ArithmeticExceptionae) {}
206 Programming in Java
Output
C:\javabook\programs\chap 7>java ThrowDemo
IN Method 1, Calling Method 2
IN Method 2, Calling Method 3
Exception, Assertions, and Logging 207
IN Method 3
Exception Handled: java.lang.ArithmeticException: Testing throw
Returned from method 3
Returned from method 2
Explanation
L28 Instead of an expression which leads to the This argument can also be separately printed using the
runtime environment throwing an exception, we getMessage() method of the ArithmeticException
have used throw keyword to throw the exceptions class.
ourselves. Just like the runtime environment, we L29 It is commented. If it is not commented, the
also need to create an object for throwing it. So the compiler will give an error stating Unreachable Code.
ArithmeticException object is created with the Particularly, in this program, the control will always
help of new keyword and an argument is passed move out after the throws clause, searching for a
to its constructor. This argument is printed onto handler, so this line will never be executed. The Java
the console via the toString() method of the compiler is intelligent enough to understand this and
ArithmeticException class, when we catch this raises an error.
exception and print the exception object (see output).
This exception is caught and printed in the catch present in L18–21. Rest of the logic is similar
to the previous example.
7.2.3 throws
The throws is added to the method signature to let the caller know about what exceptions the
called method can throw. It is the responsibility of the caller to either handle the exception
(using try…catch mechanism) or it can also pass the exception (by specifying throws clause
in its method declaration). If all the methods in a program pass the exception to their callers
(including main()), then ultimately the exception passes to the default exception handler. A
method should use either of the two techniques—try/catch or throws. Usually (for checked
exceptions specifically), it is the catch or specify mechanism that is used. A method can throw
more than one exception; the exception list is specified as separated by commas. The syntax for
the throws keyword is shown below:
public void divide(int a, int b) throws ArithmeticException, IllegalArgumentException
Let us take a look at the following example.
L12 }
L13 static void method2()
L14 {
L15 System.out.println("IN Method 2, Calling Method 3");
L16 try{
L17 method3(4,0); }
L18 catch(Exception e)
L19 {
L20 System.out.println("Exception Handled: " + e);
L21 }
L22 System.out.println("Returned from method 3");
L23 }
L24 static void method3(int a, int b) throws Exception
L25 {
L26 System.out.println("IN Method 3");
L27 if(b == 0)
L28 throw new ArithmeticException("Testing throw");
L29 else
System.out.println("Result: "+a/b);
}}
Output
When a = 4 and b = 2
C:\javabook\programs\chap 7>java ThrowsDemo
IN Method 1, Calling Method 2
IN Method 2, Calling Method 3
IN Method 3
Result: 2
Returned from method 3
Returned from method 2
When a = 4 and b = 0
C:\javabook\programs\chap 7>java ThrowsDemo
IN Method 1, Calling Method 2
IN Method 2, Calling Method 3
IN Method 3
Exception Handled: java.lang.ArithmeticException: Testing throw
Returned from method 3
Returned from method 2
Explanation
L24 method3() has been declared with throws clause intact, the compiler will not compile the program as
specifying that it may throw an exception. The parent now, it is mandatory for the calling method to either
class (Exception) has been specified in the throws pass or catch the exception.
clause, so there is no need to explicitly mention the L26 Print statement.
L27 if statement checks the value of b. If it is zero,
subclass name (ArithmeticException). If throws is L28 is executed, else L29.
omitted in this line, the program works as usual. If the L28 An object of ArithmeticException is created
try/catch in method2() (L16, L18–21 and L23) is and thrown.
omitted and throws in method3() declaration is kept L29 else prints the result of division of a by b.
Exception, Assertions, and Logging 209
Output
When a = 24 and b = 4
C:\javabook\programs\chap 7>java FinallyDemo
IN Method 1
Exception Handled: java.lang.NullPointerException
In method 1 finally
IN Method 2
In method 2 finally
Result : 6
210 Programming in Java
When a = 24 and b = 0
C:\javabook\programs\chap 7>java FinallyDemo
IN Method 1
Exception Handled: java.lang.NullPointerException
In method 1 finally
IN Method 2
In method 2 finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyDemo.method2(FinallyDemo.java:24)
at FinallyDemo.main(FinallyDemo.java:6)
Explanation
L5 Call to method1(). Control passes to L7. zero, an attempt to divide any number by zero results
L6 Call to method2() and if any, return is printed in an ArithmeticException being thrown.
on the screen. L23 Just to show that the finally block executes
L7 method1() declaration. in all cases, we have intentionally not given the catch
L9 try block defined. in method2(). A try can either have a corresponding
L11 NullPointerException is thrown. Control catch with finally or it can also have a finally
passes to catch in L12. following it. In the earlier examples, we have seen
L12 catch block corresponding to try in L9. that as soon as an exception is encountered, its
L14 Prints the exception object e. (e.toString() appropriate handler is looked upon and nothing gets
is called by default). executed until and unless the exception is handled.
The only exception to this fact is the finally block.
L16 Shows the finally block. The exception
In our example, the exception is thrown in L22.
thrown in L11 is caught at L12. The finally block
method2() does not have its own catch to handle
following catch gets executed after that (see output).
exceptions, so its caller is to be looked upon but
L17 The statement within finally gets executed. before control passed to the caller, i.e., main method,
L18 method2() declared expecting two integer the finally in method2() is executed. And then the
arguments. Value passes are 24 and 0. control passes to main() where no handler is present,
L20 try block within method2(). so the runtime environment handles the exception as
L22 As already discussed, the value of b being already discussed (see output).
This close method will be overridden by the class that implements the interface and all resources
releasing code can be put in this method. The close method of the AutoCloseable object is called
automatically when it is used with a try-with-resources statement as soon as the try-with-
resources block has finished execution regardless of whether an exception is thrown or not.
The syntax of a try-with-resources statement is as follows:
try (resources to be used and automatically released)
{
// statements within the block
}
For example
try (abc a=new abc(); pqr p=new pqr())
{
// statements within the block
}
More than one AutoCloseable resources can be used in try-with-resources statement separated
by semicolon. Hence it is mandatory for abc and pqr objects to implement the AutoCloseable
interface as shown below in the example. The resources created in the try-with-resources
statement are closed in the reverse order of creation. We will elaborate these concepts in Example
7.7.
L9 catch(Exception e)
{
System.out.println("Within catch block");
}
}
}
Output
D:\javabook\programs\chap 7\java TestTryWithResources
Within try with resources block
Within close method of pqr
Within close method of abc
Within catch block
Explanation
L1–4 All resources that need to be closed auto- method of abc (see output). Note that these two
matically after their use must implement the Auto- objects have already inherited the AutoCloseable
Closeable interface and override the close method. interface otherwise a compile time error will be raised
L5 Another class is created to test the AutoClose- by the compiler.
able resources created above. L8 An explicit Exception is raised to show that
L6 main method declaration. the close methods are called irrespective of whether
L7 try-with-resources statement is used to create an exception occurs or not. In case an Exception is
two resources which will be automatically closed raised, the close methods are called prior to handling
once the block exits by calling their respective close the Exception (see output).
methods in reverse order of creation. The close L9 catch block is declared to handle the exception
method of pqr is called first and then the close raised from the try-with-resource block.
Note It is not mandatory for a try-with-resource block to have a catch or finally block unlike the
previous version of JDK. They are optional in Java 7 with a try-with-resource block.
{
// statements
}
catch (Exception1 | Exception2 | Exception3 e)
{
// statements
}
Exception, Assertions, and Logging 213
So you might get the feeling that the catch block in Example 7.3 can be rearticulated as:
catch (ArithmeticException | Exception e)
{
// statements
}
But the problem with the catch block above is that both ArithmeticException and Exception
belong to the same hierarchy. (Actually every exception has branched out of Exception.) If the
catch block is rearticulated as shown below, it compiles because now both exceptions belong
to different inheritance hierarchy.
catch (ArithmeticException | NullPointerException | NumberFormatException e)
{
// Statements
}
The benefit of using multi catch is that it results in more efficient byte code as you have just
one catch block (instead of more as in the above case). Moreover same treatment can be applied
to exceptions of different hierarchies. A way of applying different treatment while using multi
catch syntax is by using instanceof operator as shown below. instanceof operator checks
whether an instance is of a particular class and return true or false.
catch(ArithmeticException | ArrayIndexOutOfBoundsException | NumberFormatException e)
{
if(e instanceof ArithmeticException)
System.out.println("Arithmetic Exception Handled: " +e);
else if(e instanceof NumberFormatException)
System.out.println("Exception Handled: " +e);
else
System.out.println(e);
}
Note In case the multi catch syntax is used, the parameter e is implicitly final.
if (a<b)
L2 throw new Exception1();
else
L3 throw new Exception2();
L4 } catch (Exception e) {
L5 throw e;
}
}
public static void main(String args[]) throws Exception
{
new DemoException().throwException(4,0);
}
}
The above method throwException could throw either Exception1 (L2) or Exception2 (L3)
based on the value of a or b. Prior to Java 7, it was not possible to specify these exception
types in the throws clause of the throwException method declaration (L1). The exception e is
re-thrown from the catch block (L5) and as e is of type Exception so only Exception can be
specified in the throws clause of method declaration on L1.
Java 7 onwards you can specify Exception1 and Exception2 in the throws clause of the
throwException method declaration. The compiler deduces that the exceptions thrown by throw
e (L5) must have come from the try block, and the exceptions thrown by the try block can
be Exception1 or Exception2. Although e is defined of type Exception (L4), the compiler can
determine that e would be an instance of either Exception1 or Exception2. Let us rephrase the
method in the program.
In other words, Java 7 onwards you can rethrow (L5) an exception that is a supertype (in our
case it is Exception) of any of the types declared in the throws (i.e., Exception1 and Exception2).
Exception, Assertions, and Logging 215
Output
C:\javabook\programs\chap 7>java TestException
Exception in thread "main" ExcepDemo Exception: Testing User Defined Exception
Explanation
L1 To create your own exception, your class has L4 toString method has been overridden. This is
to extend the Exception class as shown. automatically called when you print the object of the
L2 Constructor for the exception subclass has been exception subclass.
defined accepting a String argument. L5 String is being returned concatenated with the
L3 The S t r i n g argument is passed to the output of the getMessage() function. It returns the
superclass constructor using super. This argument string passed to the constructor of the superclass.
can be retrieved using a method of the superclass,
i.e., getMessage().
216 Programming in Java
The user-defined class is ready and now we need a L11 testException() method called.
sample class to test it, so we created the TestExcep- L12 catch corresponding to try (L10).
tion class. L13 Prints the exception. toString() is called
L6 TestException class defined. automatically, which returns the string Exceptionin-
L7 static method declaring that it can throw thread "main" ExcepDemoException: concatenated
ExcepDemo exception. with the argument passed in the constructor of the
L8 Exception thrown using the keyword throw. ExcepDemo class in L8 (see output). This String is
L9 main method declaration. returned through the method getMessage(), defined
L10 try block defined. in the Throwable class.
Wrapping has some disadvantages also. It leads to long stack traces; one for each exception in
the wrapping hierarchy. Secondly, due to wrapping, it becomes difficult to figure out the problem
that led to exceptions.
The possible solution is exception enrichment. In exception enrichment, you do not wrap
exceptions but add information to the already thrown exception and rethrow it, which leads to
a single stack trace. Let us take an example to see exception enrichment.
L8 class ExceptionEnrichmentDemo{
L9 static void testException() throws ExcepDemo
L10 {
try
{
L11 throw new ExcepDemo("Testing User Defined Exception");
}
L12 catch(ExcepDemo e)
{
L13 e.addInformation("\nexception was successfully enriched and
re-thrown from catch");
L14 throw e;
}
}
L15 public static void main(String args[]) {
L16 try
{
L17 testException();
}
L18 catch(ExcepDemo e){
L19 System.out.println(e);
}
}}
Output
C:\javabook\programs\chap 7>java ExceptionEnrichmentDemo
Exception in thread "main" ExcepDemo Exception: Testing User Defined
Exception exception was successfully enriched and re-thrown from catch
Explanation
L6 addInformation method has been added in is appended by calling the addInfomation() method
the user-defined exception class: ExcepDemo. This of the ExcepDemo object.
method accepts an argument of type String, so that L14 The exception object is re-thrown. When an
additional information about the exception can be exception is re-thrown from the catch block, then
added to the exception object. the control passes directly to the caller’s catch (if
L7 The string is concatenated to the instance any). In our case, it is present on L18.
variable message. L18 It shows the catch in the main method. This
L8 To test this, a new class has been created: catch is responsible for handling.
ExceptionEnrichmentDemo (a) Exceptions occurring in its own try (L16).
L9 Method named testException has been (b) Exceptions occurring in the methods that are
defined stating that it can throw ExcepDemo exception. called from the try block (L16) corresponding to
L11 Exception ExcepDemo is thrown. this catch.
L12 The exception thrown in L11 is caught at the (c) Exceptions re-thrown from the catch of the
catch defined in this line. other method that are called from your try (L14).
L13 Additional information regarding the exception L19 The exception object is printed.
7.5 ASSERTIONS
Assertions were added in Java 1.4 to create reliable programs that are correct and robust.
Assertions are boolean expressions that are used to test/validate the code. They are basically used
during testing and development phases. Assertions are used by the programmers to be doubly
218 Programming in Java
sure about a particular condition, which they feel to be true. Conditions such as a number is
positive or negative, array/reference is null or not can be checked by asserting them. Assertions
in Java are declared with the help of assert keyword as shown below:
assert expression1; // assert x > 0;
or
assert expression1: expression2 // assert x < 0:" Value Ok ";
where expression1 is the condition to be evaluated. In case, the condition is evaluated as false,
an AssertionError is thrown. expression2 is a string which is passed to the constructor of the
AssertionError object.
Assertions have to be enabled explicitly; they are disabled by default. Using the –ea and –da
options of Java, we can enable or disable assertions (see output).
-ea enable assertions
-da disable assertions
Output
When i = 1
C:\javabook\programs\chap 7>java -ea AssertDemo 1
value fine 1
When i = –1
C:\javabook\programs\chap 7>java -ea AssertDemo -1
Exception in thread "main" java.lang.AssertionError: Value must be positive
at AssertDemo.check(AssertDemo.java:4)
at AssertDemo.main(AssertDemo.java:9)
Explanation
L2 The static method has been declared with an Valuemustbepositive is passed to the constructor
integer argument. of the AssertionError object (see output). This
L3 assert keyword is used to check if the value has been handled in the same way exceptions were
of i is greater than 0 or not. If the value of i is less handled (refer Example 7.1).
than 0, an AssertionError is thrown and the string L4 Prints valuefine followed by the value of i.
Exception, Assertions, and Logging 219
L6 The method c h e c k is called. The first As you can see in the output, if assertions are not
command-line argument is converted to int using enabled, problems can arise. We never expected –1
the Integer.parseInt() function and passed to the to be a fine value in our program but in the (without
check method. enabling assertion) output, you can see it for yourself.
7.6 LOGGING
The logging feature was added in the java.util.logging package of Java 1.4 for debugging
purpose. Logs are basically used to report messages regarding the functioning of the application
to the programmer. These logs are supposed to be saved and reviewed later by the programmer.
Logs are created with the help of a Logger class in the util.logging package. These messages
are passed to handler objects which pass these messages to console, log files, etc. Loggings have
nine levels in Java (illustrated in Table 7.2) to indicate the severity of logged messages. These
levels are final and static fields of Level class (util.logging package).
Table 7.2 Logging Levels
Level Description
SEVERE Indicates severe problem, requiring attention (highest)
WARNING Indicates potential problem
INFO Informational messages; written on the console
CONFIG Message regarding configuration information
FINE Less detailed messages
FINER More detailed messages
FINEST Least of all three: FINE, FINER, FINEST. Used for most detailed output (lowest)
OFF Turns off logging
ALL Logs all messages
By default, the level is set to INFO. All messages above and including level INFO are sent to
the console. You can set and get these levels using the methods of the Logger class. In addition
to setting the level for the Logger, one has to set the level for the handler also.
public void setLevel(Level l)
public Level getLevel()
The Logger class provides methods similar to the names of the levels for logging messages.
All these methods take a String argument as shown:
public void severe(String msg) – for logging messages of SEVERE level.
public void warning(String msg) – for logging messages of WARNING level.
public void config(String msg) – for logging messages of CONFIG level.
public void info(String msg) – for logging messages of INFO level.
public void finest(String msg) – for logging messages of FINEST level.
public void finer(String msg) – for logging messages of finer level.
public void fine(String msg) – for logging messages of finer level.
220 Programming in Java
In addition to these, it also provides a method that sets the level as well as prints the message
on the console.
public void log(Level l,String msg)
Output
C:\javabook\programs\chap 7>java LoggingDemo
22 Feb, 2009 11:18:49 AM LoggingDemo demo
SEVERE: Shows Severe level of the Logger
Explanation
L1 Package java.util.logging has been im- argument sets the level of the logger and the second
ported, as the class Logger is a part of this package. argument is a String message that is the output on the
L3 Normally, we use one Logger per class. That is the console. The details of the output are shown below:
reason why we have created the Logger object as static. L7 An object of the class LoggingDemo has been
L4 The method demo() has been declared. declared.
L5 The log method of the Logger object has been L8 The method demo has been called using the
called to log the message to the console. The first LoggingDemo object.
Output Details
22 Feb, 2009 11:18:49AM LoggingDemo demo
Date Time of execution ClassName methodName where error occurred
SEVERE: Shows Severe level of the Logger
Level Message passed to constructor of Assertion Error
SUMMARY
This chapter focused on how to handle unusual Apart from using the predefined exception, you can
conditions/situations in Java. Exception handling is the code your own exceptions according to your own
key. Two types of exceptions have been defined: checked requirements. Exception chaining (introduced in JDK
and unchecked. All exceptions, whether checked or 1.4) wraps a particular exception into another.
unchecked, inherit from the parent class Throwable. Assertions (introduced in JDK 1.4) are helpful in
There are five keywords in exception handling, namely assuring the programmer about a particular condition
try, catch, throw, throws, and finally. using the assert keyword. They help in increasing the
Exception, Assertions, and Logging 221
reliability of a Java program. Logging features (part of Java 7 introduced the automatic resource management
java.util.logging package introduced in JDK 1.4) with the help of a new try block, i.e.,try-with-
help the user to debug his program. resource block. This chapter also highlights the new
syntax for compressing multiple catch blocks used in Java 7.
EXERCISES
Objective Questions
1. What are the two types of exceptions available (a) Exception (b) Assert
in Java? (c) Assertion (d) Assertion Error
(a) Checked and compiled 5. What is the result of attempting to compile and
(b) Unchecked and compiled execute the program?
(c) Checked and unchecked
(d) Compiled and non-compiled class Demo
{
2. The parent class of all the exceptions in Java is void show() throws ArithmeticEx
(a) Throwable (b) Throw ception{}
(c) Exception (d) Throws }
3. What is the result of attempting to compile and class Demo1 extends Demo {
execute the program? void show()
{
class Demo
System.out.println("In Demo1
{
Show");
void show() throws ClassNotFound
}
Exception{}
public static void main(String ar[])
}
{
class Demo2 extends Demo {
Demo1 d = new Demo1();
void show() throws IllegalAccess
d.show();
Exception,
}
ClassNotFoundException, Arithmetic
}
Exception
{ (a) Does not compile
System.out.println("In Demo1 (b) Compiles successfully
Show"); (c) Executes successfully and prints “In Demo1
} show”
public static void main(String ar[]) { (d) Complies but does not execute
try{
6. What is the result of attempting to compile and
Demo2 d = new Demo2();
execute the program?
d.show();
} class Test
catch(Exception e){} {
} } static void test() throws Runtime-
Exception
(a) Does not compile
{
(b) Compiles successfully
throw new ArithmeticException();
(c) Compiles successfully and prints “In Demo1 }
show” public static void main(String args[])
(d) Complies but does not execute {
4. If the assert statement returns false, what is try{
thrown? test();
222 Programming in Java
Review Questions
1. What are exceptions? How are they handled in 5. Explain the need for automatic resource
Java? management.
2. Explain logging in Java with all its levels. 6. What is a try-with-resources block and how
is it used?
3. Explain exception changing and environment.
7. Explain the Java 7 enhancement regarding
Write a program in support of your answer.
multiple catch clauses.
4. What is the difference between checked and 8. Explain in detail the Java 7 enhancements
unchecked exception? regarding re-throwing an exception.
Programming Exercises
1. Create a user-defined exception named Check- gumentexception, else print the addition of all
Argument to check the number of arguments the five numbers.
passed through command line. If the number of 2. Consider a Student examination database
arguments is less than five, throw the CheckAr- system that prints the marksheet of students.
Input the following from the command line:
Exception, Assertions, and Logging 223
8.1 INTRODUCTION
Until now, whatever programs we have discussed were sequential ones, i.e., each of them has a
beginning, an execution sequence, and an end. While the program is being executed, at any point
of time, there is a single line of execution. One thing that you must note that a thread in itself is
not a program, as it cannot run on its own. However, it can be embedded with any other program.
The concept of single thread is quite simple to understand. Things become somewhat complex
when there are multiple threads running simultaneously, each performing different tasks, within a
single program. This can be enabled by multithreading, where you can write programs containing
multiple paths of execution, running concurrently, within a single program. In other words, we
can say that a single program having multiple threads, executing concurrently, can be termed as
multithreaded program.
Let us go to the basics of multithreading, which is actually a form of multitasking. Multitasking
can either be process-based or thread-based. If we assume programs as processes, then process-
based multitasking is nothing but execution of more than one program concurrently. On the
other hand, thread-based multitasking is executing a program having more than one thread,
performing different tasks simultaneously. Processes are heavyweight tasks, while threads are
lightweight tasks. In process-based multitasking, different processes are different programs, thus
they share different address spaces. The context switching of CPU from one process to another
Multithreading in Java 225
requires more overhead as different address spaces are involved in the same. On the contrary,
in thread-based multitasking, different threads are part of the same program, thus they share the
same address space and context switching of CPU occurs within the program, i.e., within the
same address space. Obviously, this will require less overhead.
The objective of all forms of multitasking including multithreading is to utilize the idle time
of the CPU. Ideally a CPU should always be processing something. The idle time of CPU can
be minimized using multitasking.
Have you ever paid attention to one thing? When you prepare a document using a word
processor program, the spelling can also be checked simultaneously. This is one such example
of thread-based multitasking. While you type in the document, the CPU sits idle and waits for
you to enter characters but because of thread-based multitasking, the word processor minimizes
the CPU idle time somewhat by simultaneously involving the CPU in checking the spelling of
the text. From now onwards, we will call thread-based multitasking as multithreading.
Note Multithreading enables programs to have more than one execution paths (separate) which
execute concurrently. Each such path of execution is a thread. Through multithreading,
efficient utilization of system resources can be achieved, such as maximum utilization of CPU
cycles and minimizing idle time of CPU.
run() means, the instructions of the run() has been processed completely.
A thread can always be killed or interrupted by calling interrupt() method.
8.3 java.lang.THREAD
Creation of threads in Java is not as complex as the concept itself. There is a class named as
Thread class, which belongs to the java.lang package, declared as,
This class encapsulates any thread of execution. Threads are created as the instance of this class,
which contains run() methods in it. In fact the functionality of the thread can only be achieved
by overriding this run() method. A typical run() would have the following structure:
226 Programming in Java
This method is automatically invoked when a thread object is created and initiated using the
start() method. Some of the methods belonging to the Thread class, which help in manipulating
thread instances, are shown in Table 8.1.
Apart from these, some constructors are also defined in the Thread class. These constructors
can be classified in two different categories. We will discuss one category here and the other in
the next section when we will discuss about Runnable interface. The constructors responsible
for creating threads are
1. Thread()
2. Thread(String threadName)
3. Thread(ThreadGroup threadGroup, String threadName)
In the first constructor, you can see that there are no arguments, which simply means it uses the
default name and the thread group. In the second constructor, the name of the constructor can
be specified as String. While in the third, you can specify the thread group and thread name.
Output
Current thread: Thread[main, 5, main]
Renamed Thread: Thread[New Thread, 5, main]
228 Programming in Java
Explanation
L1 Class MainThreadDemo declared. Thread.currentThread()
L2 main method declared.
The reference to the current thread object (i.e., main)
L3 A reference to the current Thread is returned and
is returned by the currentThread() method and
is stored in the threadObj. Here the current thread is
stored in the reference previously declared.
the main thread itself. The reference is declared by
L4 The thread object (i.e., main) is passed to the
specifying the name of the class, i.e., Thread class
println method. The toString() method of the
in this case followed by the name for the reference,
Thread class is called by default, which displays the
which is done as in the following line of code:
first line of the output.
Thread threadObj L5 The setName() method of Thread class is used
We acquire a reference to the main thread by calling to change the name of the Thread. This example uses
the static method currentThread() of the Thread the setName() method to change the main thread’s
class using the following method call: name from main to New Thread.
If we see the output now, the information within the square brackets is the signature of the
thread. The first element in the bracket is the name of the thread. The second element signifies
the thread priority (explained later in the Chapter under the topic thread priority). The range for
setting the priority can be between 1 and 10; 1 for lowest priority 10 for highest priority and 5
for normal priority. The last element in the bracket is the group name for threads to which the
thread belongs. The state of collection of threads can be controlled by a data structure, known
as thread group. The thread group is automatically handled by the Java runtime system.
Starting New Thread The third part talks about the start() method, which is required to create
and initiate an instance of our Thread class. The following piece of code is responsible for the same:
The first line creates an instance of the class NewThread, where the object is just created. The
thread is in newborn state. Second line, which calls the start() method, moves the thread to
runnable state, where the Java Runtime will schedule the thread to run by invoking the run()
method. Now the thread is said to be in running state.
L19 Thread.sleep(400);
L20 }
L21 } catch(InterruptedException e){
L22 System.out.println("child thread 2 interrupted");
L23 }
L24 System.out.println("Exit from child thread 2");
L25 }
L26 }
L27 class ThreadThree extends Thread {
L27 public void run(){
L28 try {
L29 for(int k = 1; k <= 5; k++) {
L30 System.out.println("\tFrom child thread 3 : k =" +k);
L31 Thread.sleep(800);
L32 }
L33 } catch(InterruptedException e){
L34 System.out.println("child thread 3 interrupted");
L35 }
L36 System.out.println("Exit from child thread 3");
L37 }
L38 }
L39 class ThreadDemo {
L40 public static void main(String arg[]) {
L41 ThreadOne a = new ThreadOne();
L42 a.start();
L43 ThreadTwo b = new ThreadTwo();
L44 b.start();
L45 ThreadThree c = new ThreadThree();
L46 c.start();
L47 try {
L48 for(int m=1; m<=5; m++){
L49 System.out.println("\t From Main Thread : m =" +m);
L50 Thread.sleep(1200);
L51 }
L52 } catch (InterruptedException e) {
L53 System.out.println("Main interrupted");}
L54 System.out.println("Exit form main thread");
L55 }
L56 }
Output
From child thread 1 :i =1
From Main Thread : m =1
From child thread 2 : j =1
From child thread 3 : k =1
From child thread 2 : j =2
From child thread 1 :i =2
From child thread 3 : k =2
From child thread 2 : j =3
From Main Thread : m =2
From child thread 1 :i =3
Multithreading in Java 231
Explanation
L1 Class ThreadOne extends the Thread class, L40 main() method declared.
thus inheriting all the functions and members of the L41 Reference for ThreadOne class is created and
Thread class. stored in a.
L2–7 run() method, returning void is overridden. L42 The start() method is invoked on the thread
The for loop incrementing the counter variable, i, object a. This method puts the thread in a ready-to
is looped 5 times (L3). Each value of i is displayed execute state. As soon as the CPU is allocated to the
on the screen (L4) and before moving to the next thread by the thread scheduler, the run() method
value of i, the thread sleeps for 0.6 seconds (L6). for the thread is called automatically. As you can see
Thread.sleep() method throws an exception, in the example also, the run()method is not called
InterruptedException, so it should be within a
explicitly.
try…catch block.
L43–46 Just like creating the object for ThreadOne,
L14 Just like the class ThreadOne, a new class
we create the reference objects for ThreadTwo
ThreadTwo, extending the Thread class is declared.
and ThreadThree and store them in b and c ,
L15–20 run() method responsible for providing
respectively. L44 is responsible for starting the
the functionality of the thread of this class is
second thread pertaining to ThreadTwo class and L46
overridden. The code of this method is similar to that
of the run(), explained in the previous paragraph. is responsible for starting the third thread pertaining
L27 Third class, ThreadThree , extending the to ThreadThree class, thus resulting in invocation of
Thread class is declared. the corresponding run() methods.
L28–36 run() method for the third class’ thread L47–55 Certain functionalities, similar to the
is implemented, similar to the previously explained functionalities of the above child threads, are
run() methods. provided inside the main thread also. It has been made
L39 Class ThreadDemo encapsulating the main() to sleep for 1.2 seconds (L50), which has been kept
method is declared. This class, which acts as the more than the three child threads, so that the main
main thread, is responsible for spawning the other thread completes its execution at last, otherwise there
three child threads. is always a possibility for the system to get hung.
by implementing the Runnable interface. Before taking on the second method of implementing
Runnable interface, we must know the ins and outs of this interface. It is actually implemented
by class Thread in the package java.lang. This interface is declared public as,
public interface Runnable
The interface needs to be implemented by any class whose instance is to be executed by a thread.
The implementing class must also override a method named as run(), defined as the only method
in the Runnable interface as,
public void run( )
{
......
......
}
The object’s run() method is called automatically whenever the thread is scheduled for
execution by the thread scheduler. The functionality of the thread depends on the code written
within this run() method. One thing worth noting is that other methods can be called from within
run(). Not only this, use of other classes and declaration of variables, just like the main thread,
are also possible inside run(). The thread will stop as soon as the run() exits.
The question that arises here is, when and how shall we resort to the second method? The
approach to be undertaken is dependent on the requirement of the class. If the class requires
inheriting any other class, then obviously the Thread class cannot be inherited, as multiple
inheritance is not allowed in Java. So the obvious solution in this case is to use the interface,
i.e., Runnable. [Remember: any numbers of interfaces can be inherited by a class.]
Some other constructors belonging to the Thread class are worth mentioning here, as these
can be used while creating thread using Runnable interface.
Thread(Runnable threadObj)
Even if a thread is created, it will not start executing unless the start() method of the Thread
class is called.
Multithreading in Java 233
Output
Detail of child thread :Thread[Example Thread,5,main]
From Main Thread : m = 1
From child thread 1 :i = 1
From child thread 1 :i = 2
From child thread 1 :i = 3
From Main Thread : m = 2
From child thread 1 :i = 4
From Main Thread : m = 3
From child thread 1 :i = 5
Exit from child Thread 1
From Main Thread : m = 4
From Main Thread : m = 5
Exit from main thread
234 Programming in Java
Explanation
L1 A class, ThreadChild , implementing the loop five times to display the numbers from 1 to
Runnable interface is declared. This class is 5. After displaying each number on the screen, the
responsible for the creation of the child thread, thread sleeps for half a second. You can see the
spawning out of the main thread. try...catch block, which is placed to catch the
L2 A constructor, ThreadChild(), is declared. InterruptedException thrown by the sleep()
L3 Inside ThreadChild() constructor, a thread method.
object t is created. Passing this as the first L16 We intend to display the exit of the child thread
argument shows that the current class has inherited created inside the ThreadChild class.
the Runnable interface. It is this class’ object that L19 Class ThreadDemo2 containing the main thread
will tell what the thread is going to perform because is declared (L31).
it has overridden the run() method. L20–26 The main method is declared (L20). The
L5 The start() method is called, which starts the constructor ThreadChild() is instantiated (L21).
execution of the thread by invoking the run(). This instantiation invokes the constructor declared
L7–15 run() is declared (L7) . It will be called between L2–6. The try...catch block between
automatically whenever this thread is scheduled L22–26 constitutes the body of the main thread. A for
by the thread scheduler. [Remember: explicit call loop is declared to loop five times and it displays the
to run()will invoke it from the caller thread rather number from 1 to 5. After displaying each number
than its own thread]. A for loop is declared to on the screen, it sleeps for one second.
The enumeration Thread.State has the possible states of a Java thread in the underlying JVM.
At any time, a thread is said to be in one of the states mentioned below. Figure 8.1 shows the
various states in which a Java thread exists during its life. Some of the methods responsible for
the transition from one state to another are also shown. Obviously, the diagram is not exhaustive,
as it does not mention all such responsible methods. It is just an overview of a thread’s life.
New In this state, a new thread is created but not started. The following line of code is responsible
for the same (assuming ThreadDemo class has inherited the Thread class or Runnable interface):
Thread threadObj = new ThreadDemo();
Multithreading in Java 235
New
yield() wait()
sleep()
start() join()
New Thread Runnable Not Runnable
interrupt()
interrupt() interrupt()
Terminated
Dead
The above statement is responsible for creating a new Thread object. In ‘New’ state, no system
resource (such as CPU) is allotted to the newly born Thread object. From this state, the thread
can either be started (by using start() of Thread class) or stopped (by using interrupt() of
Thread class), thus moving to ‘Runnable’ or ‘Terminated’ state, respectively. No other method
apart from start() and interrupt() can be called from this state and if tried to do so, it would
cause an exception, IllegalThreadStateException.
Runnable In this state, a thread is ready for execution by the JVM. It represents the running
state of the thread, as well. Ready state of a thread can be defined as it is ready for execution
but it might be in the queue, waiting for the operating system to provide it the required resource,
like processor. Once a thread is actually being executed by the processor then it is termed as
“Running”. From ‘New’ state the thread might move to the ‘Runnable’ state on execution of
the following statements:
Thread threadObj = new ThreadDemo();
threadObj.start();
As soon as start() is called, the thread is allotted the system resource as per the scheduling
done by the Java Runtime Environment. Now the thread has entered into the runnable state.
In Fig. 8.1, no differentiation is made between a running thread and a runnable thread. Even
the running threads are made a part of the runnable state. But there is a difference between the
two. A running thread is the one which is being executed by the processor. Such a thread can
be called as the current thread. Runnable threads are those which are not actually running,
but are scheduled in queue to get the processor. The scheduling scheme, under which all the
236 Programming in Java
runnable threads are prioritized for sharing the processor, is implemented by the Java Runtime
system. However, when a thread moves to ‘Running’ from ‘Runnable’, the instructions of the
run() method are being executed sequentially. During this phase the processor can be forced to
relinquish its control over the thread, thus forcing it to be a part of the queue again by the use
of yield() method as shown in Fig. 8.1.
Not Runnable From runnable state, a thread might move to the not runnable state, as shown in
Fig. 8.1. This state is just a hypothetical state used by us to categorize the three valid states of
Java. A thread which is in any of these three states can be assumed to be in ‘not runnable’ state.
These three states are WAITING, TIMED_WAITING, and BLOCKED.
Waiting In this state, a thread is waiting indefinitely for another thread to perform a particular
action (i.e., notify). Threads can move into this state either by calling the methods Object.wait()
(without time out) or Thread.join() (without time out).
Timed_Waiting In this state, the thread is waiting for another thread to perform an action (notify)
up to a specified waiting time. A thread can get into this state by calling either of these methods:
Thread.sleep(), Object.wait(), and Thread.join() (all these methods should be called with
time out specified).
Blocked In this state, a resource cannot be accessed because it is being used by another thread.
A thread can get into this state by calling Object.wait() method.
Before proceeding further, we must discuss the concept of monitors in Java. This is taken
up in greater detail in Section 8.8. Monitor is an object that is a mutually exclusive lock on the
resource to be accessed. A monitor can be owned by only one thread at a time. When a thread
calls Object.wait() method, it releases all the acquired monitors and is put into WAITING
state, until some other thread enters the same monitor and calls notify()/notifyAll(). When
notify() is called, it wakes up a thread that called wait() on the same object. The method
notifyAll() will wake up all the threads that called wait() on the same object. The difference
between two methods is that, if notify() is used, then only one thread (selected by the JVM
scheduler) is granted the monitor and all other threads are put into BLOCKED state, whereas
if you use notifyAll(), it wakes up all the threads and puts them into ready state. The threads
that can execute, start executing, and the rest move into the waiting state.The three methods
mentioned above are final methods of the ObjectClass, so all classes have them.
final void wait() throws InterruptedException;
final void notify()
final void notifyAll()
Additional form of wait() where time can be specified for the thread to wait for that period,
is also available. It puts the thread in TIMED_WAITING state. We can easily figure out that a
WAITING state thread will always be dependent on an action performed by some other thread,
whereas a thread in TIMED_WAITING is not completely dependent on an action performed by
Multithreading in Java 237
some other thread, as in this case, the wait ends automatically after the completion of the time
out period. Similarly, if a thread has put itself into WAITING state by calling Thread.join()
method, then it will keep waiting until the specified thread terminates or the specified time
elapses. There seems to be no difference between sleep() and wait() as both of them do the
same job of making a thread wait for a specified time. The differences between the start methods
have been specified in Table 8.2.
Table 8.2 Difference between wait() and sleep()
Object.wait() Thread.sleep()
wait() belongs to Object class sleep() belongs to Thread class.
It can only be used from within the synchronized It can be used from outside the synchronized methods and
method or statements. statements.
Wait state can be terminated by calling Object. The sleep state can be terminated by invoking interrupt()
notify() method. method of the thread instance.
Object.wait() is used in concurrent thread Thread.sleep(int ms) is used wherever and whenever
access codes only. required method.
It stops the current thread execution and Thread.sleep(int ms) causes the current thread to suspend
releases the lock of the object. Now other execution for a specified number of milliseconds. This can let
threads can use this released object. other threads to use the resources being held by the previous
thread
Terminated
This state is reached when the thread has finished its execution. A thread can move to ‘Terminated’
state, from any of the above mentioned states. In this state, the thread is dead. The death of a
thread can either be natural or forceful. A thread dies naturally when it exits run() normally.
The normal exit from run() means the instructions of the run() has been processed completely.
For example, the for loop in the following method is a finite loop which would iterate 5 times
(i.e., from 1 to 5) and then exit.
public void run(){
for(int i = 1; i<= 5; i++)
{
System.out.println(“i =” +i);
Thread.sleep(500);
}
}
A thread with the above run() method will die naturally after the last statement of run()
completes. A thread can always be interrupted by using interrupt(). The following block of
code does the job of killing a thread by calling interrupt() method.
We can know the state of a particular thread by using getState() method. The following
program shows the usage of getState() and interrupt() methods.
238 Programming in Java
Output
C:\javabook\programs\chap 8>java ThreadInterrupt
Starting Thread: InterruptExample state: NEW
Thread running: InterruptExample state: RUNNABLE
Thread running: InterruptExample state: RUNNABLE
Thread running: InterruptExample state: RUNNABLE
Stopping Thread: InterruptExample state: TIMED_WAITING
InterruptExample state: TIMED_WAITING
Thread Interrupted: InterruptExample state: RUNNABLE
Thread exiting under request: InterruptExamplestate : RUNNABLE
Exiting application state: TERMINATED
Multithreading in Java 239
Explanation
L1 A thread class is created. Thread followed by the name of the thread and its
L2 A Boolean variable interrupt (similar to a state. The thread has just been created, so its state
flag) has been defined to check the thread interrupted will be NEW.
status. L18 Starts the thread by using the start() method
L3 A string instance variable name has been defined on the newly created thread instance in L16. The run
to assign a name to the thread. method for this thread will be called automatically
L4–6 Constructor for the class has been defined. as the thread is scheduled for execution (L7). As
This constructor sets the name of the thread by using the interrupt flag is initially false, the while loop
the super constructor call and assigns the argument in the run method will execute and L9 will keep on
value to the string variable name. executing.
L7 The run() method which states what the thread L19 The main thread is made to sleep for 3 seconds.
has to perform is overridden. So the other thread InterruptedExample will keep
L8 It checks the status of the interrupt flag and if on executing and sleeping (1 second only).
it is false, the while loop keeps on executing. L20 Shows a print statement that displays the
L9 It is a print statement that displays the name of Stopping Thread: followed by the name of the thread
the thread along with its state. The current state of the and its state. If you see the output, the state of the
thread is obtained using the method getState(). The thread displayed is TIMED_WAITING because the
state of a thread if enquired from a run method will InterruptedExample thread is sleeping for 1 second
always be RUNNABLE as the run method is only and the main thread is executing at this moment.
executed when a thread is executing. (See output) L21–22 The interrupt boolean variable is set to
L10–13 A try...catch block has been defined true and the InterruptedExample thread is inter-
because the thread is made to sleep for a second using rupted using interrupt(). Note that the Interrupt-
Thread.sleep(1000) method and the sleep method edThread is sleeping and if a thread is interrupted
may throw InterruptedException, if interrupted. while it is sleeping, an InterruptedException is
So it has to be caught. The throws keyword cannot generated. This exception will be caught at the catch
be used with the run method as the method is defined in L12 and this block will execute as soon as
overridden and the parent interface (Runnable) does the thread regains CPU, in other words is scheduled
not mention any throws clause with the definition of by the scheduler.
the run method. So during overriding, the definition L23 Shows a print statement that displays the name
of the method cannot be changed. If an exception of the thread and its state. If you see the output, the
is generated, it is caught by the catch defined in state of the thread is still TIMED_WAITING because
L12 and L13 is executed, which displays Thread the InterruptedExample thread is still not allowed
Interrupted: followed by the name of the thread to execute as the main thread is executing.
and its state (i.e. RUNNABLE). L24 The main thread is deliberately made to sleep
L14 It is the final print statement in the run to allow the other thread to execute. At this stage,
method that displays the thread exiting under request the control passes to catch in L12. L13 executes
followed by the name of the thread and its state, i.e., followed by L14 and then the run method exits.
RUNNABLE. This line will be executed after the L25 Shows a print statement that displays Exiting
while loop exits. Application followed by the state of the child thread
L15 It defines the starting point for the execution (created from main) i.e., InterruptedExample. The
of the program, i.e., the main method. run method for the thread InterruptedExample
L16 A new thread is created and the name for the has exited, so the state is now TERMINTAED (see
thread is passed as an argument in the constructor output).
of the thread. L26 The application is terminated using the exit
L17 Shows a print statement that displays Starting method of the System class.
240 Programming in Java
There was one more method, stop(), which has now been deprecated, used to terminate a
thread. The reason for this deprecation is that it throws a ThreadDeath object at the thread to kill
it. Apart from this, calling stop() method results in sudden termination of thread’s run() method,
which might lead to the results achieved by the thread program in inconsistent or undesirable
state.
Once it resumes from the blocked state, it will again preempt the low priority thread to which
it had relinquished its control earlier, thus forcing the low priority to move to the runnable state
from the running state.
Note Higher priority threads will always preempt the lower priority threads. Actually it depends on
how the priorities of threads set by the JVM are mapped to the operating system. It might
happen that a higher priority might not be considered higher by the operating system. So this
actually depends on the operating system and it varies from OS to another.
As shown in Table 8.3, the Thread class has a method setPriority(), responsible for setting
the priority of the thread by programmer. The signature of the method is
final void setPriority(int x)
where x specifies the value used to signify the thread’s priority. Thread class defines several
predefined priority constants (as static final variables) as shown in Table 8.3.
Table 8.3 Priority Constants and their Corresponding Value for Threads
Constant Value Meaning
MIN_PRIORITY 1 Max priority a thread can have
NORM_PRIORITY 5 Default priority a thread can have
MAX_PRIORITY 10 Min priority a thread can have
From the above table, it is clear that priority can be set in the form of values between 1 and
10. If this priority is not externally assigned, by default it is set to NORM_PRIORITY, i.e., 5.
A thread’s current priority can be obtained by the getPriority() of the thread class, which
returns an integer value.
Multithreading in Java 241
finalintgetPriority()
Here is an example that shows the use of priority constants and getPriority() method.
Output
Default Priority for thread 1 :5
Default Priority for thread 2 :5
Default Priority for thread 3 :5
New Priority set for thread 1 :1
New Priority set for thread 2 :5
New Priority set for thread 3 :10
All the Three threads start
from here From child thread
3 : k = 1 From child thread
2 : j = 1 From child thread
1 : i = 1 From child thread
3 : k = 2 From child thread
2 : j = 2 From child thread
1 : i = 2 From child thread
3 : k = 3 From child thread
2 : j = 3 From child thread
1 : i = 3 From child thread
3 : k = 4 From child thread
2 : j = 4 From child thread
1 : i = 4 From child thread
3 : k = 5 From child thread
2 : j = 5 From child thread
1 : i = 5
Exit from child thread 3
Exit from child thread 2
Exit from child thread 1
Explanation
L1–39 These lines have the details about declaring L40 Main thread class threadPriority is declared.
three different classes, ThreadOne, ThreadTwo, and L41 The main()method is declared.
ThreadThree , each extending the Thread class. L42–45 Reference objects for the three child thread
Each of these child thread classes have already been classes are created and stored in a, b, and c.
explained in Example 8.2.
Multithreading in Java 243
L45 Default priority for child thread one is L50 Similar to thread one, the object of child thread
displayed. You can see the use of getPriority() two invokes its setPriority() method to set the
method, which has been called using the object of priority of the thread to normal priority, i.e., 5.
ThreadOne class. This method returns the current L51 The object of child thread three is used to call
priority of the thread pertaining to ThreadOne class. its setPriority() method to set the priority of the
L46–47 Just like child thread one, the current thread to highest priority, i.e., 10.
L52–54 New priorities of the three children threads
priority of child thread two and child thread three
are displayed. Once more, getPriority() method
is displayed.
can prove to be instrumental for the purpose of
L49 Object a of child thread class, ThreadOne obtaining the newly set priorities of the threads.
invokes its setPriority() method to set the priority L57–59 From within the main thread, all the
for the execution of threads, so as to schedule the three threads started using the start() methods
threads externally. You can see that the priority for corresponding the thread objects. The respective run
thread one is set to minimum priority, i.e., 1, by () methods of the thread objects will be executed as
passing it as argument to setPriority(). and when the threads are scheduled for execution.
As far as the join() method is concerned, it waits until the thread on which it is called terminates.
It waits for the child thread to terminate and then joins the main thread. Apart from this, join()
method can also be used to specify the amount of time you want the child thread to wait before
terminating. Example 8.6 shows the use of these two methods.
Example 8.6 Use of join() in Forcing a Thread to Wait for Other’s Termination
L1 class ThreadJoin implements Runnable {
L2 String thread;
L3 Thread thrd;
244 Programming in Java
Output
Thread Status: Alive
Thread A: true
Thread B: true
Thread C: true
Multithreading in Java 245
Thread D: true
Threads Joining......
From child thread A :i = 1
From child thread A :i = 2
From child thread A :i = 3
Terminating thread: A
From child thread B :i = 1
From child thread B :i = 2
From child thread B :i = 3
Terminating thread: B
From child thread C :i = 1
From child thread C :i = 2
From child thread C :i = 3
Terminating thread: C
From child thread D :i = 1
From child thread D :i = 2
From child thread D :i = 3
Terminating thread: D
Thread Status: Alive
Thread A: false
Thread B: false
Thread C: false
Thread D: false
Terminating thread: main thread.
Explanation
thread. The join() method causes the main thread
(Only those lines relevant to the topic are explained.)
L28–32 After the threads are declared using the to wait for all child threads to complete execution
constructor of the MyThread class, the isAlive() before the main thread terminates.
method is called for each thread. The value returned L43–46 Again the isAlive() method is used
by the isAlive() method is then displayed on the with each thread’s object to check whether the child
screen. threads are alive or dead and the boolean values are
L35–38 The join() method is called for each
displayed on the screen.
8.9 SYNCHRONIZATION
There can be instances when two or more threads access a common resource, say a common
data or file. In order to maintain consistency, it becomes imperative that the resource is made
available to only one thread at a time. For example, there are two threads, one responsible for
writing to a file (here, a resource) and other for reading from the same file. If both the threads
start concurrently, both would try to access the file at the same time. Obviously, if the first thread
has not written the values completely, the values read by the second thread would be inconsistent.
Java has such inbuilt mechanism, which lets only one thread use a resource at a time, known
as synchronization. Usually, operating systems do provide for such mechanism, but Java has a
unique language level support for it.
How does it work? Many of you, having the knowledge of operating systems, would know
what semaphores are. Likewise, we have the concept of monitors here. Monitor is an object that
246 Programming in Java
is used as a mutually exclusive lock on the resource to be accessed. A monitor can be owned
by only one thread at a time. A thread enters the monitor as soon as it acquires the lock. All the
other threads cannot enter the locked monitor, unless it is unlocked or the first thread exits the
monitor. During this period, other threads are waiting for the lock on the monitor. If a thread
exits the monitor, it can again enter the same monitor at some later stage.
This synchronizing mechanism mentioned above can be achieved in Java in two ways:
(a) By using the synchronized keyword with the method definition (synchronized methods)
(b) By using the synchronized keyword with any block of code (synchronized statements)
8.9.1 Synchronized Methods
We can make a particular method synchronized by declaring it so, as under,
class Xyz {
synchronized anyMethod()
{
......
//method body
}
}
You can see the use of ‘synchronized’ prefixing the method declaration. Now, if ‘n’ number
of threads want to use the method, anyMethod(), the system will not allow them to do so. The
highest priority thread will lock the monitor for the method, making it inaccessible to other
threads. Once the thread locking for the monitor finishes its job, it releases the monitor for the
use of other waiting threads.
8.9.2 Synchronized Statements
We can synchronize a block of code by using the keyword synchronized. Just like synchronizing
a method, here the word synchronized is used before the block of code to be synchronized. This
synchronized statement must specify the object that provides the monitor lock. An example for
such a block is given below,
public void anyBlock()
{
synchronized (this)
{
......
//statement for the body of block
......
}
}
Explanation
L1 Defines a SusResThread class that implements assigning ‘true’ to the instance variable, suspended.
the Runnable interface. This class houses three L29–32 resThread() is declared, which is used for
methods, run(), susThread(), and resThread(). assigning ‘false’ to the instance variable, suspended.
L4 An instance variable, suspended, is declared, In L31, notify() is called to resume the processing
whose value is used to indicate whether or not the of the suspended thread.
thread is suspended. L35–51 The main() method of the SuspendResume
L10–19 run() is declared, which contains a for
class is declared, where an instance of SusResThread
loop that displays the value of the counter variable,
class is created, as shown in L36. The execution then
i. Each time the counter variable is displayed, the
thread pauses briefly due to the method sleep(1000). pauses for about a second because of sleep(1000)
In L15, it then enters a synchronized statement at L38, before calling susThread() and displaying
to determine whether the value of the suspended a message about the suspension of the thread on the
instance variable is ‘true’. If so, wait() is called, screen (L39). Similarly, it pauses for another second
which causes the thread to be suspended until because of another sleep (1000) at L41, before
notify() is called. calling resThread() (L42) and again displaying a
L26–28 susThread() is declared, which is used for message about the resumption of the thread on the
screen, as shown in L43.
We have already discussed about the methods, wait(), notify(), and notifyAll(). These are
the methods, which help the threads in communicating with each other. One important thing is
the use of synchronization in communication between threads, as the above three methods are
called from synchronized methods and synchronized statements.
The following example shows you how to use the above methods in an application. This
example defines four classes: the Carrier class, the Giver class, the Taker class, and the Comm
Thread class. The objective of the program is to have the Giver class give a value to the Taker
class through the use of a Carrier class. The Giver class places a value on the Carrier and then
waits until the Taker class retrieves the value before the Giver class places another value on the
queue.
L37 }
L38 }
L39 }
L40 class Taker implements Runnable {
L41 Carrier c;
L42 Taker (Carrier c){
L43 this.c = c;
L44 new Thread (this, "Taker thread").start();
L45 }
L46 public void run(){
L47 for (int i = 0; i< 5; i++){
L48 c.getValue();
L49 }
L50 }
L51 }
L52 class CommThread {
L53 public static void main(String args []){
L54 Carrier c = new Carrier ();
L55 new Giver (c);
L56 new Taker (c);
L57 }
L58 }
One thing worth noting is that the value placed on the Carrier by the Giver is retrieved by the
Taker. The Giver places the next value only when the previous value is retrieved by the Taker.
Output
Put: 0
Get: 0
Put: 1
Get: 1
Put: 2
Get: 2
Put: 3
Get: 3
Put: 4
Get: 4
Explanation
L1 The Carrier class is defined. (L11)). Once the value is assigned, putValue()
L2 Instance variable, communicatedValue, is used changes the value of the flag from ‘false’ to ‘true’
to store the value placed on the Carrier by the Giver. (L12), indicating there is a value on the Carrier.
L3 A flag variable of boolean type, busy , is L5–15 The value of the flag is used within the two
declared, which is used to check whether a value methods to make the thread that calls the method
has been placed on the Carrier. It is set to ‘false’ by wait until either there is a value on the Carrier or
default, which enables the Giver to place a value there is no value on the Carrier, depending on which
onto the Carrier. method is being called.
L4–15 putValue() is declared and defined (L4). L16–27 getValue() is defined (L16). This method
The purpose is to place a value on the Carrier (i.e., to is used to retrieve the value contained on the Carrier
assign a value to the communicated Value variables (i.e., to return the value of communicatedValue (L23)).
Multithreading in Java 251
L28–38 The thread class Giver is declared, which Taker class calls getValue() five times from within
implements Runnable (L28). This class declares an a for loop. Each call to getValue () is paused until
instance of the Carrier class (L29) and then calls the Giver class places an integer in the Carrier.
putValue() to place five integers on the Carrier L52–58 The main() method of the CommThread
(L36). Although the putValue () method is called class creates instances of the Carrier class (L45).
within a for loop, each integer is placed on the Notice that a reference to the instance of the Carrier
Carrier and then, there is a pause until the integer class is passed to both the constructors of the Giver
is retrieved by the Taker class. The Taker class is class and the Taker class. They use the instance of
very similar in design to the Giver class, except the the Carrier class for inter-thread communication.
L18 System.out.println(d);
L19 Thread.sleep(1000);
}
L20 catch(Exception e){}
}
}
}
Output
Explanation
L1 The java.util package is imported because we implementation for the thread. What the thread is
will be using Calendar and Date classes in this class going to perform will be implemented by the object of
which are part of the java.util package. Task class. In our earlier examples, we have used this
L2 Class TimeThreadDemo is declared keyword while creating threads because the current
L3 Instance variable of type Thread class is created object was providing the implementation for run()
within the class. in those cases and setting the task for the threads.
L4 Constructor for the class has been defined to start() method is invoked on the thread to put it in
accept a String argument which will be used to name a ready state where it can be scheduled by the thread
the thread created within the constructor. scheduler. Please note that this thread is a separate
L6–7 A thread is created by instantiating the thread now apart from the main thread.
Thread class and assigning it to the instance variable L8–9 main method is defined and the object of the
created in L3. The name of the thread (string TimeThreadDemo class is created within this method.
argument in L4) is passed within the constructor of This results in calling the constructor of the class
the Thread class along with the object responsible which instantiates the Thread object and implicitly
for telling what the thread is going to perform. The instantiation of the task class also occurs.
object of Task class has been passed within the L10 Class Task is defined to implement Runnable
constructor of the Thread class to indicate that the interface. The Runnable interface is inherited because
object will override the run method and will provide we want this class to override run() and tell the
Multithreading in Java 253
thread what is expected of it. We want this thread to a static method getInstance () which return an
perform a predefined set of task every second, i.e., instance of Calendar class initialized to the current
print the date and time which keeps on ticking like date and time.
a clock. These steps are implemented within run(). L17 Using the instance created in previous line,
L11–12 Instance variables of Calendar class and getTime() is invoked to return the date and time
Date classes are defined to get the current date and encapsulated as a Date object. This date object is
time. referenced by instance variable created in L12.
L13 run() is overridden. As soon as the thread L18 Prints the Date object.
created in L6 is scheduled by the scheduler, this L19 We deliberately provide a delay of one second
method is invoked automatically. using the Thread.sleep(1000) method to give it
L14 An infinite loop is created to print the time a feeling of a normal clock. The Thread sleeps for
indefinitely second on second. one second and return to its work of printing the
L15 try block is created within the infinite for date object.
loop. L20 catch block has been defined to catch the
L16 As Calendar is an abstract class, it cannot be InterruptedException that the sleep method
instantiated directly. The Calendar class provides might throw.
Note Please note that as the thread works in an infinite loop, the program will not terminate on its
own. It has to be terminated by pressing Ctrl+C at the DOS prompt.
SUMMARY
Java has the capability to support multithreading. creating a new thread: (i) by extending the thread class
Thread is a single sequential flow of execution. It or (ii) by implementing the runnable interface which is
is not a program in itself, but it can just be a part actually implemented by thread class. Thread.State
of a program. Multithreading enables to write such is an enumeration type, which has five possible states.
programs which can have more than one thread, each At any time, a thread is said to be in one of these
executing simultaneously. Multithreading ensures
five states. These states are: new, runnable, waiting,
running different parts of the same program (different
timed_waiting, and terminated.
threads) concurrently. It simply helps in increasing the
Threads in Java run on the concept of preemptive
efficiency of CPU, thus reducing its idle time.
scheduling, done by the Java runtime system by
Every program written in Java has at least one thread
assigning priority to every thread. It simply means,
running inside it, i.e., the main thread. At the start of
threads having higher priority are given preference
the program, JVM starts executing the main thread for getting executed over the threads having lower
which simply calls the main() method. The main class priority. Thus, we can say that the lower priority thread
supporting multithreading in Java is the Thread class, is preempted by higher priority thread. There is a
which is a part of java.lang package. Threads are facility in Java, to synchronize threads so as to avoid
created as the instances of this class, which contains unwarranted interleaving between them.
the run() method. Actually the functionality of the A thread can either die naturally or be forced to
thread can only be achieved by overriding this run() die. A thread dies naturally when it exits the run()
method in the class extending the Thread class. This method normally. The normal exit from run() means,
Thread class is made to inherit the abstract class Enum. the instructions of the run() have been processed
The Enum class is a common base class of all Java completely. A thread can always be killed or interrupted
language enumeration types. There are two ways of by calling interrupt() method.
254 Programming in Java
EXERCISES
Objective Questions
1. Which type of exception does a sleep() method 6. Which type of exception does a join() method
throw? throw?
(a) Arithmetic exception (a) Arithmetic exception
(b) Nullpointer exception (b) Null pointer exception
(c) Arrayindex out of bounds exception
(c) Array index out of bounds exception
(d) Interrupted exception
(d) Interrupted exception
2. Which state is entered once a thread is created?
(a) Ready (b) Running 7. Which interface is used to create a Thread?
(c) New (d) Terminated (a) Thread (b) Runnable
3. Which method is used to know the current state (c) Cloneable (d) Serializable
of a thread? 8. Which class is used to create a Thread?
(a) geThreadState() (a) Thread (b) Runnable
(b) getState()
(c) ThreadGroup (d) Synchronization
(c) get()
(d) getThreadCurrentState() 9. Which type of exception does an interrupt()
4. Which package contains Thread classes and method throw?
interfaces? (a) Arithmetic exception
(a) java.lang (b) Null pointer exception
(b) java.io (c) Array index out of bounds exception
(c) java.util (d) Interrupted exception
(d) java.thread
10. What is the priority assigned to all Java threads
5. Which of the following are termed as not runnable
by default?
states?
(a) 1 (b) 5
(a) READY (b) WAITING
(c) TIMED_WAITING (d) BLOCKED (c) 10 (d) unassigned
Review Questions
1. Define each of the following terms: 4. What is the purpose of calling the y i e l d ( )
(a) Thread method?
(b) Multithreading 5. What is multitasking? Is multithreading a form of
(c) Waiting state and Timed_waiting state
multitasking?
(d) Running state
(e) Preemptive scheduling 6. What is thread priority? How can it be set for a
( f ) Runnable interface thread?
(g) Monitor 7. What is synchronization and why is it important?
(h) Notify method 8. What is runnable interface? How can you use
( i ) Join() method this interface in creating threads?
( j ) Thread class
9. When should you extend the Thread class for
2. What is a thread? How do threads behave in
creating a thread?
Java?
3. Distinguish between preemptive scheduling and 10. If you create two threads in your program, how
non-preemptive scheduling. Which one does many threads actually run? Explain the complete
Java use? flow of execution of threads inside a program.
Multithreading in Java 255
11. Which method is responsible for creating the 12. Distinguish among each of the following means
body or giving the functionality to a thread in your of pausing threads:
program? Explain with an example program. wait() sleep()
yield()
Programming Exercises
1. Create and run a threaded class using Runnable 4. Write a Java program showing the actions from
interface. three threads. Use runnable interface to create
2. Write a Java program to demonstrate the the threads. Make sure that the main thread
execution of a high-priority thread and how it always executes last (Hint: use join()).
delays the execution of all lower-priority threads.
5. Write a program that uses thread synchronization
3. Write a Java program that demonstrates how a
to guarantee data integrity in a multithreaded
high-priority thread using sleep makes way for
the lower-priority threads to execute. application.
know about the new classes and interfaces in the new IO packages
9.1 INTRODUCTION
The two most important parts of a computer are input and output. It is the input that is processed
to generate output. Input/output classes form the core of any programming language. As of Java
1.4, there are two predefined packages named io (input/output) and nio (new I/O or non-blocking
i/o) which contain classes to perform I/O operations. java.io package deals with operations such
as reading/writing to console and reading/writing to files. The java.nio package contains classes
that support the classes in the java.io package and perform advanced operations such as buffering,
memory mapping, character encoding and decoding, pattern matching, and locking a file.
The java.io package provides separate classes for reading and writing data (byte and character
data). The Java I/O facility is based on streams. Stream is a continuous flow of data. In Java,
streams for both types of data have been defined: byte stream classes and character stream
classes. Byte stream classes deal with reading and writing of bytes to files, socket, etc. Character
stream classes deal with reading and writing of characters to files, socket, etc.
The java.io package contains two top level byte stream abstract classes: java.io.InputStream
(for reading bytes) and java.io.OutputStream (for writing bytes). It also contains two other
top level character stream abstract classes: java.io.Reader (for reading characters) and java.
io.Writer (for writing characters). The subclasses of these classes are actually used for reading
and writing data. We will discuss some of the subclasses in detail.
Input/Output, Serialization, and Cloning 257
Methods Description
int available() throws Returns the number of available bytes that can be read from
IOException an input stream.
void close() throws IOException Closes the input stream.
void mark(int readlimit) Makes a mark at the current position in the input stream.
readlimit defines after reading how many bytes this mark
is nullified.
boolean markSupported() mark() method works if this method returns true.
abstract int read() Reads the next byte from the input stream. Subclasses
provide implementation for this method. It returns the byte
read and –1 if EOF encountered.
int read(byte[] b) Reads bytes and stores them in the byte array b. It returns
the number of bytes read into the array and –1 if EOF
encountered.
int read(byte[] b, int off, Reads bytes and stores them in byte array b upto length (len)
int len) starting from offset (off) in b.
void reset() Resets the current pointer to the mark set by the mark()
method only if readlimit has not expired.
long skip(long n) Skips the specified number of bytes (n) and returns the
number of bytes actually skipped.
Methods Description
void close() Closes the output stream.
void flush() Flushes the output stream.
void write(byte b[]) Writes the contents of the byte array to output stream.
void write(byte b[], int off, Writes the specified number of bytes (len) to the output
int len) stream starting at offset (off) in b.
abstract void write(int b) Abstract method to write byte to the output stream. Sub-
classes to provide implementation.
Figures 9.1 and 9.2 show the hierarchy of classes (beneath input stream/output stream and reader/
writer) as well as the interfaces in java.io package that they inherit. These figures do not show
all the classes in java.io package. For all classes, refer JDK 6 documentation.
258 Programming in Java
Reader Writer
FilterReader
File Writer
FileReader
Output
For ‘Sample.txt’ file
C:\javabook\programs\chap09>java FileDemo sample.txt
File exists: true File can be read: true
File can be written: true
File can be executed: true
File name: sample.txt
parent of File: null
path of the File: sample.txt
Hidden File: false
length of the file: 105
last modified time: 1236860698637
it is a File: true
For ‘programs’ directory
C:\javabook\programs\chap09>java FileDemo
c:\javabook\programs
File exists: true
260 Programming in Java
Explanation
L1 To use File class, we need to import the of file in bytes.
package java.io. L14 lastModifiedTime() returns the time the
L4 File object is created and the file name/ file was last modified. The time was calculated in
directory name is passed to it through command line milliseconds since 1 January 1970, GMT 00:00:00.
argument. Some of the methods of the File class are L15 isFile() returns true if argument to File
used to know the properties of a file. All the methods object is a file.
have been called from the println method so that L16 isDirectory() returns true if argument to
their return values can be printed. File object is a directory. If it is, then the following
L5 exists() returns boolean value to indicate lines will be executed.
whether file/directory exists or not. L18 list() method is used to list all the directory
L6 canRead() returns boolean value to indicate and files within a directory and it returns them as a
whether file/directory can be read or not. string array.
L7 canWrite() returns boolean value to indicate L20 for-each loop is used to iterate through the
contents of the array one by one. L21–27 are executed
whether file/directory can be written or not.
for all the elements of the array.
L8 canExecute() returns boolean value to indicate
In the following lines, we find whether an element of
whether file/directory can be executed or not.
the array is a file or directory and print it accordingly.
L9 getName() returns the name of the file/
L21 File object is created for each and every
directory. element in the string array.
L10 getParent() returns the name of the directory L22 isDirectory() method of the file object is
of which the file/directory is a part of. used to find whether the element is a Directory or not.
L11 getPath() returns the complete path of file/ L23 Prints “it is a directory”.
directory (see output). L24 As we are creating a new File object in every
L12 isHidden() returns boolean value to indicate iteration, assigning null to the file object makes it
whether file is hidden or not. eligible for garbage collection.
L13 length() returns long value to indicate length L25–27 else prints, “it is a File” and null is
assigned to the File object.
Input/Output, Serialization, and Cloning 261
//Reading a file
L9 if(f.exists()){
L10 FileInputStream f1 = new FileInputStream(f);
L11 int num = f1.available();
L12 b = new byte[num];
L13 int n = f1.read(b);
L14 String s = new String(b);
L15 System.out.println("Contents of "+args[0]+ ":"+ s);
L16 f1.close();
L17 f = null; }
L18 else {
L19 System.out.println("File does not exist");
L20 System.exit(0); }
//writing to file
L21 f = new File(args[1]);
L22 if(!f.exists())
L23 System.out.println(args[1] + "is a New File");
L24 else
L25 System.out.println(args[1] + "File exists, will be overwritten");
L26 System.out.println("Opening File: "+ args[1]);
L27 FileOutputStream fs = new FileOutputStream(args[1]);
L28 System.out.println("File Opened, now writing contents");
L29 fs.write(b);
L30 fs.flush();
L31 System.out.println("contents written");
L32 System.out.println("Closing File");
L33 fs.close();
}}
Output
C:\javabook\programs\CHAP09~1>java ReadWriteDemo Sample.txt Demo.txt
Contents of Sample.txt: This is my sample file
Demo.txt is a New File
Opening File: Demo.txt
File Opened, now writing contents
contents written
Closing File
Input/Output, Serialization, and Cloning 263
Explanation
Reading a File This number should be equal to num.
L14 Directly displaying the bytes on to the standard
L4–6 if statement checks whether the number output would lead to confusion, as the contents of the
of command-line arguments is equal to 2. If the file are in the form of bytes. We want to read the file
condition is evaluated as true, it prints how to run as it was (readable string format). So we look up in
the program and terminates the program. the String class for a constructor that accepts byte
L7 File class object is created and the first array and converts it into a readable format. The one
command line argument (args[0], i.e., Sample.txt) we found is shown.
is passed as an argument to the constructor. We have L15 Prints the contents of the file.
mentioned only the name of the file, as the file exists L16 Closes the FileInputStream object.
in the current working directory. If you wish to refer L17 File object is assigned null.
to a file stored in some other directory, specify the L18 Else part of if in L9.
L19 Prints File does not exist.
full path of the file.
L20 Terminates the program.
L 8 An empty byte array is created. As we are using
byte stream classes, files will be read and written in Writing to a File
the form of bytes. The contents of the file will be read L21 Similar to L7. The only difference lies in the
into this byte array and later, the contents of the byte argument.
array will be written on to a different file. L22 Similar to L9.
L9 A check is made using exists() of the File L23 Gets printed if L22 returns the statement file
object to check whether the file (denoted by args[0], does not exist, else L25 is printed.
exists or not. If file exists, L10–17 are executed, L27 FileOutputStream object is created to
otherwise L19–20 are executed. write bytes to a file and filename (string argument,
L10 FileInputStream object is created to read i.e., args[1]) is passed to the constructor of the
FileOutputStream object. We could have passed
the contents of the file and the File class object
the file object also created in L21 (as done in the
(f) created in L7 is passed to the constructor of this
creation of FileInputStream object created in L11),
object.
but we wanted to show you that the constructor in
L11 The available() method of the f1 object is these classes are overloaded to accept different kinds
used to find the number of bytes that can be read from of argument.
the file. The return value is stored in num. L28 Shows statement to print “File Opened, now
L12 Now when we know the number of bytes in a writing contents”.
file (num), we create a byte array of that size so that L29 write method is used to write the entire byte
the bytes from the file can be read into this byte array. array to the file.
L13 read() is an overloaded method. It reads the L30 Flushes the contents to the file if any in the
entire contents of the file into the byte array. It returns output stream using the flush() method.
the number of bytes actually read into the byte array. L33 Closes the FileOutputStream.
264 Programming in Java
Output
C:\javabook\programs\chap 09>java ScannerDemo
Enter your name: Tom
Enter your age: 31
you entered Tom as your name
you entered 31 as your age
Explanation
L1 The java.util package is imported as Scanner L7 Print statement asking the user to enter his
class belongs to it. age.
L4 An object of the Scanner class is created L8 Using the Scanner class, we can directly read
and System.in is passed to the constructor of the a primitive value from the user. This line shows
object. nextInt()that reads directly int from the user.
L6 Reads the input from the user using nextLine() Similarly if required, nextByte(), nextDouble,
method of Scanner class and returns the string. nextFloat(), nextBoolean(), etc. can be used.
nextLine() keeps on taking the user input until the A list of methods of scanner class is shown in
user presses enter. Table 9.5.
Note System is a class in the java.lang package. This class has three predefined variables:
in, out, and err.System.in refers to standard input stream, more specifically keyboard
input. Together they give an object of type InputStream. System.out refers to standard
output stream, more specifically display device. Together they give an object of type
PrintStream which contains println() method. We have been using this method from
our first example (System.out.println()). System.err refers to standard error output
stream, more specifically display device. Together they give an object of type PrintStream.
Input/Output, Serialization, and Cloning 265
In Example 9.3, nextLine() has been used before nextInt( ). If nextInt() is used before
nextLine(), then the output is not what you would expect it to be. Let us take another example
to show what happens when nextLine is used after any of the nextInt or nextFloat methods.
Output
Explanation
We run this example with two sets of input to clarify is read using nextInt or nextFloat() or nextLong()
the differences. etc., the number is returned by the respective methods
L2 nextInt() returns the integers value typed till and methods return. The empty string with the
the delimiter which is a whitespace by default. carriage return is consumed by the nextLine() and
L4 The nextLine() method continues reading the returned. So it does not prompt for an input on L4 as
input till carriage return and returns it as a string. The the carriage return typed while reading integer input
carriage return is consumed and not appended to the for L2 is consumed by nextLine().
string. So when a nextLine() is used after a number
Note The first output of the program shows 12 is returned as an integer by nextInt() and user is
not prompted for value as carriage return is consumed by nextLine() and it returns. Similarly,
13 is returned as a float by nextFloat() and user is not prompted for any value for the same
reason explained above. The second output of the program clears the concept where 12 is
returned as an integer by nextInt() and 13 as a string by nextLine(). Similarly, 14 is returned
as a float by nextFloat() and 15 as a string by nextLine().
Input/Output, Serialization, and Cloning 267
Prior to JDK 5, BufferedReader was used to read inputs from the user. The following statements
show how to get the input from the user using the BufferedReader class.
try
{
. . .
Explanation
L1 BufferedReader object is created to get input converted to character stream and then the concept
from the user. The constructor of BufferedReader of buffering is used to enhance performance.
accepts an object of type InputStreamReader, which L2 readLine() of the BufferedReader class is
in turn accepts an argument of type InputStream used to read the input. It can throw an IOException,
(System.in). InputStream is a byte stream class so either place readLine() call in a try/catch block
and InputStreamReader is a character stream or specify throws in the method declaration using
class. So actually the byte stream is getting readLine().
Java 6 introduced the Console class in the java.io package for gathering user input from
the user and output it to the standard output. A list of methods of the console class is shown in
Table 9.6. Let us take an example to see the Console class.
Table 9.6 Methods of Console Class
Methods Description
void flush() Flushes the console and writes the buffered output immediately.
Console format(String fmt, Writes a formatted string to the console’s output stream using the
Object ... args) specified format string and arguments.
Console printf(String format, Writes a formatted string to the console’s output stream using
Object ... args) the specified format string and arguments (L10, Example 9.5).
Reader reader() Returns the unique Reader object associated with this console.
String readLine() Reads a single line of text from the console.
String readLine (String fmt, Provides a formatted prompt, then reads a single line of text from
Object ... args) the console (Lines 5, 7, and 9; Example 9.5).
char[] readPassword() Reads a password from the console with echoing disabled (L13,
Example 9.5).
char[] readPassword(String Provides a formatted prompt, then reads a password from the
fmt, Object ... args) console with echoing disabled.
Printwriter writer() Returns the unique PrintWriter object associated with this
console.
268 Programming in Java
Output
Enter your username: Tom
Welcome Tom. Hope You had a Nice Day.
Enter your Phone No.: 34343434
You entered 34343434 as your phone Number
Enter your Age: 31
Name: Tom, Age: 31, Phone No: 34343434
Enter your password
Explanation
L4 System class has a static method console() to s specifies strings.
return the Console object. c.printf("Welcome % 1$s. Hope You had a Nice Day.".user);
L5 readLine() is an overloaded method in the
Console class, used to read input from the user. The
Format String First argument
string argument is displayed on the console and then in the argu-ment list
program blocks for user input. The value entered by
the user method is returned as a string. So in place of %1$s, the value in the string user (i.e., Tom)
L6 Print statement, similar to C language, has been is placed while displaying on the console (see output).
added in this class, i.e., printf ("",""). The first L7 Similar to L5. The‘ \n’ is placed in the beginning
argument in the method ("Welcome %1$s. Hope you of the string to print it on a new line.
had a Nice Day") is the format string to be displayed L10 We have specifically added this line and
on the standard output. The value for %1$s is picked changed the order of the arguments in the argument
up from the arguments referred by the format string list so that you can better understand it.
which starts from the second argument of the method. c.printf("name: %3$s, Age: %2$s
We have only two arguments in this method, but if Phone No: %1$s",pno,age,user);
required, you can have more. First of all "name:" is printed followed by the
% sign is for specifying literals. third argument (%3$s), i.e., user (Tom), then
n$ specifies the argument index in the argument "Age:"followed by the second argument (%2$s), i.e.,
list. 1$ is the index of the first argument. 2$ is age (31) and lastly "Phone No.:"followed by the first
used to refer to the second argument, and so on. argument (%1$s), i.e., pno (34343434).
Input/Output, Serialization, and Cloning 269
L11 Another way of writing to the console is shown from the user without echoing it on to the screen. It
in this line. You can get the PrintWriter object using returns the password in a character array.
the writer() method of the Console class. L14 Similar to the previous print statements. But
L12 println() of PrintWriter is used to write to here, we have a character array that is to be displayed
the console, prompting the user to enter password. on the screen. To display the character array, we have
L13 Console class provides a unique method passed the character array to String class constructor
readPassword(), used for reading the passwords and then it is displayed.
Note The readLine() method returns a string. Suppose we want numeric input, in that case, the
string returned can be converted to its respective numeric values using certain static methods
of the wrapper classes in the java.lang package.
int using Integer.parseInt()
float using Float.parseFloat()
double using Double.parseDouble()
long using Long.parseLong()
byte using Byte.parseByte()
short using Short.parseShort()
Explanation
Reading a file
L4 File object is created and file name is passed as to read the file character by character or place the
a command line argument. entire file into a character array. This method throws
L5 Integer variable n is declared for reading an IOException in case of problem.
characters. L9 Integer variable n is cast to character and
L6 Checks whether the file exists or not. If it exists, printed.
L10 else clause of if statement defined in L6.
L7–9 are executed, else L11 is executed.
L7 FileReader object is created and File Writing to a file
object created in L4 is passed to it. If the file L12 FileWriter object is created and the second
referenced by the FileReader object does not exist, command line argument is passed to the constructor
a FileNotFoundException results. of the object. If the file exists, it is overwritten and
L8 A while loop that reads the file character by if does not, a new file is created.
character using read() of the FileReader object. This L13 A sample string is declared.
method returns the character read as an integer or –1 L14 The string is written to the file using write() of
if EOF is reached. The value read is put in variable n the Writer class. The write() method is overloaded
to accept character array, integer, and string.
and checked for equality to –1. read() is overloaded
L15 Closes the FileWriter object.
Output
C:\javabook\programs\chap09>java BufferedInOutStreamDemo sample.txt Demo.txt
Marked the stream
Contents of sample.txt: This is my sample file
Resetting the stream
Reading the stream again from the marked point
This is my sample file
Writing contents to : Demo.txt
Contents written
Explanation
L4 and 5 BufferedInputStream object is created the pointer to the marked point. The read operation
and the FileInputStream object created (L4) is will begin from the marked point after resetting the
passed to the constructor of BufferedInputStream stream. The n passed as an argument is the limit
object. The input is buffered and operations like mark which is the maximum number of bytes that can be
and reset are supported. mark() and reset() are the read before the mark expires. A reset in that case
methods of BufferedInputStream class. But why raises an IOException.
are we using BufferedInputStream class? Since, it L9 and 10 Two byte arrays have been created. One
is not possible to re-read the file with an object of for reading the content before the stream is reset and
FileInputStream, we use mark and reset operations the second one for reading the stream after it is reset.
to read the file again. L11 read method reads the entire file into the
L7 The stream is marked. The reset method sets byte array.
272 Programming in Java
L12 byte array is converted to string and displayed L21 FileOutputStream object is created and
on the standard output. filename is passed as argument.
L14 reset method is used to reset the stream to the L22 BufferedOutputStream object is created and
marked point. In our case, it is the beginning of file. OutputStream object (created in L21) is passed to it.
L16 read method again reads the entire file into L23 write method is used to write contents of
the second byte array. If the mark and reset methods byte array to file.
are not used, then it is not possible to read the file L25 Closes the output streams.
again using FileInputStream class and its methods.
Output
C:\javabook\programs\CHAP09~1>java BufferedReadWriteDemo Sample1.txt Demo2.txt
File opened: Sample1.txt
This is my sample file
Contents copied to: Demo2.txt
Input/Output, Serialization, and Cloning 273
Explanation
L5 FileReader object is created and file name L10 and 11 BufferedWriter object is created and
passed as an argument to the constructor of this class. FileWriter object is passed into the constructor of
L7 B u f f e r e d R e a d e r object is created and the BufferedWriter object.
FileReader object is passed to it. The BufferedReader L12 to 14 readLine() method of BufferedReader
object buffers the characters for efficiency purpose is used to read the String from the file whose name
and it also supports the mark and reset methods. has been specified while creating the FileReader
L8 PrintWriter object is created to write contents object. The return value is placed in the str and is
to the standard output ( system.out ). The true checked for equality to null. The loop continues until
specified as the constructor is for auto-flushing the str is null (EOF). The while loop prints the file line
output buffer. by line (L13) and then writes it to another File using
BufferedWriter object (L14).
Note Java 5 added an interface java.lang.Appendable which is implemented by the writer class.
This interface has three methods to append characters and string to the writer object. The
methods have the following forms:
public Writer append(char c)
public Writer append(CharSequence c)
public Writer append(CharSequence c, int start, int end)
Output
C:\javabook\programs\CHAP09~1>java RandomAccessFileDemo
Opening the file in read write mode
Appending contents to file
Contents appended
Reading the contents of the file....
This is my sample File
Contents appended using RandomAccessFile
Explanation
L5 An object of RandomAccessFile is created. length of the file as an agreement to seek method.
The filename is passed as the first argument and the L7 Shows the contents to be written to file.
second argument is the mode in which to open the L9 write() method of RandomAccessFile is
file. There are four modes that can be applied as a used to write bytes to file. Writing of bytes starts
string. If the file denoted by the first argument does from the position set by seek method in the
not exist, a FileNotFoundException results. The file. This method can throw an IOException.
L12 seek(0)sets the file pointer to the beginning
various modes are shown in Table 9.10.
of the file.
L6 seek (long pos) method is used to set the file L13–14 readLine() reads an entire line of text from
pointer at a particular position (pos) in the file. read/ file and puts it in str. This str is printed until str is null.
write begins from this point. We are setting the
L15 RandomAccessFile object is closed.
pointer to the end of file, as we have passed the entire
Mode Description
r File will be opened in read-only mode.
rw File will be opened in read–write mode. If a file does not exist, it will be created.
rws File is opened in read–write mode and every update in file contents and its metadata will be
synchronously written to the storage device.
rwd Similar to “rws” with the exception that any update in metadata is not synchronously written to
the storage device, thereby reducing the number of interactions with the storage device.
276 Programming in Java
Note nio stands for non-blocking io. A non-blocking i/o or asynchronous i/o operation is one in which
the program is not blocked waiting for the i/o operations to complete. Instead the other parts
of the program that do not require i/o can proceed further. The parts requiring input or outputs
would still be blocked or waiting for the i/o to finish.
nio package provides extensive support for buffer management that is used in our example
below. So let us first understand what is a buffer? A buffer is a container which can be used
to store the contents of the file or primitive data types like byte, short, char, int, long,
float and double. Buffer is an abstract superclass of ByteBuffer, ShortBuffer, CharBuffer,
IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer in java.nio package. We also use the
MappedByteBuffer class which is a subclass of ByteBuffer class and which represents a memory
mapped region of a file. A mapped buffer is obtained using the map method of the FileChannel
object as shown in the example below.
L23 fc1.close();
L24 fos.close();
}catch (Exception e){
System.out.println(e); }}}
Output
C:\javabook\programs\chap09>java ReadWriteUsingNIO
This is my sample File
C:\javabook\programs\chap09>edit samplenio.txt
welcome, writing to a file using nio package
Explanation
L1–3 Show the importing of packages. The java. 2. Position Point at which mapping in a file starts.
io, java.nio and java.nio.channels packages are This value cannot be negative.
imported. ByteBuffer and MappedByteBuffer classes 3. Size Size of the mapping. This value cannot be
are part of java.nio package and FileChannel class negative.
is a part of java.nio.channels package. L11 and 12 for loop to extract the characters from
L7 and 8 Using the getChannel() method of the mapped buffer through get method. Get method
FileInputStream object, a FileChannel object is returns the byte read and then advances the positions.
obtained. Now this channel actually represents a The byte value read is cast to character and printed.
connection to the file (Sample.txt). A FileChannel L13 and 14 closes the F i l e C h a n n e l and
object apart from reading and writing a file can FileInputStream objects.
(a) map the file to memory
Writing a String to a file
(b) lock the file
(c) read and write files at specified positions L15 String declared.
(d) you can force the file changes to be written to L16 and 17 Same as L7 and 8. The difference is
the storage device. that here, FileOutputStream object is used to obtain
L9 size() method returns the size of the file. the FileChannel object.
L10 Static method map of FileChannel class is used L18 java.nio package contains a class ByteBuffer
to get a MappedByteBuffer object. MappedByteBuffer used for storing bytes. The ByteBuffer class
object is a byte buffer whose content defines the has a static method allocate used for creating a
memory mapped file. The map method takes three ByteBuffer. This method accepts an argument that
arguments: sets the size of the buffer in bytes.
1. Mode Three modes for mapping are available. L19 The string is converted to byte array using the
(a) Read read only mapping (FileChannel. getBytes() method of the String class.
MapMode.READ_ONLY) L20 put method is used to transfer the bytes from
(b) Read-write ( FileChannel.MapMode. byte array to ByteBuffer.
READ_WRITE). If the contents of the buffer L21 flip method is used to set the position to the
are manipulated, then they are written to the beginning of the buffer. After the put operation, this
mapped file. method prepares the buffer for write operations.
(c) Private Buffer manipulations will not be L22 The ByteBuffer is written to the FileChannel
written to file. connected to the FileOutputStream.
MapMode is a static inner class in FileChannel class. L23 and 24 Closes the FileChannel object and
READ_ONLY, READ_WRITE, PRIVATE are static fields the FileOutputStream object.
within the class.
278 Programming in Java
L15 System.out.println("Executable:"+Files.isExecutable(file.getFileName()));
L16 System.out.println("Readable:"+Files.isReadable(file.getFileName()));
L17 System.out.println("Writable:"+Files.isWritable(file.getFileName()));
L18 System.out.println("Exists: "+Files.exists(file.getFileName()));
L19 System.out.println("Last Modified Time: "+Files.getLastModifiedTime(file.getFileName()));
L20 System.out.println("Size: "+Files.size(file.getFileName()) +" bytes");
L21 Path anotherFile=Paths.get("D:/javabook/chapter of java book/Second Edition/
programs/chap 9/ScannerInput.java");
// checks whether path starts with d:/javabook not D or
//DemoThis or chap 9
L22 System.out.println("Name starts with d:/javabook : "+ anotherFile.startsWith("d:/ja
vabook"));
L23 System.out.println("Another File exits : "+ Files.exists(anotherFile));
// checks whether two files in two paths are same
L24 System.out.println(file.getFileName() +" is same as "+ anotherFile.getFileName() + ":
"+Files.isSameFile(file.getFileName(),anotherFile.getFileName()));
// make a copy of the file
L25 Path copy = Paths.get("D:/javabook/chapter of java book/Second Edition/programs/chap
9/CopyOfDemoThis.java");
// static Path Files.copy(Path source, Path target, CopyOption... options)
// Copy a file to a target file.
// Apart from REPLACE_EXISTING - Replace an existing file if it exists.
// ATOMIC_MOVE - Move the file as an atomic file system operation.
// COPY_ATTRIBUTES - Copy attributes to the new file.
L26 System.out.println ("File Copied: "+ Files.copy (file.getFileName(),
copy.getFileName(),StandardCopyOption.REPLACE_EXISTING));
// read the contents of the copied file and prints it on the screen
L27 System.out.println(Files.readAllLines(copy.getFileName(),StandardCharsets.US_ASCII));
// rename a file in the same directory
L28 System.out.println (Files.move(copy.getFileName(),copy.getFileName().
resolveSibling("Renamed"+copy.getFileName()), StandardCopyOption.REPLACE_EXISTING));
// beacause file has been renamed so copy does not exists and thus only deleted
// method raises exception so we used deleteIfExists()
// delete a file
L29 System.out.println("Copy File deleted if existed "+Files.deleteIfExists(copy));
// check for deletion of file
L30 System.out.println(copy.getFileName() +" Exists: "+Files.exists(copy.getFile
Name()));
// traversing a directory
L31 try(DirectoryStream<Path>
ds=Files.newDirectoryStream(Paths.get("d:/javabook/chapter of java book/Second
Edition/programs/chap 9")))
280 Programming in Java
{
System.out.println("----------------------------------");
L32 System.out.println("Directory Listing: "+ds);
L33 for(Path iterate:ds)
{
L34 if(Files.isDirectory(iterate))
L35 System.out.println("Directory: "+iterate.getFileName());
L36 else
L37 System.out.println(iterate.getFileName());
}
}
L38 File f = file.toFile();
L39 System.out.println ("File object : "+f);
}
}
Output
Input/Output, Serialization, and Cloning 281
Explanation
L1–3 Imports the relevant packages so that the Files.size()—returns a long value indicating
new classes and interfaces in java.io and java.nio the size of the file in bytes.
packages can be used. All the above methods accept an argument, i.e.,
L6 get method of the Paths class is used specify the the file name or path as a Path object.
path of the file whose attributes need to be accessed L21 Creates another Path object.
and create a Path object. A few basic methods can be L22 Same as L11.
used on this Path object as well as this can be passed L23 Checks for the existence of the file as already
to some other methods as we will see. discussed.
L7–11 Shows the usage of various methods of Path L24 Checks whether two files are same using the
object to extract information about the path like static method is SameFile() of Files class. The two
files are passed as Path arguments to the method.
getNameCount —is used to extract the names
L25–26 Shows how to create a copy of a file. The
present in the path. Files.copy static method is used copy the contents
getFileSystem()—to know the files system on of a file into another. The general notation for the
which the files was created, copy method is as follows:
getFileName()—to know the name of the file Files.copy(Path source, Path target,
CopyOption... options)
getParent() – to know the parent of the path
The first two arguments are source and destination
object (file).
files as Path objects and last is the CopyOption
startsWith()—returns a boolean value to indicate object. The CopyOption interface is inherited by an
whether the path start with the string argument passed Enum, StandardCopyOption which has three Enum
to the method. The path starts with DemoThis.java constants. These can be specified as the last argument.
and not D or De (see Output). These constants are:
L12–20 Shows the usage of static methods of Files REPLACE_EXISTING—Replace an existing file
class to extract information about the file like. ATOMIC_MOVE—Move the file as an atomic file system
Files.isHidden()—returns a boolean value to operation.
indicate whether the file is hidden or not. COPY_ATTRIBUTES—Copy attributes to the new
Files.isDirectory()— returns a boolean value file.
to indicate whether the path refers to a directory L27 readAllLines method of the Files class is
or not. used to read all line of the Path object.
Files.isRegularFile() —returns a boolean L28 Shows how to rename a file. The method
requires three arguments source, destination, and
value to indicate whether the file is a regular file
copy options. Source and destination are Path objects.
or not. If you want to rename a file and keep it in the same
Files.isExecutable()—returns a boolean value directory then you can use the method as shown in
to indicate whether the file is executable or not. the program above. The destination Path object
Files.isReadable()—returns a boolean value (file name can be specified in it) can be specified
to indicate whether the file is readable or not. by using the resolveSibling method on the source
Files.isWriteable()—returns a boolean value Path object. In case you want to move a file to a new
to indicate whether the file is editable or not. directory (newdir as Path object) then the destination
Path object can be obtained by using the resolve
Files.exists()—returns a boolean value to method on the new directory Path object as shown
indicate whether the file exists or not. below keeping the file name same.
Files.getLastModifiedTime() —returns a Files.move(source, newdir.resolve(source.
FileTime object to indicate the files last modified getFileName()), REPLACE_EXISTING);
time.
Or any name can be specified.
282 Programming in Java
Some of the other methods of the Files class are shown in Table 9.11.
Table 9.11 Few methods of Files Class
Methods Description
long copy(InputStream in, Path target, Copies all bytes from an input stream to a file.
CopyOption... options)
Path copy(Path source, Path target, Copy Copy a file to a target file.
Option... options)
Path createDirectory(Path dir, File Creates a new directory.
Attribute<?>... attrs)
Path createFile(Path path, File Creates a new and empty file, failing if the file already exists.
Attribute<?>... attrs)
Path createLink(Path link, Creates a new link for an existing file.
Path existing)
Path createSymbolicLink(Path link, Creates a symbolic link to a target.
Path target, FileAttribute<?>... attrs)
Path createTempDirectory(Path dir, Creates a new directory in the specified directory, using the
String prefix, FileAttribute<?>... attrs) given prefix.
Path createTempDirectory(String prefix, Creates a new directory in the default temporary-file
File Attribute<?>... attrs) directory, using the given prefix.
void delete(Path path) Deletes a file.
boolean deleteIfExists(Path path) Deletes a file if it exists.
boolean exists(Path path, Tests whether a file exists.
LinkOption... options)
Path write(Path path, byte[] bytes, Open Writes bytes to a file.
Option... options)
Path setAttribute(Path path, Sets the value of a file attribute.
String attribute, Object value,
LinkOption... options)
Object getAttribute(Path path, Reads the value of a file attribute.
String attribute, LinkOption... options)
Path walkFileTree(Path start, Walks a file tree.
FileVisitor<? super Path> visitor)
(Contd)
Input/Output, Serialization, and Cloning 283
9.7 SERIALIZATION
Serialization is the process of converting an object to bytes so that its state can be made persistent.
The state is made persistent by writing the bytes to a file. De-serialization is the reverse of
serialization. It is the process of converting bytes back to object.
The question arises: Why should an object be made persistent? The state of object is defined by
its properties (value of the instance variables). Normally we create objects, work with them, and
when the job is done, they are garbage collected automatically. But suppose, we need the value
of the instance variables at a later point of time, then the values will not be available. So in this
case, serialization is helpful. A class that wants its objects to be serialized has to implement the
Serializable interface. This interface is empty. It does not contain any method. This interface is
implemented by the class to inform that the objects of that class can be serialized. The attributes
that we do not want to serialize are made transient, e.g. temperature. By default, static variables
of a class are also not serialized.
L21 fos.close();
L22 FileInputStream fis = new FileInputStream("Serialize");
L23 ObjectInputStream ois = new ObjectInputStream(fis);
L24 System.out.println("Deserializing Object......");
L25 DayTimeTemp c1 = (DayTimeTemp)ois.readObject();
L26 System.out.println("Temperature: " +c1.temperature);
L27 System.out.println("Day, Date & Time: " +c1.d.getTime());
L28 ois.close();
L29 fis.close();
}}
Output
C:\javabook\programs\CHAP09~1>java TestSerialization
Serializing Object......
Values to be serialized......
Time: Thu Mar 12 20:46:12 IST 2009
Object Serialized......
Deserializing Object......
Temperature: 0.0
Day, Date & Time: Thu Mar 12 20:46:12 IST 2009
Explanation
L1 io package is imported. L14 Now we need a class which can write object
L2 util package is imported as Calendar class to OutputStream. So the ObjectOutputStream object
is part of it. is created and the FileOutputStream object (L13)
L3 Class inherits the serializable interface. is passed to the constructor of ObjectOutputStream
L4 Reference variable of Calendar class is created. object.
L5 float transient variable is declared. The values L15 Prints "Serializing Object......".
in transient fields are not written during serialization. L16 Prints "Values to be serialized......".
L6 Constructor of the class has been defined and it L17 getTime() method of the Calendar class is
accepts two arguments: the Calendar object and the used to return the Date object. This Date object when
float value for temperature. printed results in a call to the toString() method of
L7 and L8 Instance variables are initialized with the Date class automatically. The toString method
the values passed in the constructor. of Date class returns a String containing current day
L9 Test class is created to serialize the DayTimeTemp (Sun), month (March), day of the month (15), time
class created in previous lines. (HH:MM:SS format), time zone (IST), and year
L11 As Calendar is an abstract class, it cannot be (2009) (see output).
instantiated directly. So getInstance()static method L18 writeObject(t) method is used to write the
of Calendar class is used to get Calendar instance. DayTimeTemp object t to the FileOutputStream
L12 An object of DayTimeTemp class is created and connected to it.
Calendar instance is passed to it along with a float L19 Prints "Object Serialized......".
value as temperature. This object t will be serialized. L20 and 21 Closes the ObjectOutputStream and
L13 For serialization, we need to write bytes to a FileOutputStream.
file. So we need a byte stream class which can write L22 We have to convert the bytes stored in the file
to a file. FileOutputStream has been chosen and it (serialize) back to the object. So for this purpose, we
is used to open the file ‘serialize’. If the file already need to first open the file for reading the bytes. That
exists, it will be overwritten and if does not exist, a is why, FileOutputStream object is created and the
new file will be created. filename is passed to the constructor of this object.
Input/Output, Serialization, and Cloning 285
L23 ObjectInputStream is used for de-serialization is not casted, an attempt to access the variables of
of objects. Its object is created and FileInputStream DayTimeTemp will result in a compile time error, as
object (L23) is passed to it. these variables are not a part of the Object class.
L24 Prints "Deserializing Object......". L27 Prints the temperature in the retrieved object,
L25 readObject() method is used to read the i.e., 0.0, as it was a transient field (see output).
object from the ObjectInputStream. This method L28: Same as L17 but in this line, the object used is
returns an object of type ‘Object’ which is casted to the de-serialized object.
type of your defined class, i.e., DayTimeTemp. If it L28 and 29 Closes the InputStream.
9.8 CLONING
Cloning is basically making copy of an existing object. There are two types of cloning: shallow
copy and deep copy. Shallow copy creates a new instance of the same class and copies all the
fields to the new instance and returns it. In case a class contains references to other classes as
instance variables, shallow copy does not create new object (for instance variables defined in
the class) when cloned, instead the objects (defined as instance variables in the class) are shared
in the original and cloned object. In deep copying the object references contained within the
original object are copied recursively and the important point is that they are different objects.
Note Serialization could also be used as an alternative to deep copying because serialization
includes deep copying implicitly.
Java offers two more ways to create objects, i.e., clone() and newInstance() apart from the
new operator. The newInstance() is a method of java.lang.Class class, it is commonly used by
class loaders and dynamic program extension. The clone() method is a member of Object class
and is used for creating copies of objects. Let us discuss the clone() method in detail.
The clone method is available to all the classes of Java as it is a part of the Object class. If
you wish to create a copy of an existing object then you can invoke the clone method on that
object provided the object inherits the Cloneable interface. The Cloneable interface is an empty
interface. A class that wants its objects to be cloned must implement the Cloneable interface. If
a class does not implement the Cloneable interface and clone method is invoked on its object,
then a CloneNotSupportedException is thrown. Otherwise it returns an exact copy of the object
as an Object reference. Let us take an example to show how cloning is done. The example below
illustrates shallow copying.
{
L5 try {
L6 return super.clone();
}
L7 catch(CloneNotSupportedException e)
{
L8 System.out.println(e);
L9 return null;
}
}
L10 public int increment()
{
L11 return ++value;
}
L12 public int getValue()
{
L13 return value;
}
L14 public void setValue(int v)
{
L15 value=v;
}
}// CloneDemo class ends here
L24 cd.increment();
Output
D:\javabook\Second Edition\programs>java TestClone
Value in original object: 23
Original object d: CloneDemo@18a992f
Cloned object cd: CloneDemo@4f1d0d
Value in Cloned object: 23
Value after increment in Cloned object: 24
Value in original object: 23
Explanation
L1 Class implements the Cloneable interface to L17 main method is declared.
signify that the objects of this class can be cloned. L18 An object of CloneDemo is created
L2 Declares an instance variable (see Fig. 9.3).
L3 Declares a constructor which initializes the L19 The value in the object created is obtained
instance variable. using the getValue method and printed (see output).
L4 Overrides the clone method of the Object class. L20 A clone of the original object (created in L18)
L5–6 Declares a try block with a call to the is created using the clone method. The return type
superclass clone() method from within itself of the clone method is Object so it returns the copy
(super.clone()).The clone method creates a copy of the cloned object as an Object which has to be
of the object from which it has been invoked with casted back to the CloneDemo to access the method
similar values for its instance members. The clone() and variables of that class (see Fig. 9.3).
method might throw CloneNotSupportedException if
L21–22 Prints both the objects: the original and the
the class did not implement the Cloneable interface.
cloned one to show that they are different objects. It
This clone method creates a copy of the object on
is evident from the output printed on the screen. The
which this method has been invoked. This copy is a
hexadecimal representation of the internal addresses
new object which is a replica of that object.
of the objects is not same. It clearly states that they
L7–9 Declares a catch block corresponding to the
are two different objects not referring to the same
try block to catch CloneNotSupportedException.
Lastly a null is returned in case an exception is memory location (see output and Fig. 9.3).
generated by the clone method. L23 Prints the value of the instance variable of the
L10–11 increment method is declared to increment cloned object, i.e., 23.
the value of the instance variable. L24 Increments the value of the instance variable
L12–13 getValue method is defined to return the of the cloned object.
value of the instance variable. L25 Prints the value of the instance variable of
L14–15 setValue method is defined to set the value the cloned object. Now the value is 24 (see output).
of the instance variable. L26 Prints the value of the instance variable of
L16 TestClone class is defined to test cloning of the original object, i.e., 23. The increment on the
CloneDemo objects. cloned object does not have any effect on the instance
variable of the original object.
Note The clone method is a protected method in the object class. Thus, only subclasses and
classes within a package are able to access it. In case you wish to make it accessible to any
class in any package, then you need to override it and declare it as a public method.
288 Programming in Java
The above class contains a primitive type value and when cloned the object contains its own
copy of the primitive type. Let us see what happens when the same class contains a reference
type.
L13 System.out.println(e);
L14 return null;
}
}
}
// class declared for Testing Cloning
L15 class TestClone
{
L16 public static void main(String args[])
{
L17 CloneDemo d = new CloneDemo();
L18 CloneDemo cd =(CloneDemo)d.clone();
L19 System.out.println("Original object d: " +d);
L20 System.out.println("Original object inner reference: " +d.br);
L21 d.br.value--;
L22 System.out.println("Original object inner reference instance variable: "+d.
br.value);
Output
D:\javabook\Second Edition\programs>java TestClone
Original object d: CloneDemo@c3c749
Original object inner reference: CloneReferenceTest@150bd4d
Original object inner reference instance variable: 11
Cloned object cd: CloneDemo@1bc4459
Cloned object inner reference: CloneReferenceTest@150bd4d
Cloned object inner reference instance variable: 11
Explanation
L1–4 Declares a class, i.e., CloneReferenceTest L7–8 Constructor for CloneDemo is declared. This
which will be used within the class CloneDemo. Earlier constructor initializes the instance variable of the class.
we used a primitive as an instance variable. In this So basically the reference variable (L6) is initialized
example we will be using a reference variable of class by creating an object of CloneReferenceTest and
CloneReferenceTest as an instance variable of class assigning it to the reference variable.
CloneDemo. This reference variable is instantiated L9–14 The clone method is overridden and imple-
within the constructor of class CloneReferenceTest. mented as in the previous example.
L5 Class CloneDemo is defined. This class inherits L15 For testing and cloning the object we have
the Cloneable interface as we want to create clone created a class TestClone as in the previous example.
of this class. L16 Main method declaration.
L6 Instance variable for the class if defined. It is L17–18 An object of class CloneDemo and its clone
basically a reference variable of type CloneRefer- is created. An object of class CloneDemo results in
enceTest. creation of an object of CloneReferenceTest auto-
290 Programming in Java
matically from within the constructor of CloneDemo L23–24 Prints the cloned object and the object
class. The CloneReferenceTest constructor initializes reference it is using (as its instance variable). The
its value instance field to 12. The return type of the hexadecimal representation of the internal addresses
clone method is Object so it returns the copy of the of the original and the cloned objects is not the same.
cloned object as an Object which has to be casted It clearly states that they are two different objects.
back to the CloneDemo to access the method and But the hex representation of the internal addresses of
variables of that class. the object references that both these objects are using
L19–20 Prints the original object and the object (their respective instance variables) is same. It means
reference it is using (as its instance variable). both original and cloned objects instance variable
object references are pointing to the same memory
L21 Instance variable in the original object is
location. A change in instance variable (value) of
decremented. This variable is contained within the CloneReferenceTest through original object (d)
class CloneReferenceTest. So to access the variable will be reflected when the instance variable will be
we use d.br.value where br being an instance accessed using cloned object (cd) (see Fig. 9.4).
member of d can be accessed using dot operator and L25 Prints the instance variables value using cloned
similarly for value instance variable of br. object. This value is similar to the value printed using
L22 Prints the decremented value of the instance original object for the reason explained above.
variable: value.
As we have seen from Example 9.13 that the object references contained within an object are
not copied during cloning instead they are shared. In case we want to clone object with all the
object references contained within the object, we should deep copy the object. For deep copying,
the object references (used within the class) should also implement the Cloneable interface and
override the clone method in their respective classes.
L3 CloneReferenceTest(int v)
{
L4 value = v;
}
L5 public Object clone()
{
L7 try {
L8 return super.clone();
}
L9 catch(CloneNotSupportedException e)
{
L10 System.out.println(e);
L11 return null;
}
}
}
L12 class CloneDeepDemo implements Cloneable
{
// reference of another class declared here
L14 CloneReferenceTest br;
L15 CloneDeepDemo()
{
L16 br = new CloneReferenceTest(12);
}
// clone method
L17 public Object clone()
{
L18 CloneDeepDemo cdd = null;
L19 try {
L20 cdd =(CloneDeepDemo) super.clone();
}
L21 catch(CloneNotSupportedException e)
{
L22 System.out.println(e); //return null;
}
L23 cdd.br =(CloneReferenceTest)br.clone();
L24 return cdd;
}
}
L25 class TestDeepClone
{
L26 public static void main(String args[])
{
L27 CloneDeepDemo d = new CloneDeepDemo();
L28 CloneDeepDemo cd = (CloneDeepDemo)d.clone();
L29 System.out.println("Original object d: "+d);
L30 System.out.println("Original object inner reference: "+d.br);
L31 d.br.value--;
L32 System.out.println("Original object inner reference instance variable:
"+d.br.value);
L33 System.out.println("Cloned object cd: "+cd);
L34 System.out.println("Cloned object inner reference: "+cd.br);
L35 System.out.println("Cloned object inner reference instance variable:
"+cd.br.value);
}
}
292 Programming in Java
Output
D:\javabook\Second Edition\programs>java TestDeepClone
Original object d: CloneDeepDemo@c3c749
Original object inner reference: CloneReferenceTest@150bd4d
Original object inner reference instance variable: 11
Cloned object cd: CloneDeepDemo@1bc4459
Cloned object inner reference: CloneReferenceTest@12b6651
Cloned object inner reference instance variable: 12
Explanation
L1–11 Class CloneReferenceTest is defined as in gives us a clone of CloneDeepDemo object (i.e.,
Example 9.14. The difference is that now it inherits d). In order to deep copy, all the references types
Cloneable interface and overrides the clone() within CloneDeepDemo should also be cloned so
method. It clearly signifies that this class objects on L24 we invoke the clone method on br (i.e., of
can also be cloned. The implementation of the clone CloneReferenceTest class) object to create a clone of
method is similar to that of previous programs. this object. It returns an object of type Object which is
L12 Declares CloneDeepDemo class similar to casted into CloneReferenceTest and stored in the br
CloneDemo of the previous program. The only instance variable of the cd object. Note that we have
difference lies in the implementation of the clone not enclosed L24 in the try catch block because the
method. clone method of CloneReferenceTest class includes
L17–24 We have to deep copy the object. So, an a try-catch and catches all exceptions thrown from
empty reference variable of class CloneDeepDemo is clone method (Fig. 9.5).
created and the clone method is invoked through L25–35 TestDeepClone class is declared. (Same
the existing CloneDeepDemo object i.e., d. This as TestClone of the previous program).
Objects in
Heap Memory
cd
Note Clone method should be applied only to mutable objects which are referenced by instance
variables of the cloned object. Objects whose state can change are mutable and whose state
cannot are immutable like String and wrapper classes.
Input/Output, Serialization, and Cloning 293
SUMMARY
JDK 1.4 introduced java.nio package in addition for establishing connection to file so that they can be
to the java.io package. The I/O in Java is based read, written, mapped, and locked. MappedByteBuffer
on streams: byte and character. A few classes in class provided in java.nio package is used for
both categories have been discussed in the chapter. mapping files. Serialization is used to convert object
These files show how to read and write data (both to bytes and de-serialization does the reverse. Java
7 introduced java.nio.file package and added new
byte and character) to files. RandomAccessFile class
classes like files and interfaces like Path to replace
is used for reading and writing a file randomly by
the legacy class like java.io.File. A new interface
setting the file pointer at a particular position in the SeekableByteChannel was also added in java.nio.
specified file. Java 6 introduced Console class for channels package which provides functionality similar
user input and output to the user. java.nio has a few to the java.io.RandomAccessFile, etc. This chapter
subpackages also like java.nio.channels (used for also discusses in detail about cloning—shallow and
creating channels to files). The FileChannel is used deep.
EXERCISES
Objective Questions
1. Which abstract class is the superclass of all import java.io.*;
classes used for reading characters? class Demo6{
(a) Reader (b) FileReader public static void main(String
(c) ByteReader (d) InputStream args[]){
Console c = System.console();
2. Which abstract class is the superclass of all
String x = c.readLine("Enter ur value");
classes used for writing bytes? int a = Integer.parseInt(x)+10;
(a) Writer (b) FileWriter c.printf("the value is %1$d",a);
(c) CharWriter (d) OutputStream }}
3. Name the class that allows reading of binary (a) ArithmeticException
representations of Java primitives from an input (b) NullPointerException
(c) IOException
byte stream.
(d) NumberFormatException
(a) DataWriter (b) FileWriter
7. What will happen when you try to compile and
(c) DataInputStream (d) DataOutputStream
run the following code?
4. Which of these classes are abstract?
(Assuming abc.txt exists in the current directory)
(a) FilterWriter (b) Reader import java.io.*;
(c) InputStream (d) All the above class Demo6{
5. Name the exception thrown by the read method public static void main(String
defined in the InputStream class. args[]){
(a) ArithmeticException FileInputStream f = new
FileInputStream("abc.txt");
(b) NullPointerException
System.out.println("size:"
(c) IOException
+f.available());
(d) IllegalAccessException
}}
6. What will happen when you try to compile and (a) does not compile
run the following code and pass the following at (b) compiles successfully but generates an
the user prompt–“MyValue”? exception at run time.
294 Programming in Java
Review Questions
1. Explain the utility of RandomAccessFile class with 4. Explain the following terms:
all its modes. (a) Memory mapping (b) Virtual memory
2. Explain in detail all the possible ways of taking (c) File channel
inputs from the user. 5. What is serialization and de-serialization? Why
is it required? Name the interface used for
3. Explain the difference between FileInputStream
serialization.
and BufferedInputStream. Show an example in
6. Explain Java 7 new io enhancements.
support of your answer.
7. Explain shallow copy and deep copying.
Programming Exercises
1. Write a program that lists all the files in a directory 6. Write a program that appends data to the file
including the files present in all its subdirectories using FileWriter class.
as well. Get name/path of the directory from the [Hint: Use a different constructor of
user through standard input. [Hint: Use recursion] FileWriter class]
2. Using classes under the Appendable interface, 7. Write a program that maps a file. Use this
append string data to a file. Get the name of the mapping to write contents to the file.
file from the user. [Use java.nio package]
3. Write a program to read the contents of a file byte 8. Create a class that has a static field x, a non-
by byte and copy it into another file. Get names static field y, and a transient field z. Initialize
of the files from the user through standard input. them through a constructor. Serialize the class
4. Write a program to read the contents of a file into and then deserialize it.
a character array and write it into another file. Get 9. Write a program to create a sequential file that
names of the files from the user through standard could store details about the employees of an
input. organization. Details include empId, empName,
empAge, empDept, and empSal. These are
5. Write a program that writes primitives (byte,
short, int, long) followed by the string “Starting provided through keyboard.
F i l e N o w ….” to the beginning of a file. 10. How many lines, words, and characters does a
[Hint: Use RandomAccessFile] file have? Write a program for the same.
Input/Output, Serialization, and Cloning 295
PROJECT WORK
Simulate an Employee database using files in Java. will be similar to the primary key in databases. For
This database contains name, address, phone number, searching, deleting, and updating a record, the user
designation, and salary. The provision of adding should be prompted to enter the Employee ID. Before
new record, deleting an existing record, searching deletion and updating, the user must be prompted for
a record, and updating a record should be provided. a confirmation, e.g.
An employee id should be automatically generated “Are you sure you want to delete the record? yes/no”.
whenever a new record is added. This employee id
understand the basic concept behind Set, HashSet, and TreeSet as also Map, HashMap, and
TreeMap
use collections class, enumeration, and iterator
understand the usage of random class
implement observer pattern using observer class and observable interface
understand runtime class
learn about reflection API
10.1 INTRODUCTION
Utility means usefulness. Utility classes are those that help in creation of other classes. The
java.util package contains utility classes such as Date, Calendar, Stack, LinkedList, and
StringTokenizer, etc. The classes in java.util package use collections, i.e., a group of objects.
Collection classes work on objects, i.e., they store/retrieve objects.
Note Primitives cannot be directly stored and retrieved in collections. Wrapper classes representing
primitives were created in java.lang package to work with collections.
The java.util package has an interface called collection. A collection supports a group of objects.
A collection may be ordered/unordered as well as some collections may possess duplicates while
others may not. This collection interface has sub-interfaces such as set, list, and queue. Figure 10.1
shows the inheritance hierarchy of collection interface. These interfaces have concrete subclasses
Generics, java.util, and other API 297
(Contd)
298 Programming in Java
Method Description
boolean removeAll Removes all the elements of this collection that are also contained in the
(Collection<?> c) specified collection.
boolean retainAll Retains only the elements in this collection that are contained in the
(Collection<?> c) specified collection.
int size() Returns the number of elements in this collection.
Object[]toArray() Returns an array containing all the elements in this collection. The return
type of array of object will be of type Object class.
<T> T[] toArray(T[] a) Creates an array containing all the elements in this collection. The return
type of the array of objects will be according to the type of objects in
the collection.
Note Figure 10.1 does not show all the interfaces in the collection. Refer JDK 6 documentation for
the complete interface list.
The java.lang.Iterable interface was added by JDK 1.5 and collection interface was made
to inherit it so that the objects can be iterated using a for-each loop. This interface provides a
method named iterator() that returns an iterator object to iterate all the objects in the collection.
The collection interface is implemented by an abstract class AbstractCollection, which is the
parent of all the collection classes and it implements almost all the methods of the collection
interface.
List interface refers to an ordered but duplicate collection of objects. We refer to a list as
ordered because the user has full control over the order in which an object is inserted into the
list. The top level class for list interface is an abstract class AbstractList (which is a subclass
of AbstractCollection). AbstractList implements almost all the methods of list interface (as
given in Table 10.2) and has three subclasses AbstractSequentialList, ArrayList, and Vector.
LinkedList class is subclass of AbstractSequentialList and its definition has been modified in
JDK 1.6 to implement the Queue interface. Methods of Queue interface are listed in Table 10.3.
Stack is a subclass of the vector class. We will discuss these classes later in the chapter.
Queue interface was added in JDK 1.5 to support the data structure. Queue operates in
FIFO (first in first out fashion). Elements inserted into the collection first are removed from
the collection first. It provides methods to examine elements at the head of the queue. This
interface is inherited by the Queue interface to support double-ended queue. These queues support
operations to add/remove/examine elements at both ends (head and tail) of the queue. Table 10.3
shows the methods of Queue interface.
Set is a collection that does not contain duplicate objects. This interface is implemented by
an abstract class AbstractSet which implements some of the methods of Set interface. The
concrete classes, HashSet, EnumSet, etc., are subclasses of AbstractSet. This interface is inherited
by SortedSet interface to access the element in a sorted order (ascending). The class TreeSet
inherits the SortedSet interface and the AbstractSet class. Table 10.4 shows the methods of Set
interface.
Map interface provides mapping of key/value pairs. These key/value pairs are unique. A static
inner interface named Entry is declared inside the Map interface for referring to each key/value
pair. This Map is inherited by an interface SortedMap to access the elements stored in Map in a sorted
order. AbstractMap class inherits the Map interface and provides implementation for most of the
Table 10.4 Methods of Set Interface
Methods Description
boolean add(E e) Adds the specified element to this set if it is not already present and
returns true, else false.
boolean addAll(Collection<? extends Adds all the elements in the specified collection to this set if they
E> c) are not already present, and returns true if set is changed, else false.
void clear() Clears the set by removing all the elements from this set.
boolean contains(Object o) Returns true if this set contains the specified object.
boolean containsAll(Collection<?> c) Returns true if this set contains all the elements of the specified
collection.
boolean equals(Object o) Compares the specified object with this set for equality.
int hashCode() Returns the hash code value for this set.
boolean isEmpty() Returns true if this set is empty.
Iterator<E> iterator() Returns an iterator over the elements in this set.
boolean remove(Object o) Removes the specified element from this set if it is present.
boolean removeAll(Collection<?> c) Removes from this set all its elements that are contained in the
specified collection.
boolean retainAll(Collection<?> c) Retains only the elements in this set that are contained in the specified
collection.
int size() Returns the number of elements in the set.
Object[]toArray() Returns an array containing all the elements in this set. The return
type of array of objects will be of type Object class.
<T> T[]toArray(T[] a) Creates an array containing all the elements in this set. The return
type of the array of objects will be according to the type of objects
in the collection.
Generics, java.util, and other API 301
methods in the interface. This class is inherited by concrete classes such as HashMap, EnumMap,
etc. TreeMap also inherits this class as well as the interface SortedMap.
Most of the interfaces and classes in the java.util package use generics. This is evident from
the syntax (e.g.,<E>, <?>, <? extends E>) used in most of the interface and class declaration as
well as some of the methods. So first let us discuss the concepts behind generics.
10.2 GENERICS
This feature was added in Java 5 with an aim to provide strict-type checking at compile time.
Generic feature also allows same class to be used by many different collections of objects such as
string, integer, etc. Consider the following example, where we have created three classes named
A, B, and GenericTest. The class GenericTest has a collection of ArrayList class to hold objects.
The objects of A and B are placed in it and later we try to retrieve them. When we try to compile
the program, two notes appear at the DOS prompt asking the user to recompile the program
specifying the –Xlint:unchecked option of javac. This option is used to show all lint warning,
specifically the unchecked warnings (as shown in the section ‘what happens while compiling
the program?’ below). These warnings are appearing as the code does not use the newer generic
syntax. These warnings can be suppressed if we compile the program using the –source option
and specify the JDK version prior to 1.5 (i.e., javac –source 1.4 GenericTest.java).
Output
C:\javabook\programs\chap 10>java GenericTest
Class A Object
Class A Object
Exception in thread "main" java.lang.ClassCastException: B cannot be cast to A
at GenericTest.main(GenericTest.java:21)
Explanation
L1 Import java.util package. L13–15 A while loop to iterate the collection
L2–5 Two classes named A and B are defined with one by one. The hasNext() method tells whether
their own toString() methods. the collection has more elements or not. The loop
L6 Class GenericTest defined. continues till the time collection has more elements
L7 main method is defined within it. to iterate. The next()method returns the next object
L8 An object of ArrayList class is created. This in the collection. The return type of next() method
object will act as a container for other objects.
is an object of type Object (Parent class). This object
ArrayList supports the functionality of dynamic
is cast to A and then printed. When you try to run the
array. Array have a limitation that they cannot grow/
shrink in size but ArrayList objects can grow and program for the first two iterations, the cast is legal
shrink in size as and when required. as the object retrieved is of type A. But in the third
L9–11 Using the add method, objects are added to iteration the object retrieved is of type B, so the cast is
the ArrayList. Two objects of class A are added and illegal. That is why a ClassCastException results as
one object of B is added to collection. shown in the output. (It is for this very reason that we
L12 An Iterator object is obtained using iterator() have received unchecked warnings on compilation
method to iterate the collection one by one. of the program).
Note The problem occurred because there was no restriction on the type of objects that can be put
into a collection. In the earlier example we had put objects of A as well as B into the collection
and we are casting all objects into A which raised an alarm at runtime. It would be much better
to check at compile-time what goes into a collection so that no exception occurs at run time.
Generics, java.util, and other API 303
If we could ensure only objects of A should go into the collection then the problem can be
solved and that is where generics help. Most of the interfaces, classes as well as some of
the methods have been modified to use generic syntax. The generic declaration of list is as
follows:
List<E> v = new ArrayList<E>();
//This E has been replaced by A as shown. Normally single Capital
//character are used to denote generic Formal parameterized types
//refer JDK6 docs for details
List<A> v = new ArrayList<A>();
// a List of objects of A (actual parameter)
The name placed in the angle brackets (commonly known as specifying parameterized type) is
class name whose objects we want to put into a collection. Now this collection will not contain
objects of class other than the class-name mentioned in the angle brackets. For example, if we
try to insert an object of type B into collection ‘v’ (after using parameterized types), a compile
time error results.
Note that the list now contains only objects of type ‘A’ and the compiler assures us of this.
So is the cast on L14 really required? Well logically it should not be required but if you remove
the cast on L14, the compiler complains about it. Why? The reason is we did parameterize the
list but we did not parameterize the iterator which continued to return an object of type object on
invocation of the next method. Similar to list, iterator also uses the generic parameterized types.
So if we change L12 as shown, the problem gets solved and the cast can now be removed safely.
Iterator<A> en = v.iterator();
while(en.hasNext())
{
A o = en.next();
System.out.println(o);
}
Also note that if you rewrite the program that uses the generics parameterized types the
warnings are all gone.
Output
C:\javabook\programs\chap 10>java ParamArgsGeneric
Hello
Generics
Explanation
L3 The method getList() returns a List object L8 Shows a method print() accepting a List that
that holds only string objects. should hold only string objects.
10.2.2 Wildcards
In Example 10.2, if we change L13 as follows:
List<Object> l = pag.getList();
Anybody would consider it legal arguing Object is the superclass of String so the assignment
should be legal, but that is not the case. A List of Object is not a List of String. Why?
Generics, java.util, and other API 305
Consider the case if a List of String is a List of Object that means the above modified L13
is supposedly working. Then we could also insert lines in the program to add objects of type
Object to the List. Now when we retrieve them and try to store in a List of String it gives a
cast exception because we are trying to store an Object into a String. So a List of Object is not
a List of String and vice versa.
If you want to be flexible in using the classes as they were used earlier (i.e., without
parameterized types), then either you will have to suppress the warnings or you will have to be
rigid in using the collection of a particular type. Well, there is a midway wherein we can use the
collection to hold different types of object not just a particular type using generic syntax. This
is possible with the help of wildcards, i.e.,‘?’. Let us take a look at how wildcards can be used.
Output
C:\javabook\programs\chap 10>java ParamArgsGeneric
Hello
Generics
1
2
3
306 Programming in Java
Explanation
L3 The getList method returns a list of unknowns, L9 The iterator object obtained, can hold any
i.e., List<?>. Just to show you that list of unknown type of objects to be iterated as the wildcard has
can be returned from a method we have used this been specified. Iterator<?> i=c.iterator();
syntax here. In Example 10.2 we had created an iterator of
L4 An ArrayList of string is created. string objects specifically so it could iterate only
L8 Method print has been defined to accept a on a collection of string. Iterator<String> i=c.
collection that can hold any type of object. You iterator();
would probably think that a collection holding L10–11 Loops through the iterator and prints any
any type of object would also be rewritten as type of collection.
Collection<Object> but that is not the case as
L13 The getList method is called to return a
collection in the form of a list of any type of objects.
explained earlier. This method (as shown in the
The return list is captured in a list of unknowns, i.e.,
example) prints a list of strings as well as integers.
List<?>.
Note ? specifies unknown type, but this unknown type will be a subclass of X. So in this case we
know that this unknown type is either X or one of its subclasses.
In the following example we have created three classes A, B, and C. Class B inherits from A. C is
an independent class. Now let us see how bounded wildcards place a restriction on collection
of objects.
L4 class C {}
L10 System.out.println(i.next());
}
L11 public static void main(String args[]){
L12 BoundedWildcard pag = new BoundedWildcard();
L13 List<B> li = new ArrayList<B>();
L14 li.add(new B());
L15 li.add(new B());
L16 pag.print(li);
L17 List<A> la = new ArrayList<A>();
L18 la.add(new A());
L19 la.add(new A());
L20 pag.print(la);
L21 List<C> lc = new ArrayList<C>();
L22 lc.add(new C());
L23 lc.add(new C());
Output
C:\javabook\programs\chap 10>java BoundedWildcard
class B
class B
class A
class A
Explanation
L6 Shows a method print that accepts any using add method and the list is passed to the print
unknown type (?) of objects with the restriction method. The print method accepts the list as objects
that it must either be an object of A or an object of are of type A.
subclass of A. L21–24 A third List collection is created to hold
L13–16 A list collection is created to hold objects objects of class C only. The object of C are added using
of class B only. The object of B are added using add
add method and the List is not passed to the print
method and the list is passed to the print method. The
print method accepts the list as B is a subclass of A. method as it will not accept this List because C is
L17–20 Another List collection is created to not a subclass of A. we have specifically commented
hold objects of class A only. The object of A are added L24 because it is illegal.
Now if you revisit Tables 10.1 to 10.4, you will realize most of the methods defined in the
interface return and accept generic types.
10.2.4 Defining Your Own Generic Classes
You can create your own classes that use generic syntax. For using a generic syntax in your
classes, a normal naming convention should be followed for specifying parameterized types. The
naming convention is a single capital letter used for specifying parameterized types. For example,
308 Programming in Java
T is for specifying any type. The letter E has been used in the Java collection API extensively
to denote collection elements. In Map, the alphabet K is for keys and V is for values. Let us take
an example to see how to use generics in user defined classes. In the following example we will
create a class that will hold objects of a particular type and we can get and set (change) the object.
Output
C:\javabook\programs\chap 10>java TestGeneric
The User Defined Generic class holds Integer Object
Value: 1
New Value: 3
The User Defined Generic class holds String Object
Value: User Defined Generics
Explanation
L1 We have created a class named A that accepts this class and the type of this var will be determined
a parameterized type T. This class will hold objects by the parameterized type.
of only a particular type ‘T’. L3 and 4 Default constructor for the class has been
L2 An instance variable var has been defined in defined which assigns null to the var.
Generics, java.util, and other API 309
L5 and 6 Parameterized constructor is defined that L12 getVar() is used to return the value of var.
takes an argument of type T and assigns it to var. L13 An integer object is passed in the setVar(T
L7 and 8 getVar() method is defined to return the a)method.
var instance variable. The return type of the method L14 getVar() is used to return the new value of
has to be T as the type of var is still unknown. var.
L9 and 10 setVar(T a) method has been defined L15 We create another object of A and specify the
to set and mutate the value of var. The method type of object that A will hold as string now. (T now
accepts an argument of type T. automatically becomes a string). The type of var is
L11 We create an object of A and specify the now string. The return type of getVar() is string
type of object that A will hold as integer. (T is now and the setVar (String a) method now accepts an
automatically an integer). The type of var is now argument of type String.
integer. The return type of getVar() is integer and L16 getVar() is used to return the value of var
the setVar(Integer a) method now accepts an initialized by passing string in the parameterized
argument of type integer. constructor.
Output
C:\javabook\programs\chap 10>java LinkedListDemo
Hello
Linked List
Demo
null
Object popped: 3
Object popped: 2
Object popped: 1
Object popped: 4
Queue : [1, 2, 3, 4]
head of queue: 1
head of queue removed and returned: 1
Queue : [2, 3, 4]
Double ended Queue : [0, 2, 3, 4]
Double ended Queue : [0, 2, 3, 4, 5]
head of queue removed and returned: 0
tail of Queue removed and returned: 5
Double ended Queue : [2, 3, 4]
Explanation
L1 A linked list of String is created. L6 for-each loop is used to iterate through each
L2–5 Objects of type String are added to the element of the linked list. The next element of linked
linked list using add() method. This method adds list is assigned to s in every iteration and then it is
elements to the end of the list and returns a boolean printed.
to indicate the element has been added to the list. L7–15 Show how linked list acts as a stack.
Generics, java.util, and other API 311
L7 A new linked list is created which holds Integer L22 The first element of the list is returned (but
objects. the element is not removed from the list) by the
L8–10 The push method is used to add elements peek method.
at the head of the list. (push method is used to push L23 poll method is used to return and remove the
contents to the top of the stack). Top of the stack is first element of the list.
now 3 and bottom is 1. L24 Prints the list (see output).
L11 add method is used to add contents to the end L25–31 Show that a LinkedList can be used as a
of the list. So the new bottom of the stack now is 4. double ended queue. A double ended queue is one
L12–15 pop operation of the stack is used to that supports addition and deletion from both ends.
remove the top of the stack. The first pop operation L25 addFirst() method adds the element at the
removes 3, the second one 2, third 1, and last pop head of the list.
L26 Prints the list (see output).
results in 4 (see output).
L27 addLast method is used to add element at
L16–31 Shows how linked list can be used as a
the end of the list.
queue and a double-ended queue.
L28 Prints the list (see output).
L16 A new linked list is created which holds Long L29 removeFirst() method removes the
objects. element at the head of the list.
L17–20 Elements are added to the end of the list L30 removeLast() method removes the element
using the add method. at the end of the list.
L21 Prints the list. L31 Prints the list (see output).
10.4 SET
Set is a collection that does not contain duplicates. Set collection in java.util models the
mathematical concept set. The concepts of union, intersection, and the difference of a set are
available in the Set interface and supported by its subclasses. We will discuss two classes under
this interface, i.e., HashSet and TreeSet. TreeSet is a sorted collection as it inherits the SortedSet
interface (sub-interface of Set), whereas HashSet is not a sorted collection. HashSet uses the
concept of hashing.
Note Hashing is a technique to quickly find, add, and remove elements from a collection. This
technique is useful in situations like we have a directory of words and we need to find a
particular word. A directory would contain thousands and thousands of words. If we want
to search a word; matching each and every word with the word we wanted to search would
consume a lot of time.
Hashing stores the data in such a way that retrieval of data is fast. It uses a function (hash
function) to create an index (hash code) and this index is used to narrow down the search.
These indexes are maintained in a hash table, as shown in Fig. 10.2.
The hash table is an array of linked list. To find a place in the bucket array, the index is
divided by the total number of buckets in the array. The remainder that we get is the position
of the element in the array. If no element is present at that position in the bucket then it is
added else a collision occurs. If bucket is full, then also a collision occurs and the table has
to be rehashed. Actually the load factor (i.e., n/m where n is the number of items to be stored
and m is the size of the bucket) determines when a table needs to be rehashed. The default
value for load factor is 0.75; it means when the table is 75% full, it will be rehashed and the
bucket size will be doubled.
312 Programming in Java
Note
L23 hs.retainAll(hs1);
L24 System.out.println("Intersection of hs and hs1: " +hs);
//Difference
L25 hs.removeAll(hs1);
L26 System.out.println("Difference of hs and hs1: " +hs);
//Union
L27 System.out.println("Hash Set to be united with previous set: " +hs1);
L28 hs.addAll(hs1);
L29 System.out.println("Union of hs and hs1: " +hs);
}}
Output
C:\javabook\programs\chap 10>java HashSetDemo
Hash Set: [null, D, E, A, B, C]
Re-adding C to set: false
Iterating contents of Hash Set one by one
null
D
E
A
B
C
Size of Hash Set: 6
null removed: true
Hash Set: [D, E, A, B, C]
check whether Set contains C :true
hs: [D, E, A, B, C]
hs1: [D, E, B]
hs1 is a subset of hs: true
Intersection of hs and hs1: [D, E, B]
Difference of hs and hs1: []
Hash Set to be united with previous set: [D, E, B]
Union of hs and hs1: [D, E, B]
Explanation
L1 A HashSet of string is created. L13 remove() method is used to remove an
L2–7 add method is used to add String to the element from HashSet and this method returns true
HashSet. if element is present.
L8 Prints the HashSet (see output to check the order L14 Prints the HashSet.
is not maintained). L15 To find a particular element in the set, the
L9 When you try to add the element which is contains(Object o) method is used. This method
already present in the set the method call is ignored returns true if element is found, else false.
L16 A new HashSet is created to show the basic
and false is returned by the add method. (Remember:
operations of mathematical set: union, intersection,
Set does not contain duplicates) (see output).
and difference.
L10 and 11 Iterating the contents of the HashSet L17–19 Objects of type string are added to this
using the for-each loop. new HashSet.
L12 size() method is used to return the size of L20 and 21 Prints both the HashSet.
the HashSet, i.e., 6 as six objects have been added L22 If a HashSet (hs) contains all the elements
to the collection. of another HashSet (hs1) then hs1 can be called
314 Programming in Java
Output
C:\javabook\programs\chap 10>java TreeSetDemo
A
B
C
D
TreeSet: [A, B, C, D]
Generics, java.util, and other API 315
Explanation
L1 A TreeSet of String is created. L9 Prints the TreeSet.
L2–7 String objects are added using the add L10 and 11 The first and the last elements of the
method. The objects have been added in a random TreeSet can be obtained using first() and last()
order. Duplicates as we have already discussed are methods of the TreeSet object.
ignored and add method returns false. L12 Prints the size of the TreeSet, i.e., 4.
L8 Using for-each loop the contents of TreeSet
are iterated.
10.5 MAPS
Map allows unique key/value pairs to be added. For searching an element from the set, you need
to have an exact copy of the element to be searched from the collection but normally we do not
have the exact copy. What we have is some key information about the element. We need a way
to look up the element with the help of that key. A Map collection is helpful in these cases as
it stores key along with their associated values. These keys in Map are unique. Map does not
allow null key and values. We will discuss two of the subclasses of Map interface, i.e., HashMap
and TreeMap.
10.5.1 HashMap Class
HashMap, like HashSet uses hashing as a technique to store key/value pairs so that the values
can be searched efficiently according to the key. There order is not guaranteed by HashMap. The
HashMap does not allow null key and null value pair to be stored.
Output
C:\javabook\programs\chap 10>java HashMapDemo
HashMap: {Emp002=Peter, Emp003=Watson, Emp001=Tom}
Watson
HashMap: {Emp002=Peter, Emp003=David, Emp001=Tom}
Key in Map
Emp002
Emp003
Emp001
Values in Map
Peter
David
Tom
value associated with Emp002: Peter
Size of HashMap: 3
remove mapping associated with Emp002: Peter
HashMap after removal: {Emp003=David, Emp001=Tom}
Explanation
L1 HashMap object is created to store string L9–11 Prints all the keys one by one on the standard
key and string value. This has been specified as output. The method keySet() returns a Set object
HashMap<String, String>.
of keys which is used in the for-each loop to print
all the keys in the Set.
L2–4 put (K key, V value) method is used for
L12–14 Prints all values one by one on the standard
adding keys and values to the HashMap. This method
output. The method values() returns a Collection
returns null if no mapping for the key exists in object of all values which is used in the for-each
the HashMap. If mapping exists the previous value loop to print all the values in the Collection.
associated with the key is returned. L15 If you want to get the value associated with
L5 Shows null is not entertained in HashMap. a particular key; use get method. The get method
L6 Prints the HashMap (see output. All key/value accepts the key as an argument and returns the value.
pairs are shown). L16 size() method returns the size of the HashMap.
L7 put method is used to overwrite the value L17 If you want to remove ant mapping; use the
associated with the key Emp003 and as the mapping remove method. This method accepts an argument,
was already present, this method returns the previous i.e., the key whose mapping is to be removed
value associated with the key, i.e., Watson (see (Emp002) and returns null if key is not found or else
the return the previous value associated with the key,
output).
i.e., ‘Peter’ (see output).
L8 Prints the HashMap. The output now reflects
L18 Prints the resultant HashMap.
value associated with Emp003 as David.
Generics, java.util, and other API 317
Output
C:\javabook\programs\chap 10>java TreeMapDemo
TreeMap: {Emp001=Tom, Emp002=Peter, Emp003=Watson}
TreeMap: {Emp001=Tom, Emp002=Peter, Emp003=David}
Key in Map
Emp001
Emp002
Emp003
Values in Map
Tom
Peter
David
value associated with Emp002: Peter
Size of TreeMap: 3
Explanation
We have discussed all the methods in the previous example.
318 Programming in Java
Output
C:\javabook\programs\chap 10>java CollectionsDemo
Elements in list : [Ignorance, is, a]
copy of list : [Bliss, is, a]
Generics, java.util, and other API 319
Explanation
L10 All elements from list sb are copied to list L15 and 16 reverse(List<?> l) reverses the
l starting from the first location in the list l. The specified list l and prints it.
elements in l will be overwritten by the elements in L17 and 18 swap method is used to swap two
sb. The only requirement is that the destination list elements in the list l at position i and j. swap
should be as long as source list to accommodate the (List<?> l, int i,int j). L18 prints the revised
elements otherwise an IndexOutOfBoundsException list after swapping (see output).
is generated. The signature of copy method is as L19 and 20 The fill (List<? super T> l, T
follows: obj) method is used to replace all the elements in
public static <T> void copy(List<? super T> list l with the object obj.
dest, List<? extends T> src) L21–23 A linked list works with iterators rather
L11 Prints the list after copying (see output). than an enumeration. Both interfaces are used for the
L12 Prints the first occurrence of srch in list l. same purpose, i.e., iterating through the collection
The method elements yet they have differences which we will
index Of SubList(List<?> src, List<?>
discuss in the next section. In case you want to
target)
obtain an enumeration of the LinkedList; use the
returns the first occurrence of target in src. (see
enumeration method of the Collections class as
output)
L13 and 14 All occurrences of a given object are shown in L21. This method accepts the collection
(List) and returns an enumeration. Now you can
replaced by another in a given specified list. The
method replaceAll (List<T> list, T oldval, T iterate through the elements of the collection list
newval) replaces oldval with newval in list l. L14
using methods of the enumeration, as shown in L22
prints the modified list (see output). and 23.
Note List <? super T> means that the list will hold objects of either T or any of its superclass. This is
in contrast to ‘? extends T’ which means the collection will hold objects of T or its subclasses.
Vector is synchronized whereas ArrayList is not. That means a vector collection is thread-safe
when accessed by multiple threads. On the other hand, an ArrayList offers better performance
as it is not synchronized. ArrayList can be used when the collection will not be accessed by
multiple threads. To iterate through the Vector collection we use a legacy interface Enumeration
whereas for ArrayList, we use iterator interface.
We have already used ArrayList in the examples throughout the chapter. A Vector object can
be created in a similar fashion as shown:
Vector<String> v = new Vector<String>();
The elements can be added to the vector using the add(E e) method as shown
v.add("One");
v.add("Two");
The method v.elements() returns an enumeration of object in the vector which can be iterated
as shown earlier.
Enumeration<String> e = v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement());
This enumeration is replaced by a newer interface; iterator. The iterator works with new classes
such as ArrayList, LinkedList, and so on. The iterator differs from enumeration in the sense
that it provides a method to delete element from the collection during the iteration. It has three
methods:
hasNext() returns boolean value to indicate that the iterator has next element in the
collection.
next() returns the next element in the collection.
remove() method removes the last element returned by the iterator.
We have already shown you how to use iterator with ArrayList in Example 10.1.
Or use a parameterized constructor that accepts an argument, i.e., seed for the random generator.
A seed is a number used to initialize a pseudorandom number generator,
Random generator r = new Random(long seed);
A random integer can be generated from a Random object using two methods: nextInt() and
nextInt(int n).They may return any integer: positive or negative. The overloaded method that
accepts an argument can be used to generate random integers between 0 and some limit. For
example, the following will generate a number between 0 and n – 1.
int randomInt = r.nextInt(n);
A random real number uniformly distributed between 0.0 and 1.0 can be generated using the
nextDouble or nextFloat() method. Table 10.5 lists the methods of the Random class.
Note Math.random() also generates a random double number between 0.0 and 1.0.
Output
Note This pattern is also used in MVC architecture. MVC stands for Model View Controller. The
model object manages the behavior and data of the application, view takes care of the
graphical or textual representation and the controller is used to interpret the user commands.
The model responds to user requests from the controller by changing its state which is
presented to the user through view. View can be treated as the observer on the model, i.e.,
observable object.
Generics, java.util, and other API 323
L52 setChanged();
// Notify observers of change
//notifyObservers(this);
L53 notifyObservers();
}
}// Account class ends here
Output
Explanation
L1–2 Import the Observer interface and Observable L20–26 Instance variable for the customer class
class. are defined, which are initialized by the constructor
L3 class Bank is defined. of the customer class.
L4–5 A Bank has many customers and a customer L27 update method is overridden. This method
owns an account. (Although a customer can hold is invoked automatically as soon as the Observable
more than one account but for simplicity we assumed entity is changed and the Observer is notified using
that a customer will have only one account. You can notifyObserver method (L49 and 53). This method
change the program to accommodate n number of accepts two arguments: first one is the Observable
customers by creating an array of customers). So for object which is being watched and second one is an
the same two customers are created with two account object passed to the notifyObserver() method.
references which are instantiated (in L7 and 8) within L28 Prints the customer name along with the
the constructors of the Bank class. updated balance. The updated balance is obtained
L9–10 We wish that as soon as the account of a using the getBalance() method of the Account class.
customer is credited or debited, the customer should L29 Class Account inherits the Observable class
be notified about it. So the customer is the observer to denote that its object will be watched.
on the account (i.e., observable entity). L30–31 An account will have a number and
Customer objects (c and c1) are added as observers to balance. Therefore, two instance fields have been
the account (a and a1) objects using the addObserver defined for the same.
method. L32–37 Overloaded constructor for initializing the
L11–13 main method. instance variables are defined.
L14–18 demo method is created. The account L38–45 getter and setter methods have been
balance is credited and debited using the two methods defined for the returning and setting the value of the
of the account class, i.e., credit (L45–48) and debit instance fields of the account class.
(L49–52). L46–53 Account will be either credited (added)
L19 Customer, in order to become an observer has or debited (deducted) with amount. Two methods
to inherit the Observer interface and override the credit and debit have been created. They accept an
update method. argument, i.e., the amount to be credited or debited.
326 Programming in Java
After the credit or debit operations have been object as its state has changed and notifyObserver()
performed, i.e., the account balance either increases method is used to notify the Observer about this
or decreases, the observer has to be notified about this change thereby calling the update (L28) method of
change. So setChanged() method is used to mark this the Observer (i.e., customer in our case).
Note As getBalance() is a method of the Account class and not the observable class we need to
cast it back into the account and then invoke the getBalance() method. This cast is legal
because the Observable reference actually would contain an Account object and also Account
is a subclass of Observable class.
L4 try{
//
L5 Runtime r = Runtime.getRuntime();
L6 System.out.println("Free Memory"+r.freeMemory());
L7 System.out.println("Total Memory"+r.totalMemory());
Output
Explanation
L1 The java.io package is imported to use L2 Class declaration.
classes like B u f f e r e d R e a d e r , I n p u t S t r e a m , L3 main method defined for the class.
InputStreamReader, and IOException. L4 try block starts.
328 Programming in Java
L5 A Runtime object, associated with the current machine and totalMemory() returns the total amount
Java application, is obtained using the static method of memory in the Java virtual machine.
getRuntime(). L8–10 The exec method can be used to execute
commands and create process objects. The commands
L6–7 freeMemory() method returns the free
that are passed as arguments to the exec method are
amount of memory available in the Java virtual as follows:
cmd /c start – for starts a new dos prompt (See Output)
notepad filename – for opening notepad with the file within it. (See Output)
cmd /c dir – for showing all directories and files within the current directory (See Output)
/c option of the cmd, executes the command specified and then terminates
L11–16 The dir command within the exec method using the InputStreamReader object (L12) and then
creates a process which will return the names of file buffered by passing the InputStreamReader object
and directories present in the current directory. In within the constructor of BufferedReader (L13).
order to display it to the user we will have to read the
Now you can use the readLine method (L15) of the
output from the Process object created in L10. For
reading the getInputStream method is used (in L11) BufferedReader object to read from the Process
to obtain an InputStream object from the Process object (created in L10) line by line.
object. This object is converted to a character stream L17–18 For catching any exceptions that may arise.
Note Fully qualified class name including all package names must be specified while using Class.
forName(). This fully qualified name can be obtained using the c1.getName() method (This
method is extensively used in our example below). If the class name is only desired, it can be
obtained using the cl.getSimpleName() method.
Not only we can know about the name of the class but can also get details about the
(a) Superclass of a class.
(b) Constructors of a class, their arguments with their types and modifiers as well.
(c) Fields with their arguments along with their types and modifiers.
Generics, java.util, and other API 329
// constructors
L13 Class c=Class.forName("ref.Reflection");
L14 System.out.println("class modifier is : "+Modifier.toString(c.getModifiers()));
// Methods
L23 Method m[] = c.getDeclaredMethods();
L24 for(int i = 0;i<m.length;i++)
{
L25 System.out.println("Method: "+ m[i].getName());
L26 System.out.println("Method Modifiers is : "+Modifier.toString(m[i].
getModifiers()));
L27 System.out.println("Method Modifiers is public: "+Modifier.
isPublic(m[i].getModifiers()));
L28 System.out.println("Method return type: "+m[i].getReturnType());
}
L29 m[0].invoke(r);
// interfaces
L43 Class in[]=c.getInterfaces();
L44 System.out.println("Interfaces: "+in[0].getName());
//packages
L45 Package cpackage=c.getPackage();
L46 System.out.println("Package of the class: "+cpackage);
}
}
Generics, java.util, and other API 331
Output
Explanation
L1 Package ref is declared to hold the class runtime by invoking the method getClass() on the
Reflection. object. getClass() method returns an object of type
L2 java.lang.reflect subpackage is imported java.lang.Class and getName() is invoked on
to use the reflection API. Please remember the sub- this object to return the name of the class, i.e., ref.
packages have to be imported explicitly. Reflection (see output).
L3 java.io package is imported as the class L13–18 A Class object is created to represent
implements Serializable interface. (The class will the class whose details are required. The class
not be serialized in our program. This interface is name is passed as an argument to the forName
inherited to demonstrate how reflection API can be static method of the java.lang.Class class. All
used to know the interfaces inherited by a class. So constructors of a class can be accessed using the
we need to inherit an interface and for the same we getDeclaredConstructors() method of the Class
had inherited the Serializable interface.) object as it returns an array of all constructors present
L4 Class declaration. in it (as a java.lang.reflect.Constructor array).
L5–7 A private field: demo, is declared within the The constructors name can be obtained by invoking
class which is initialized using the constructor. The the getName() method (L16) on the individual
constructor accepts two arguments one is used in our constructor object present in the array (L15). The
program to initialize the instance variable: demo and modifiers used in the constructors can be obtained
the other parameter is used for illustration purpose. by invoking the method getModifier() (L17) on
L8–9 Show method is declared and it specifies that the individual constructor object present in the array.
it may throw ArithmeticException. This method returns an int representing the different
L10 main method. modifiers of Java which can be converted to string
L11 An object of the Reflection class is created. using the Modifier.toString method (as shown in
L12 The name of the class can be obtained at L16). [Note 1]
332 Programming in Java
L19–22 If constructors accept arguments of any L30–32 Shows how to get details about exceptions
type, their respective types can also be known using thrown by the methods of a class. getException()
the getParameterTypes method on the java.lang. method of the Method object returns an array of type
reflect.Constructor object. This method returns an Class containing all the exceptions declared in the
array of type Class. The array length is determined throws clause of a particular method. The exception
name is obtained by invoking the method getName()
to loop through and display the types of all the
on the individual elements of the array object.
arguments within a constructor. [Note 2]
L33–34 The getSuperClass() method of the class
L23–28 Shows how to get details about methods of java.lang.Class is used to determine the superclass
a class using reflection API at runtime. getDeclared- of a class whose object is created in L12. This method
Methods()method is invoked on the Class object returns an object of type java.lang.Class.
(created in L13) to extract details about methods of L35–42 Shows how to determine the fields of a
a class. This method returns an array of type java. class with their respective names, types, modifiers
lang.reflect.Method. The method name is obtained and values. getDeclaredFields() method of the
by invoking the method getName() on the individual java.lang.Class returns an array of type java.
elements of the Method array. The method modifiers lang.reflect.Field class. Each element of the
can be obtained using the method getModifiers(). Field array object represents the fields of the class.
This method returns an int representing the modifier. The name, type, value, and modifier of the fields
can be extracted using the methods of the Field
To get the name of the modifier we convert the int
class like getName() used in L33, getType() in
value of the modifier into its name using the Method.
L34, get(r) (for extracting value of that field) and
toString (int modifier) method.
getModifiers() respectively. Not only the value can
L29 The methods of a class can be invoked at be extracted, they can also be set using the setter
runtime using the invoke() method of the java. method as shown in Table 10.7. The first argument
lang.reflect.Method class. The method object is is the object whose fields value is to be set and the
used to call invoke() and the object on whom to second is the value which is to be set. We have use the
invoke this method is passed as an argument to the set method wherein the first argument is the object
invoke method (In other words an instance of the on which to set the value and second is the value to
class that declares the method). [Note 3] be set. The question that may arise at this point is
Table 10.7 Setter Methods of the java.lang.reflect.Field Class
public void set(Object obj, Object val) Changes the field value represented by this Field
object on the object obj to the new value specified in
the second argument.
public void setBoolean(Object obj, Sets the boolean value (b) in a boolean field of the
boolean b) object obj.
public void setByte(Object obj, byte b) Sets the byte value (b) in the byte field of the object obj.
public void setChar(Object obj, char c) Sets the char value (c) in the char field of the object obj.
public void setDouble(Object obj, double d) Sets the double value (d) in the double field of the
object obj.
public void setFloat(Object obj, float f) Sets the float value (f) in a float field of the object obj.
public void setInt(Object obj, int i) Sets the int value (i) in a int field of the object obj.
public void setLong(Object obj, long l) Sets the long value (l) in long field of the object obj.
public void setShort(Object obj, short s) Sets the short value (s) in short field of the object
obj.
Generics, java.util, and other API 333
that: The second argument in the set method is of method of the java.lang.Class class is used to
type Object and we are passing an int value in our return an array of interfaces inherited by the class.
method yet still it compiles and executes. Why? The The name of the interface is printed using the method
answer is because of autoboxing features of Java you getName(). [Note 4]
are able to pass values to Object directly. You can L45–46 getPackage() is invoked through the
also use setInt method for the same. Class object (created in L13) to returns the package to
L43–44 Shows how to get the details of the which this class belongs as a Package object.
interfaces inherited by the class. getInterfaces()
Notes 1. You can also check these modifiers using the following methods of java.lang.reflect.
Modifier class:
Modifier.isAbstract(int modifiers)
Modifier.isFinal(int modifiers)
Modifier.isInterface(int modifiers)
Modifier.isNative(int modifiers)
Modifier.isPrivate(int modifiers)
Modifier.isProtected(int modifiers)
Modifier.isPublic(int modifiers)
Modifier.isStatic(int modifiers)
Modifier.isStrict(int modifiers)
Modifier.isSynchronized(int modifiers)
Modifier.isTransient(int modifiers)
Modifier.isVolatile(int modifiers)
2. You can also get the types of parameters used in the methods by using the
getParameterTypes() method explained in L19–22.
3. If the method is static, then the specified object argument is ignored and it may be null.
4. The interfaces specifically declared by the class will only be returned by the getInterfaces()
method. If the superclass of the class implements an interface and this fact is not
specifically stated by the class, then the interface name will not be returned. For getting
a complete list of the interfaces implemented by a class you will need to look in the class
as well as its super class/classes recursively.
SUMMARY
The java.util revolves around collections (bag of these concepts. For mapping keys to their values java.
objects). To provide compile-time safety for collections, util package provides a Map interface.
generics were introduced in Java 5. The collection In addition to these, the util package also provides
can be ordered or unordered and may also contain utility classes such as Date and Calendar for getting
duplicates. For example, a Set does not allow date and time which we have already discussed in
duplicates whereas a LinkedList does. This package
the earlier chapters. StringTokenizer class used for
deals with data structure concepts such as Linked list,
splitting strings has already been discussed in the
stack, queues, trees, and hashing. The classes like
earlier chapters under the topic ‘String’. This package
LinkedList, Stack, HashSet, TreeSet encompass
334 Programming in Java
also came up with a Scanner class which we had Random class for generating random values (like int,
touched in Chapter 9. Dynamic array functionality double , float , and long ), the observer pattern
is provided by two classes: ArrayList and Vector. along with Observable class and Observer interface
ArrayList methods are not synchronized but Vector for keeping an eye on other objects. Runtime class,
is synchronized. Legacy interface Enumeration and although a part of java.lang is also discussed here
newer Iterator interface are used for iterating over to show its features and utilities.
the collection of objects. Finally the reflection API is discussed in detail to show
This chapter discusses about utility classes like the how the details of a class can be known at runtime.
EXERCISES
Objective Questions
1. What will happen if a list is created as shown 6. Which collection contains an ordered collection
below: of elements?
List l = new LinkedList(); ? (a) TreeSet (b) HashSet
(a) compiles and executes (c) TreeMap (d) LinkedList
(b) compile time error 7. What are used to provide compile-time safety to
(c) run time error your programs?
(d) raises an unchecked exception (a) List (b) collections
(c) Interfaces (d) Generics
2. Which collection does not contain duplicates?
(a) Set (b) List 8. What feature of Java 5 enables a collection class
to hold objects as elements of same type?
(c) Map (d) Queue
(a) Generics (b) Annotations
3. Which collection contains the mapping of keys (c) Enumerations (d) Assertions
to their values?
9. In case, you do not use generics in your programs
(a) Set (b) List what option of javac is used to compile the
(c) Map (d) Queue program?
4. What collection class is synchronized to hold (a) javac -d
elements? (b) javac -s
(a) HashMap (b) TreeMap (c) javac -classpath
(c) Vector (d) ArrayList (d) javac -Xlint:unchecked
5. Which collection contains an unordered collection 10. What collection class is used to hold elements
(similar to dynamic arrays) and is not
of elements?
synchronized?
(a) TreeSet (b) HashSet
(a) HashMap (b) TreeMap
(c) TreeMap (d) LinkedList (c) Vector (d) ArrayList
Review Questions
1. What is a collection in Java? Can you identify any 3. What are Generics and how are they used
real life example which is similar to a collection in Java? (Use an example in support of your
in Java? answer)
2. Explain the difference between: 4. What are bounded wildcards? How are they
(a) Vector and ArrayList used?
(b) Enumeration and Iterator
Generics, java.util, and other API 335
5. Explain the union, intersection, and the difference 7. What is reflection API used for?
operation of a mathematical set. How is it related 8. What is observer pattern? How is it useful?
to the Set interface in Java? 9. Explain Runtime class with its features.
6. Explain the unique features of a Map interface.
Programming Exercises
1. Reverse the LinkedList and then copy all the 6. Create a class to simulate a dictionary of words
elements of a LinkedList into another list. along with their meanings. The words/meaning
2. Write a program to iterate a L i n k e d L i s t should be stored in such a way that retrieval of
using for-each and traditional for with a meaning is as fast as possible.
ListIterator. 7. Rewrite the above program to display the list of
3. Write a program to convert an array to a collection words along with their meanings in the dictionary
and back. in a sorted order.
4. Create a Collection class named Queue to 8. Write a program to generate 20 unique random
implement the FIFO order of queues. [Use integers from 1 to 100.
Generics] 9. Rewrite the observer example to use n customers
5. Demonstrate the Collections class and use the instead of just two customers as depicted in the
following methods in the class: example. You are required to get the details of
(a) rotate (b) max the Customer from the user. Also try to figure out
(c) min (d) disjoint whether there can be more than one Observer
(e) sort (f) binary search on an Observable object?
11.1 INTRODUCTION
Computer network is an interconnected collection of computers. The nodes of a network
communicate with each other using a wired/wireless medium. This communication is actually
carried between two processes residing in two different machines. The process on one machine
initiates the request and another responds to the requests. The initiator is the client and the
responder is the server.
Network programming deals in the implementation of client/server concept. The client and
server communicate via protocols. TCP/IP protocol suite is followed in all networks including
the Internet. Protocols are a set of rules and regulations to be followed for the purpose of
communication.
11.1.1 TCP/IP Protocol Suite
TCP/IP protocol suite contains a number of protocols. It is a four-layered model followed by the
networks. Internet also follows the same model. Figure 11.1 shows the TCP/IP model.
The client and server applications created by the users reside at application layer. They
interact with the transport layer using sockets API, i.e., classes in the java.net package. The
transport layer takes data from the application layer (sender) and breaks it up into segments,
attaches the port number used by application to the data, and passes it to the network layer.
Network Programming 337
Depending upon the protocol used, a connection is established (TCP) or not (UDP) at the transport
layer.
The two protocols used for the purpose are TCP and UDP. Both client and server use
the same protocol. TCP is a connection-oriented protocol, while UDP is a connectionless
protocol. Connection-oriented protocols ensured guaranteed delivery, sequence of data, and
acknowledgement for the data sent. On the other hand, connectionless protocols neither guarantee
delivery nor sequencing and acknowledgement. All standard applications run on standard port
numbers also known as well-known port numbers (from 0–1023), e.g., HTTP (80), FTP (20/21),
DAYTIME (13), ECHO (7), TELNET (23), SMTP (25), etc. Mostly server applications use
well-known port numbers. The client applications use ephemeral port numbers (i.e., short-lived)
starting from 1024 onwards.
The network layer creates packets by encapsulating the segments into its own header format,
attaches the source and the destination IP address to it and passes it to the link layer. IP protocol
is a connectionless routed protocol. The java.net package supports both versions of IP protocol
(IPv4 and IPv6). IPv4 addresses are of 32 bits in size and IPv6 addresses are of 128 bits in size.
The link layer frames the data received from the network layer according to its own format,
converts the data to bits and subsequently, signals are sent over the wire to the other side. The
other side repeats the same steps, but in reverse order, decapsulating the data at each layer.
Network programming is supported in the java.net package of Java.
11.2 SOCKETS
Network programming revolves around the concept of sockets. A socket is an end-point of
communication. Sockets are created at both ends of communication, i.e., at the client as well as
the server. A socket is defined by three things: IP Address, port, and the protocol to be used for
communication. IP address is the unique address assigned to every machine on the network and
port is a unique logical number on that IP address used for identifying the applications running
on that particular machine. IP address exists on network layer and port numbers on the transport
layer of the TCP/IP protocol suite.
338 Programming in Java
Note Do not confuse the concept socket with the class Socket in java.net. Till now, we have covered
the concept socket and now, we will discuss the class Socket.
There are separate classes in java.net package for creating TCP sockets and UDP sockets.
Client TCP socket is created with the help of Socket class and server TCP socket is created using
ServerSocket class. We will discuss UDP client and server later.
Explanation
L1 and 2 Imports the necessary packages. like the previous one, returns an InetAddress object.
L3 and 4 Class defined with the main method L10 getlocalPort() method prints the local port
within it. to which the socket is connected. In case you want
L5 All the statements have been placed in a try/ the remote port to which the socket is connected, use
catch block to catch the necessary exceptions thrown getport() method.
by statements in try block. L11 Prints the address with which the socket is
L6 Socket class used to create a socket at the client connected. If you see the output, this line prints the
side. As soon as the object of this created, a request same output as L9 because both the client and the
is automatically sent to the specified server at the server are running on the same machine. If they
specified port. The first argument in the constructor would have been running on different machines, this
is the server name and the second argument is the line would have given the address of the server. The
port on which the server application is running. If method getInetAddress() returns an InetAddress
some problem occurs while creating a socket, then object.
an IOException is thrown. Reading data from server through sockets
The local machine address is obtained using the static L12 Using the getInputStream() method of the
method getLocalHost() of the InetAddress class. Socket class, we obtain an InputStream to read con-
The InetAddress represents an IP address. This tents from the socket and using getOutputStream()
class has two subclasses Inet4Address (for IPv4 method of the Socket class, we can obtain an Out-
addresses) and Inet6Address (for IPv6 addresses). putStream to write contents to the socket.
This method throws an UnknownHostException if no L14 BufferedReader object is created to read
host could be found. strings from the socket. The byte stream is converted
L8 Prints the local address of the machine to character stream using the InputStreamReader
associated with the client socket (see output). The object.
loopback address (127.0.0.1) is printed. Packets L15 to 17 String x is created. A while loop is used
destined for loopback address are routed back to the to iterate and print string until the socket has no more
same machine from which they are sent. The method strings to be read. We have already discussed this in
getLocalAddress() returns an InetAddress object Chapter 9. The only difference is that there, we were
which is then printed. The toString() method of reading data from files and here, we are reading data
the InetAddress object is called before writing it from sockets.
on the standard output which converts the IP address L18–19 Closes the streams and the socket.
to a string. L20–21 catch clause.
L9 Print the local host (see output). This method,
Note We are running the client and the server on the same machine, so we have mentioned the
address of the local machine in the first argument. Also note that we have not mentioned
the port and IP address for the client socket. These will be attached to the client socket
automatically. If you wish to do it on your own, you can use the other constructors of the
Socket class.
340 Programming in Java
The server program for the client in Example 11.1(a) is shown below. The server programs
are meant to be up and running all the time and serve many clients at a time. But this server
program (Example 11.1(b)) cannot serve multiple clients at one time. There are two types of
servers: iterative and concurrent. Iterative servers process only one request at a time, so the
other client requests have to wait until the first one is processed. The other type is a concurrent
server which we will discuss in Section 11.4. ServerSocket class is used for creating a socket
at the server side. The constructors of this class are shown in Table 11.2.
Client
C:\javabook\programs\chap11>java SocketDemo
Socket created
Local Address: /127.0.0.1
Local Host: sachin-pc/127.0.0.1
Local Port : 49362
Inet Address: sachin-pc/127.0.0.1
Streams created
Hello, How are you?
The server date and time is: Sun Mar 29 19:06:18 IST 2009
Explanation (Server)
L1 to 3 Imports the necessary packages. client socket. Anything written to socket at server
L6 try block begins. side is eventually sent to client as a connection exists
L7 ServerSocket object is created to create a between them.
server socket. This application will run on Port Connection between client
number 7. and server
L8 An infinite loop is created to process client’s Client Server
request one by one.
L9 accept method of ServerSocket object listens L14 PrintWriter object is created to write the
for client’s requests and as soon as one is received, character to the OutputStream directly. The first
argument is used to connect the PrintWriter object
accepts it and returns a Socket object connected to
to the Socket output stream and second argument sets
the client. Now this socket is responsible for handling
the auto-flush property to true.
client’s requests. L16 String declared.
L11 Prints the client’s IP address using L17 Calendar instance created.
getInetAddress() on the socket object (see output). L18 String created in L17 is written to the output
L12 Prints the client’s port number (remote port) stream connected to the socket.
using getPort() method on the Socket object (see L19 Current date and time of the server is written
output). to the client.
L13 InputStream and OutputStream objects can L20 Prints a string on the server standard output
be obtained from Socket object returned in L9 using console “contents written to” followed by the client’s
getInputStream() and getOutputStream(). These name.
streams can be obtained to read and write data to the L21 PrintWriter object is closed.
342 Programming in Java
Let us take an example of how UDP can be used in network programming. In the following
example, the client sends a datagram to the server. The server receives the datagram and generates
another datagram in response to it. The server code is shown in Example 11.2(a).
Network Programming 343
Explanation
L6 DatagramSocket has been created with the UDP L13 A new DatagramPacket is created for sending
server running on port number 8. it to the client. The constructor arguments are
L7 and 8 DatagramPacket object (L8) is created to (a) buff–byte array to be sent to client
hold the data received in the byte array (L7) through (b) buff.length–length of the array
the datagram socket. (c) in.getAddress()—to get the address of the
L9 receive() method of datagram socket object is client. We have extracted it from the datagram
used to receive data from UDP client and put it in the received by the client.
byte array. (d) in.getPort()—to get the port address of the
L10 Byte array converted to string and is printed client. We have extracted it from the datagram
on the standard output. received by the client.
L11 and 12 String to be sent to client is created L14 send method is used to send DatagramPacket
and converted to bytes using the getByte() method. to the client.
Output
Server
C:\javabook\programs\chap11>java DatagramServer
Hello Server
Client
C:\javabook\programs\chap11>java DatagramClient
sending to server: Hello Server
received from server: Hello client
Explanation
L6 and 7 DatagramSocket object is created to exception is thrown, it will be caught by the catch
create a socket for the UDP client. As both client and
having a reference of IOException class.
server are running on the same machine, we pass the L8 to 16 A datagram packet (i.e., dp) is created
local machine address using getLocalHost() static and sent to server. In response to this, the server
method of the InetAddress class. This method throws also sends a datagram which is received by client in
an UnknownHostException if no host could be found. a DatagramPacket object (i.e., in).
It is a subclass of the IOException class, so if this
In the following example, we have used the URL class to refer to a resource on the local machine.
The methods of the URL class are used to parse the URL and read the file. Let us take an example
to understand the concept.
Output
C:\javabook\programs\chap11>java URLExample file:\\localhost\jdk-6-doc\docs\ api\index.html
The Protocol used is: file
The Host used is: localhost
The File used is: /jdk-6-doc/docs/api/index.html
The Port used is: -1
The Reference in page is: null
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR /html4/
frameset.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Wed Nov 29 02:28:47 PST 2006-->
<TITLE>
Java Platform SE 6
</TITLE>
<SCRIPT type = "text/javascript">
targetPage = "" + window.location.search;
if (targetPage != "" &&targetPage != "undefined")
targetPage = targetPage.substring(1);
functionloadFrames() {
if (targetPage != "" &&targetPage != "undefined")
top.classFrame.location = top.targetPage;
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<FRAMESET cols = "20%,80%" title = "" onLoad = "top.loadFrames()">
346 Programming in Java
<P> This document is designed to be viewed using the frames feature. If you see this
message, you are using a non-frame-capable web client.
<BR> Link to <A HREF = "overview-summary.html"> Non-frame version.</A>
</NOFRAMES>
</FRAMESET>
</HTML>
Explanation
L6 Object of class URL is created and the URL L12 To access the resource, we have to open a
is passed to the constructor. We have accessed the connection to the resource. The openConnection()
resource on the local machine. That is the reason we method of the URL object is used to return a
have used the file protocol followed by the name URLConnection object. This object represents a
of the machine (i.e., localhost) and the path of the connection to the resource (remote or local).
file, e.g. L13 We have to read the contents of that file
file:\\localhost\jdk-6-doc\docs\api\index.html (index.html) so an InputStream is required for
reading the contents. The connection object provides
L7 Prints the protocol used in the URL using the a method getInputStream() which returns an
getProtocol() method.
InputStream object connected to the URLConnection.
L8 Prints the host used in the URL using the L14 to 18 We have used these lines for reading
getHost() method.
the file.
L9 Prints the file to be accessed on the host used L19 The constructor of URL class may throw a
in the URL using the getFile() method. MalformedURLException if the protocol specified in
L10 Prints the port used in the URL using the the URL is unknown, so it is necessary to catch it.
getPort() method. The output shows –1 as no port
The IOException needs to be caught as discussed
has been specified. in earlier chapters (MalformedURLException is a
L11 Prints the protocol used in the URL using the subclass of IOException).
getProtocol() method.
Request
Client x ServerSocket
Accepts client’s request
Explanation
L1 A Server class is created that extends the socket. Whatever is read from the client is written
Thread class. back to client.
L2 An instance variable of type Socket has been L16 A server socket is created which run on Port
created in the Thread subclass. number 7.
L3 Constructor for the server has been defined and L17 to 19 An infinite loop is defined to accept
incoming client’s request. As soon as a client’s
it accepts an instance of Socket.
request is received, it is accepted (via the accept()
L4 Initializes the instance Socket variable. method in L18) and a Socket instance (s) i
L5 The thread is started using start method (refer returned (for handling client). A Thread is created
Chapter 8). (L19) and socket instance (created L18) is passed
L6 to 14 run method has been overridden to to the thread (as an argument in the constructor
provide the details for the thread. We have already of ThreadedEchoServer). This Socket instance is
discussed the code written in the run method many assigned to the client instance variable (L4) in the
times. It is actually to read and write data to the constructor of ThreadedEchoServer.
Now we will create a client that establishes a connection with the server and writes contents
to it which is echoed back to the client by the server.
Output
Server
C:\javabook\programs\chap11>java ThreadedEchoServer
From client: hello
From client: Hi I am new Client
From client: hi i am the First client
From client: how are you
Client1
C:\javabook\programs\chap11>java EchoClient
hello
echo from server: hello
hi i am the first client
echo from server: hi i am the first client
Client2
C:\javabook\programs\chap11>java EchoClient
Hi I am new Client
echo from server: Hi I am new Client
how are you
echo from server: how are you
L9 System.out.println("InetAddress:" +inetAddress);
}
L10 System.out.println();
} }}
Output
C:\javabook\programs\chap11>java NetInterfaceDemo
Display name: Software Loopback Interface 1
Name: lo
MTU: -1
Interface is up: true
InetAddress: /0:0:0:0:0:0:0:1 //IPv6 Address
InetAddress: /127.0.0.1 //IPv4 Address
Note This is a sample output and not complete. Besides, the value of parameters may vary from
machine to machine.
Network Programming 351
Explanation
L1 A machine having more than one network ArrayList are assigned to NetworkInterfac e
interface is called a multi-homed machine. For variable ‘netint’in the for-each loop. L3–L10
example, all routers are multi-homed as they will execute as long as there are objects in the ArrayList.
have at least two interfaces on for the internal network L3 and 4 Prints the display name and the name
(LAN) and another for outer world (WAN). To obtain of the interfaces using simple methods (see output).
all interfaces on the machine, we use the static method L5 MTU defines the size of the packet that can
getNetworkInterfaces() of the NetworkInterface be sent over the network. The getMTU() method is
class. This method returns an enumeration of objects used to return the MTU of the interface. This method
and throws a SocketException if any problem was added in Java 6. It returns –1 if no MTU is
occurs. Enumeration is a collection of objects which associated with an interface like loopback interface.
can be iterated successively one at a time. The The loopback does not need to send anything on the
name mentioned in the angle brackets <> specifies network. All data sent to loopback is reverted back
the class of objects that the enumeration can hold. to client.
The getNetworkInterfaces() method returns an L6 isUp() method prints whether the interface is
enumeration which contains <NetworkInterface> up or down.
objects only. L7 to 9 Prints the IP addresses associated with
L2 The Collections class (java.util package) an interface. The getInetAddresses() method of
operates on the collections (like enumeration). This the NetworkInterface class is used to return an
class provides a static method list (Enumeration<T> enumeration of IP addresses. We iterate through
n) that takes an enumeration as an argument and the enumeration as we have done earlier in L2. It is
returns an ArrayList containing elements of possible that an interface may have an IPv6 address
the enumeration. One by one the elements of the as well as an IPv4 address associated with it (as
shown in the output).
Note IPv4 addresses are represented in dotted decimal notation. 32 bits are divided into 4 parts of
8 bits each. These 8 bits are converted to their respective decimal equivalent and then written
with a dot in between them.
IPv6 addresses are represented in colon hexadecimal format. 128 bits are divided into 8 parts
of 16 bits each. Then these 16 bits are grouped (4 groups of 4 bits each). Each 4 bit binary
value is converted to its corresponding hexadecimal value. The hexadecimal value of all the
16 bits is written separated by a colon, for example, fe80:0:0:0:8c3d:30ab:4e1b:76a%8. The
number mentioned after the % determines the scope of this address.
For more details on IPv6 addressing architecture, refer IPv6 addressing draft and RFC 4007.
SUMMARY
Network programs in Java (compared to C language) evolved since its inception and it has added a lot of
are short in size, easier to code, and debug. The features like support for newer IPv6, knowledge of your
extensive support of multithreading in the language local network interfaces, URLs, multicasting, cookie
makes it easier to implement concurrent client/server handling, and so on.
applications in Java. Java network programming has
352 Programming in Java
EXERCISES
Objective Questions
1. What is the value of backlog by default? 7. What is the address of the loopback address?
(a) 10 (b) 20 (c) 30 (d) 50 (a) 127.0.0.0 (b) 10.1.1.1
2. A socket is comprised of 3 identifiers. What are (c) 192.168.10.1 (d) 126.255.255.255
they? 8. Which five parameters uniquely identify a
(a) MAC Address, Port and Protocol connection?
(b) IP address, Port, Protocol (a) Local IP, Remote IP, Local MAC, Remote
(c) MAC Address, IP Address and Port Number MAC and Protocol
(d) MAC Address, IP Address and Protocol (b) Local IP, Local port, Remote MAC, Remote
3. What is the size of an IPv6 address? port and Protocol
(a) 32 (b) 64 (c) 128 (d) 16 (c) Local MAC, Local port, Remote MAC,
4. What is the size of an IPv4 address? Remote port and Protocol
(a) 32 (b) 64 (c) 128 (d) 16 (d) Local IP, Local port, Remote IP, Remote port
and Protocol
5. Which class is used for creating a TCP socket at
server? 9. SocketException is a subclass of
(a) Socket (b) ServerSocket (a) IOException
(c) DatagramPacket (d) DatagramSocket (b) ReadWriteException
(c) FileNotFoundException
6. Which method of the NetworkInterface class is
(d) NullPointerException
used to obtain the maximum transmission unit?
(a) getMaximumTransmissionUnit() 10. UnknownHostException is a subclass of
(b) getTU() (a) IOException
(c) getMTU() (b) ReadWriteException
(d) getMaxTU() (c) FileNotFoundException
(d) NullPointerException
Review Questions
1. Explain the TCP/IP protocol suite. (c) IPv6 (d) MTU
2. Explain the difference between TCP and UDP. (e) Unicasting (f) Multicasting
Use real-life situations in your explanation to (g) Broadcasting (h) Port address
describe the differences. 5. Explain the role of the following classes:
3. Explain what is URL with all its parts. Which (a) Socket (b) ServerSocket
methods of the URL class can be used to obtain (c) DatagramPacket (d) DatagramSocket
the individual parts of a URL? 6. What is URL connection class used for and how
4. Explain the following terms: an instance of it is obtained from the URL object?
(a) MAC address (b) IPv4 Explain.
Programming Exercises
1. Create a UDP echo client/server application, 4. Write a Java program that implements a simple
wherein whatever is written to a UDP server is client/server application. The client sends data
written back to the client. to a server. The server receives the data, uses
2. Create a sample TCP chat application where it to produce a result, and then sends the result
client and server can chat with each other. back to the client. The client displays the result
on the console. For example, the data sent from
3. Use multithreading in the previous example to
the client is the radius of a circle, and the result
make it a multithreaded chat application.
produced by the server is the area of the circle.
Network Programming 353
5. Write a program to return the hardware address 6. Create a client/server application where the client
of your machine. requests for a particular file on the server. If the
[Hint: Use getHardwareAddress() method of file exists on the server, then write the contents
NetworkInterface class introduced in Java 6] of the file to the client.
12.1 INTRODUCTION
Many of you must have come across the word ‘Applet’. What is this applet? Applets are basically
small Java programs which can be easily transported over the network from one computer to
other. This is the reason why applets are used in Internet applications, where these applets (i.e.,
small Java programs), embedded in an html page, can be downloaded from the server and run
on the client, so as to do a specific kind of job. These applets have the capability of displaying
graphics, playing sound, creating animation, and performing other jobs that can be done by
simple application programs. To execute these applets on the client, the client must have either
a Java-enabled browser or a utility known as appletviewer (comes as part of JDK).
If we could develop simple Java standalone application programs, what was the need to have
applets? Actually applets are not full-featured programs, as these are usually written to accomplish
small tasks or part of bigger tasks. Before getting further, you must understand the difference
between an applet and an application. Table 12.1 illustrates the differences between applets and
applications.
In Java, applets can be dealt in two ways. One is the conventional applets, which are directly
evolved from ‘Applet’ class. Theses applets use Abstract Window Toolkit (AWT) to get the
GUI features. The other kinds of applets are those which are based on swing class, JApplet. We
will discuss AWT-based applets in this chapter, while swing-based applets will be discussed in
Chapter 15.
Applets 355
12.2 APPLETS
java.applet.Applet is the superclass of all the applets. Thus all the applets, directly or indirectly,
inherently use the methods of Applet belonging java.applet package. This class provides all the
necessary methods for starting, stopping, and manipulating applets. It also has methods providing
multimedia support to an applet. Applet class has a predefined hierarchy in Java, which shows
the classes extended by Applet class.
Figure 12.1 simply makes it easy for you to understand that an applet, which is a subclass of
java.applet.Applet, also inherits the methods of the other classes like java.awt.Panel, java.
awt.Container, java.awt.Component, and java.lang.Object, indirectly.
You can see that these classes are the ones which provide support for Java’s window-based GUI,
thus making an applet capable of supporting window-based activities. The common methods
belonging to the Applet class are mentioned in Table 12.2.
356 Programming in Java
in Section 12.1 that unlike an application program, Java runtime system does not call the main()
method to start the execution of an applet, rather it just loads the methods of applet class which
are responsible for starting, running, stopping, and manipulating an applet. The complete life
cycle of the applet will be taken up in the next section.
There is a method, paint() in the Container class, which is inherited by Applet class (as you
can make out from Fig. 12.1), carrying the signature,
public void paint(Graphics g)
This method, when called, displays the output of applet as per the code written on the applet’s
panel. You can see the argument of this method; it is nothing but an object of Graphics class.
The object makes it possible for an applet to output text, graphics, sound, etc. One thing you
must remember, you cannot take the services of Graphics class unless you import the package
it belongs to, i.e., java.awt. The output operations for an applet requires the methods contained
in the Graphics class, that is why its Graphics object is passed as argument to paint(). Now that
you know some details about the internals of an applet, we can discuss the program structure
of an applet.
When an applet is first loaded, Java runtime system creates an instance of the main class,
which is FirstApplet in this case. Then the methods belonging to the Applet class are called
through this object.
import java.applet.*;
//so as to make Applet class available
…………………………………
…………………………………
Explanation
L1 All applets are the subclasses of Applet class. L4 The paint() method defined by AWT
All applets must import the java.applet package. Container class is overridden. Any output to be
L2 The applet uses the methods of java.awt shown by an applet has to be taken care by this
package; it must be imported. method only. Please note that an object of Graphics
L3 The FirstApplet class is declared public so class is passed as parameter to this method.
that the program that executes the applet (a Java- L5 The object of the Graphics class is used to
enabled browser or applet viewer, which might not invoke drawString() method, which is responsible
be local to the program) can access it. This class for printing the string (“This is my First Applet”) at
extends the Applet class of java.applet package, x-coordinate 10 and y-coordinate 10.
thus inheriting the features of Applet class.
Note If you wish to run the above html file in any web browser, instead of using applet viewer, you
must have Java-enabled web browser. Otherwise, you will have to install Java plug-in, which
lets you run your applets as web pages under 1.2 version of JVM instead of the web browser’s
default virtual machine.
(b) Just as above, save the file as FirstApplet.java and compile it by using javac. In
order to run the applet, you have to give the below HTML coding as a comment in
FirstApplet.java.
In this chapter, we will be using the second approach throughout. So Example 12.1(a) should
have been actually written as shown in Example 12.1(b).
Output
Idle
Dead
Figure 12.3 shows the flow an applet takes while moving from one state to another.
As mentioned before, an applet may override some of the basic methods of class Applet. Note
that these methods are responsible for the lifecycle of an applet. These methods are
init()
start()
stop()
destroy()
init() Loading an
BORN
Applet
start()
stop()
RUNNING IDLE
start()
destroy()
paint()
DEAD
Note In order to initialize an applet, we must override the init() method of Applet class.
Running State
Applet moves to the running state by calling start(). An applet moves to this phase automatically
after the initialization state. But if the applet is stopped or it goes to idle state, start() must be
called in order to force the applet again to the running state. Suppose you have opened a web
Applets 361
page (having an applet) and you move temporarily to another web page (by minimizing it) the
first one goes to the idle state; when you return back to the first page, start() is called to put
the applet in the running state again. Unlike init(), start() can be called more than once.
You can see the paint() method in Fig. 12.3. This method is responsible for forcing the applet
to an intermediary state (display state), which is actually a part of the running state itself. While
running, an applet may need to perform some output and display it on the panel of the applet.
The paint() method, which is a part of Container class (a superclass of Applet class), needs to
be overridden for the purpose. This method is called each time to draw and redraw the output
of an applet. We already know the drawing of output of an applet. Let us discuss redrawing the
output of an applet with an example. An applet window may be minimized and then restored.
This restoration is nothing but redrawing of applet’s output and could be achieved by calling
paint(). Actually when an applet in restored, start() and paint() are called in sequence. We
will revisit this method in Section 12.7.1.
Idle State
An applet goes to idle state, once it is stopped from running. If we leave a web page containing
an applet (i.e., minimize it), the applet automatically goes to idle state. An applet can also be
forced to stop or go to idle state by calling stop().
Note If a thread has been created to control an applet by overriding start(), then we must use
stop() to stop the thread, by overriding the stop() method of the Applet class.
Dead State
Terminating or stopping an applet should not be confused with destroying an applet. An applet
goes to dead state when it is destroyed by invoking the destroy() method of Applet class.
It results in complete removal of applet from the memory. Whenever we quit the browser,
destroy() is called automatically. You should free up the resources being used by applet (if any)
by overriding the destroy() method. Like init(), destroy() is also called only once. stop()
is always called before destroy().
Here, the string msg is the string output to be displayed by the applet and a, b are the x, y
coordinates respectively of the window, where the output has to be displayed.
setBackground()
This method belongs to component class. It is used to set the background color of the applet
window. Its form is
void setBackground(Color anyColor)
The above method takes the color to be set as background, as argument. The Color class has
certain predefined constants for each color, such as Color.red, Color.blue, Color. green,
and Color.pink.
setForeground()
This method is similar to setBackground method, except that these are used to set the color of
the text to be displayed on the foreground of the applet window. Its form is
void setForeground(Color anyColor)
Component class has two more methods getBackground() and getForeground(), having the
following forms:
Color getBackground();
Color getForeground();
You can very well see that these methods return the current context of the Color, showing the
background and foreground colors, respectively.
showStatus()
This method is a member of Applet class. It is used to display any string in the status window
of the browser or appletviewer. Its from is
void showStatus(String text)
Here, the argument of the method is basically the string which you want to be displayed in the
status window.
Before going any further, we should better take an example which uses these methods, discussed
until now.
Output
Explanation
L1–3 All the important classes (belonging to their class (part of java.awt package). In L9, the text is
respective packages), whose members are to be used initialized by a string, This is an example applet.
in the applet are imported. L11–13 These lines account for the implementation
L6–10 This section shows the implementation of of start(), responsible for forcing the applet in
init(), where the background and foreground of running state. L13 displays the message about
the applet is set to white and red, respectively (see the start of the applet on the screen. Note that this
L7–8). White and red are static fields of the Color message will not be displayed on the applet window;
364 Programming in Java
it will be displayed as seen by you in earlier chapters L20–23 These lines are accountable for the
(by the use of System.out.println()). implementation of paint() method. In L22,
L14–16 These lines take care of the implementation Graphics object g is used to invoke its drawString()
of stop(). L16 just displays the message about method, which is actually used for writing on an
stopping an applet. As many a times you will stop the
applet window. See the arguments passed to this
applet, this message will be displayed on the screen.
method: text, which contains the string, “This is
You can visualize easily that even minimizing the
applet window stops or forces the applet into idle an example applet” and the x, y coordinates from
state. If restored after getting minimized, it will where this text will start in the displayable part of
again invoke start() and paint(). the applet. paint() is also called when the window
L17–19 These lines take care of the implementation containing applet is covered by another window and
of destroy(). Try closing the applet window and they later uncovered. (not minimized and restored)
you will see the message “……Exiting the applet” L22 You can see the method, showStatus() ,
(L19). Here, this message simply means that the having the text, which has to be shown in the status
applet is destroyed or has moved to the dead state. window of the applet, as argument.
If you wish that a drawing should appear in a window, you shall override either or both of the
methods. Let us discuss these methods in detail.
12.7.1 paint() Method
When a component needs to draw/redraw itself, its paint() method is called. The component
draws itself when it first becomes visible. The component paint() method is also invoked when
the window containing it is uncovered, if it is covered by another window.
The simplest paint() method looks like the following:
public void paint(Graphics g) {... }
We have discussed the Graphics object passed to the method earlier. It will be discussed in more
detail in the next chapter.
Example 12.3 Set the Color of the Applet and Draws a Fill Oval
/* <APPLET code = "FillOval.class" WIDTH = 200 HEIGHT = 200></APPLET> */
L1 import java.applet.Applet;
L2 import java.awt.Color;
L3 import java.awt.Graphics;
L4 public class FillOval extends Applet
{
L5 public void paint(Graphics g)
{
Applets 365
L6 g.setColor(Color.red);
L7 g.fillOval(20, 20, 60, 60);
L8 }
L9 }
Output
Explanation
L5–8 These lines are accountable for the class is invoked at L7. It fills an oval bounded
implementation of paint() method. The setColor() by the specified rectangle with the current color.
method of Graphics class is used to set the The parameters passed to the method are the
drawing color of the applet to red (L6). Another x-coordinate, y-coordinate, width, and height,
method, fillOval(), belonging to the Graphics respectively.
the update() method, and then the red oval will be drawn by the paint() method. A large area
of one color is first drawn and then the large area of the oval in another color (red in this case)
is redrawn. You, as a user can see some slight flickering while displaying the result, especially
if you try to draw the oval a number of times in succession.
The above problem can be overcome by overriding update(). You would override update()
to call paint(). Then this paint()will first draw only the background areas surrounding the red
oval and then draw the red oval. Obviously, the flickering problem found earlier is removed
because of elimination of the drawing of two overlapping objects of different colors.
12.7.3 repaint() Method
Sometimes you may want to force a component to be repainted manually. For example, if you
have changed certain properties of a component to reflect its new appearance, you can call the
repaint() method. Here is an example:
text.setBackground(Color.blue);
text.repaint();
repaint() in its default implementation calls update() which in turn calls paint(). repaint()
method requests the AWT to call update and it returns. The AWT combines multiple rapid repaint
requests into one request (usually this happens when you repaint inside a loop). So the last
repaint in the sequence actually causes paint(). We will discuss these topics in Chapters 13 and
14, where we will illustrate the use of repaint() with proper examples.
This is the most simplified form of APPLET tag, having only the mandatory fields as attributes.
Actually this particular tag has many more attributes which are optional but worth discussing.
The full syntax of the APPLET tag is shown below.
<APPLET [CODEBASE= codebasedURL]
CODE = appletFile [ALT= alternateText] [NAME = appletInstanceName] WIDTH
= pix els HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels]
[HSPACE = pixels]>
[<PARAM NAME = attributeName VALUE = attributeValue>]
[<PARAM NAME = attributeName VALUE = attributeValue>]
…………………………………
</APPLET>
Applets 367
In the above syntax, the attributes which are put inside the big braces are optional ones. Let us
discuss about the use of these attributes in detail.
Codebase Here, we may specify the URL of the directory where the executable class file
(specified by CODE attribute) of the applet will be searched for.
Code It gives the name of the file containing the applet’s compiled class file. It is a mandatory
attribute, which should always be present in APPLET tag.
Alt It is an attribute, which is used to specify the alternate short text message that should be
displayed in case the browser recognizes the HTML tag but cannot actually run the applet
because of some reason.
Name It is possible to give a name to an applet’s instance using this optional attribute. If any
other applet on the same web page wants to communicate with this applet, it is referenced
through its NAME only.
Width It gives the width of the applet display area in terms of pixels.
Height It gives the height of the applet display area in terms of pixels.
Align This optional attribute is used to set the alignment of an applet. The alignment can be
set as LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.
Vspace These are used to specify the space, in pixels, above and below the applet.
Hspace These are used to specify the space, in pixels, on each side of the applet.
You can use PARAM tags between the <APPLET> and </APPLET> tags to provide information
about parameters, or arguments, to be used by the Java applet. The <PARAM> tag is simple—it
NAMES a parameter the JAVA applet needs to run, and provides a VALUE for that parameter.
Let us take an example applet which uses the concept of passing parameters.
L1 import java.awt.*;
L2 import java.applet.*;
368 Programming in Java
Output
Explanation
Let us start with the APPLET tag placed as comment L4–6 References to the String class is declared as
before the actual code for the program starts. Three name and profession in L4 and L5, respectively.
PARAM tags are between the start and close of the A variable, age, of integer type is declared in L6.
APPLET tag. All the three PARAM tags have NAME L7–19 Implementation of start() method is
and its corresponding VALUE, such as yourName has shown. At L9, getParameter() method returns the
the value John, yourProfession has the value consultant value of the parameter name, yourName, passed
and yourAge has the value 35. as argument. The returned value is stored in name,
L1–2 For importing necessary classes from their declared at L4 as string reference. Similarly, two
respective packages. more getParameter() methods are used at L11
L3 A class named as ParamPassing is declared to and L14, returning the values for the respective
extend the Applet class of the java.applet package. parameters names passed as arguments. The use of
Applets 369
these values returned by getParameter() methods method of Integer class. This method throws
is too simple to be explained here. Only point worth an exception, named as NumberFormatException,
mentioning here is the use of wrapper class, Integer, which is caught at L18.
at L16. The value returned by getParameter() at L20–24 Implementation of paint() method is
L14 is of Stringtype, and it needs to be converted shown, where values for name, profession, and age
to integer, which is done by the use of parseInt() are displayed on the applet window.
Note The APPLET parameters stored in the PARAM tag actually have little directly to do with HTML.
As you have already seen in the previous example, that it is the responsibility of the applet to
check the parameter values and respond accordingly. One more interesting thing worth noting
here is that you can increase the flexibility of the applet by making the applet work in multiple
situations without recoding and recompiling it, by defining and redefining the parameters (as
these are placed as comments, so they are not checked during compilation).
We can sum up the use of PARAM tag for passing parameters to applets in two steps:
Place the PARAM tag with names and corresponding values between the start and end
of the APPLET tag.
Write the needed code for the applet to retrieve these parameter values, as shown in
Example 12.4.
Output
Fig. 12.7 Applet’s Code Base and Document Base are Displayed
Explanation
L1–3 All the classes belonging to different package is created with the name of url. At L8,
packages are imported, so that they can be made a getCodeBase() is called, which returns the URL
vailable to the program. We require the URL class object of the directory where the class file of the
of java.net package in the program, so we are applet is loaded. This returned object is stored in url.
importing all the package java.net (L3). At L9, the URL object stored in url is converted
L4 Public class ‘BaseMethods ’ extending the to string by using toString() and stored in str.
Applet class is declared. Similarly, you can see the use of getDocumentBase(),
L5–14 paint() method is overridden. A reference which returns the URL object of the directory that
to String class with the name of str is created at holds the HTML file, responsible for starting the
L6. Another reference of URL class of java.net applet at L11.
void showDocument(URL url); Replaces the Web page currently being viewed with the given
URL.
void showDocument (URL url, String target) Requests that the browser or applet viewer show the Web page
indicated by the URL argument.
void showStatus (String status) Requests that the argument string be displayed in the “status
window”.
The url, where you want your applet to transfer control to, is specified as the argument of this
method. You can use this method only with the object of the currently executing applet, which
can be obtained by getAppletContext() defined in the Applet class.
Once you have obtained the context of the currently executing applet, your browser or
appletviewer can show another document or web page by using showDocument(url).
There is another form of showDocument() method, having the signature,
public abstract void showDocument(URL url, String target)
The only new thing you see here is the second argument, target. This argument indicates in
which HTML frame the document is to be displayed. The target arguments can be used in
following forms as shown in Table 12.4.
Table 12.4 Values of the Argument of showDocument() Method
Target Argument Description
"_self" Show in the window and frame that contain the applet, i.e. the current frame.
"_parent" Show in the applet’s parent frame. If the applet’s frame has no parent frame,
it acts the same as “_self”.
"_blank" Show in a new, unnamed top-level window.
"_top" Show in the topmost frame of the applet’s window. If the applet’s frame is
the top-level frame, it acts the same as “_self”.
Name You can specify a name which causes the document to be shown in a
new browser window by that name.
372 Programming in Java
Note The file whose URL is passed as argument to the showDocument() method must be in same
directory on the server as the applet.
You can see the try…catch block around the showDocument() method. It has been put because this
method throws an exception named MalformedURLException which must be caught and handled.
This object actually encapsulates the audio clip found at the specified URL, passed as the
argument to the method (refer to Table 12.1).
We have already told that an applet can take care of audio also. There are various methods
defined in AppletContext interfaces that take care of manipulating the activities related to an
audio clip. A few of these methods are
play(): plays a clip from the beginning
stop(): stops playing the clip
loop(): plays the clip in loop continuously
The above methods can be used by the audio clip object (returned by getAudioClip()), to either
play, stop, or loop an audio clip. An example applet for loading and playing a sound file is given
below.
Explanation
L7 The clip is loaded during init() using object of the audio clip returned by the method
the getAudioClip() method, which takes the is stored in aud_clip.
url (from getDocumentBase() method) of the L8 The object aud_clip is used to invoke the
audio clip and the name of the audio file. The pay() method of AppletContext interfaces.
Note You can use the Java media framework API for playing sound files of different formats with
enhanced functionality.
Output
Fig. 12.8
Explanation
L1–2 Import the required packages; awt and method. We have used getDocumentBase() as the
applet. first argument to the getImage method for retrieving
L3 The applet html tag (commented) is inserted. the path (upto the base directory) where the applet
This html statement is commented so that it is is stored and the second argument is the Image
ignored by the complier as this code does not belong file name. getDocumentBase() will fetch the base
to Java. This html tag is inserted for running the directory of the applet as a URL object. We have
applet through the appletviewer utility. In case you fetched the base directory of the applet because
run the applet through html file, this tag should be the applet and the image are placed in the same
written within the body tag of the html file. directory. (Moreover you do not have to change
L4 All applets have to be publicly defined and the path every time you copy your applets to other
they must be subclasses of the Applet class. So directories or to a directory on different machines.)
ImageDemo is a public class and it inherits the Applet
L8–10 paint method defined to display the image
class. on the applet. The drawImage method is used to draw
L5 An instance variable of type Image is defined
an image on the applet. L9 shows how to draw an im-
outside (any of) the methods and within the Applet
age with its default height and width at a particular
class so that it can be used within all the methods
x–y position (second and third arguments) and L10
of the class.
shows how to change the height and width of the
L6–7 The image is instantiated inside the init
Image. The difference is evident in the output. The
method, which is called only once during the
lifetime of the applet. The image object is obtained current applet needs to be notified about the images
using the getImage() method and the path of the that is why this keyword is used as an argument in
image file is passed as an URL argument to this the drawImage method.
Applets 375
// second image
L14 imageArray[1] = getImage(getDocumentBase(), "bulbon.gif");
L15 m.addImage(imageArray[1], 1);
(OFF) (ON)
Fig. 12.9
Applets 377
Explanation
L1–2 Imports the awt and the applet packages. be invoked when this thread is started.
L3 Commented html APPLET tag meant to run L18–21 paint method is declared. L19 set the
the applet through the applet viewer utility. color as white. L20 fills the rectangle (i.e., entire
L4 Public class MediaTrackerDemo is declared to applet) with white color so it erases whatever
inherit the Applet class. is there on the applet in every paint attempt and
L5–8 Instance variables are created of type Image then restores the black color in L21. (It is better to
array, MediaTracker, Thread and an int variable whitewash the applet so that there is no overlapping
meant to change the images. Image array is defined of images).
to store images. MediaTracker instance will be L22 Checks whether all images have loaded and
tracking the status of images stored in the image if yes, draws the images on the applet using the
array. A Thread instance is required for changing the drawImage method in L23 else displays a string
images and it acts as a counter for deciding which mentioned in L27. We have already discussed the
image to be shown. drawImage method above.
L9–15 init method is defined for the applet. L24–25 Shows statements to change the images.
So all one-time initializations will be done in this We are using the current variable as an index into
method. L10 creates a MediaTracker object and the image array which is incremented to change
the image. The value of the current variable is
this is passed as an argument within the constructor
checked against the length of the image array (so
to signify the component on which the images will
that all images in the image array are shown) and
be drawn. L11 creates an image array of two images.
then reset to 0.
The image array is populated with two images in
L28 run method is defined to tell what the thread
L12 and L14 using the getImage method. We have
is supposed to do.
already discussed this method in the above example.
L29 try block defined to catch the exceptions
These images are added to the MediaTracker that arise in the code.
instance using the addImage method in L13 and L15. L30–33 waitForAll() method has been used on
The first argument is the image and the second is an the tracker object to wait for all images to finish
integer id which is used to track the image. loading and then an infinite loop is executed (L31)
L16–17 Instantiates the thread and starts it. to repaint (L32) the applet. Thread is made to sleep
Remember this (current object) is passed in the in L33 to introduce a delay effect.
constructor of Thread class to signify the object L34 Catches the exception raised by sleep method,
(i.e., the applet in our case) whose run method will if any.
Note The Graphics class is the abstract base class for all graphics contexts that allows an application
to draw onto components that are realized on various devices, as well as onto off-screen
images.
This class has a number of methods defined in it, some of which are mentioned below in Table 12.5.
Table 12.5 Few Methods of the Graphics Class
Name Description
drawArc(int x, int y, int width, int Draws the outline of a circular or elliptical arc covering the
height, int startAngle, int arcAngle) specified rectangle.
drawLine(int x1, int y1, int x2, int y2) Draws a line.
finalize() Disposes of this graphics context once it is not referenced.
Translates the origin of the graphics context to the point (x, y)
translate(int x, int y)
in the current coordinate system.
drawOval(int x, int y, int width, int Draws the oval.
height)
drawPolygon(int[] xPoints, int[] Draws a polygon defined by arrays of x and y coordinates.
yPoints, int nPoints)
drawRect(int x, int y, int width, int Draws the specified rectangle.
height)
getClip() Returns the bounding rectangle of the current clipping area.
fillArc(int x, int y, int width, int Fills a circular or elliptical arc covering the specified rectangle.
height, int startAngle, int arcAngle)
fillOval(int x, int y, int width, int Fills an oval bounded by the specified rectangle with the
height) current color.
fillPolygon(int[] xPoints, int[] Fills a closed polygon defined by arrays of x and y coordinates.
yPoints, int nPoints)
fillRect(int x, int y, int width, int Fills the rectangle.
height)
getColor() Returns this graphic context’s current color.
getFont() Returns the current font.
setColor(Color c) Sets the drawing color.
setFont(Font font) Sets this graphic context’s font to the specified font.
fillRoundRect(int x, int y, int Fills the specified rounded corner rectangle with the current
width, int height, int arcWidth, int color.
arcHeight)
drawRoundRect(int x, int y, int Draws an outlined round-cornered rectangle using this graphic
width, int height, int arcWidth, int context’s current color.
arcHeight)
drawString(String str, int x, int y) Draws the string on the specified coordinates.
clearRect(int x, int y, int width, int Clears the specified rectangle by filling it with the background
height) color of the current drawing surface.
(Contd)
Applets 379
L8 g.drawLine(100,10,230,140);
L9 g.drawLine(100,140,230,10);
}}
Output
Here, we will stick to the paint() method only as all the methods of the Graphics class are used
inside this method only. The description of these methods is available in Table 12.5.
Explanation
L2 The drawRect method is used to draw a rect- fillRoundRect is same as drawRoundRect. The only
angle. The first two arguments specify the x and difference is that in this case the rounded rectangle
y coordinates and later two specify the width and is filled with a color.
height of the rectangle. L7 drawArc method is used to draw an arc
L3 The fillRect method is used to draw a (as shown in the output). The first argument is x
rectangle that is filled with a color. The default color coordinate of the upper left corner of the arc to be
is black. You can always change the color using the drawn. The second argument is the y coordinate of
setColor method. the upper left corner of the arc to be drawn. The
L4 The fillOval method is used to draw an oval third and fourth argument specifies the width of
that is filled with the default color. The first two the arc and height of the arc. The fifth argument
arguments specify the x and y coordinates and the is the starting angle of the arc. The arcs begin at
latter two specify the width and height of the oval. starting angle and extend to arc angle which is the
L5 and 6 The drawRoundRect method is used last argument.
to draw a rectangle with rounded corners. The L8 and 9 drawLine is used to draw lines between
additional arguments (last two) are the width of points x1, y1 and x2, y2 (which are specified as four
the arc (i.e., 10) and height of the arc (i.e., 10). arguments to this method.)
from specifying a particular color, you can also create your own color in Java. It is an astonishing
fact; you can create up to 24 million different colors in Java. Color class has various constants
specifying a number of common colors. These constants are as shown below:
Color.Black Color.DARK_GRAY Color.GRAY
Color.LIGHT_GRAY Color.WHITE Color.MAGENTA
Color.RED Color.PINK Color.ORANGE
Color.YELLOW Color.GREEN Color.BLUE
Some of the constructors and methods of Color class are shown in Table 12.6
Table 12.6 Color Class
Constructor of Color Class
Constructor Description
Color(Color space cspace, float[] Creates color in a specific ColorSpace with specified color
components, float alpha) components.
Color(float r, float g, float b) Creates a mix color of red (r), green (g), and blue (b) and the
values are in the range of (0.0–1.0).
Color(float r, float g, float b, float a) Creates a mix color of red, green, and blue and alpha () values
in the range of (0.0–1.0).
Color(int rgbValue) Creates a mix color of red, green, and blue and the
bits for red component is 16–23, bits for green component is
8–15, and bits for blue component is 0–7.
Color(int r, int g, int b) Specify a color of mix red, green, and blue values in the range
of (0–255).
Color(int r, int g, int b, int a) Creates a color of mix colors red, green, blue, and alpha values
in the range of 0–255.
Methods of Color Class
Methods Description
brighter() Creates a brighter version of a color.
createContext(ColorModel cm, Rectangle This method is used to create a solid color pattern.
r, Rectangle2D r2d, AffineTransform
xform, RenderingHints hints)
darker() Creates a darker, brighter version of a color.
decode(String nm) It translates a String to an integer that returns the specific
Color.
equals(Object obj) Checks that another object is equal or not to this Color.
getAlpha() Returns an alpha component whose range is 0–255.
getBlue() A blue component is returned by this method in the range
0–255 in the default red, green, blue space.
getColor(String nm) Finds a color in the system properties.
(Contd)
382 Programming in Java
Methods Description
getColorComponents(ColorSpace cspace, A float array is returned. It contains color components
float[] compArray) specified by the escape parameter.
getColorSpace() ColorSpace of the Color is returned by it.
getComponents(float[] compArray) An array of float type is returned which contains the color
and alpha components of the Color.
getGreen() A green component is returned by it in the range
0–255 in the default red, green, blue space.
getRGBComponents(float[] compArray) An array of float type is returned which contains color and
alpha components of the Color which represents red, green,
blue color space.
HSBtoRGB(float hue, float saturation, float Using HSB model, it returns a packed RGB value with the
brightness) help of Color(int) constructor.
RGBtoHSB(int r, int g, int b, float[] The color of component is converted to HSB model specified
hsbvals) by RGB model.
toString() A color is represented as a string.
How to create your own color? Let us take an example constructor for creating a light ‘red’
color object.
We can use the fifth constructor from Table 12.6 for the purpose,
Color c= new Color (255, 100, 100)
Once a color object is created by using any of the above constructors, it can be used to set the
foreground and background colors by using the setForeground() and setBackground() methods,
respectively.
The constructors of color class and some of its methods are listed in Table 12.6 along with
their description.
more method belonging to the same class is getAllFonts(), which returns an array of font objects
of all the available fonts.
As mentioned above, these methods belong to GraphicsEnvironment class, so we would need a
reference to this class for calling these methods. There is a static method in GraphicsEnvironment
class, named getLocalGraphicsEnvironment(), which returns this reference. The signature of this
method is follows:
static GraphicsEnvironment getLocalGraphicsEnvironment()
Example 12.10 clarifies the use of this method. The next question is, how to create and select
a new font? For this, you need to construct a Font object, describing that font. Obviously, one
of the constructors mentioned in Table 12.7 will help in constructing a Font object. Let us talk
about the second constructor of the table, i.e.,
Font(String name, int style, int size)
Once the font is created, setFont() method of component class is used to select it. The signature
of this method is as follows:
void setFont(Font fontObject)
Here the argument fontObject is the object that contains the desired font.
If you have a font and you want to get information about that font, getFont() method of
Graphics class will be helpful. It returns the current font. It has the following signature:
Font getFont()
Once you have obtained the current font, you can easily get the other related information about
the font using the various methods of Font class, like getName(), getStyle(), getSize(),
getFamily(), etc. (for more details, refer to Table 12.7). The following example shows the use
of Color and Font classes.
Output
The output of the above program shows the available fonts on the machine as well as some
sentences painted, using the Font class, on the applet window:
386 Programming in Java
Fig. 12.11 Output Showing Available Fonts and How to Use Color Class
Explanation
L1 All the required classes of AWT package are L12–16 In L12, for loop is used to increment the
imported. integer, i, by 1, till it reaches the maximum size of
L2 A class named as ColorFont extending the the array, i.e., the length of the array. Each element
Applet class is declared. of the array FontList is drawn on the applet surface
L3–6 init() is declared and implemented, using drawstring() (L15).
where a reference to the Color class with the name L17 Another object of the Color class, color2 is
of color1 is created in L4. The arguments passed constructed.
to the constructor, Color(), are responsible for the L18 Graphics class reference is used to set the
output color, which you are seeing in the output Color to color2, using setColor(). This color is
window. These arguments are integer values set for the text to be displayed on the applet.
signifying red, green, and blue, respectively (in L19 drawString() is used to display the string,
the range of 0–255). Once the Color object is “Hey Look!!!” on the x and y coordinates specified
created in L5, it is passed to setBackground(), as the second and third argument respectively of the
responsible for setting the background of the applet drawString().
window as per the color mix. L20 Constructor belonging to Font class is
L7 The paint() method, with graphics reference used to construct a Font object, currentFont,
as argument, is declared. This method ends at L26. encapsulating font name as ‘Times New Roman’,
L9 An array of String is declared as FontList. Font style as ‘Font.PLAIN’ and font size as 20 (see
L10 The getLocalGraphicsEnvironment() the constructor’s arguments).
method of GraphicsEnvironment class returns the L21 Reference of Graphics class is used to call
reference to GraphicsEnvironment, which is stored setFont() of component class to set the font to
in ge. ‘currentFont’.
L11 The getAvailableFontFamilyNames() method, L22 drawString() is used to display the string
which returns the array of fonts available on machine, Thisisanexample at the location specified as
is called using the reference ge. The resultant array is arguments of the method.
stored in array, FontList, declared at L9.
Italic angle
I
Ascent
Line X-height
height
Origin
Descent
Baseline
FontMetrics Object
Font metrics are determined by the font and the graphics context. To create a FontMetrics object,
where g is a Graphics object and f is a font object, the following constructor can be used:
FontMetrics fm = g.getFontMetrics(f);
The object fm is created to find out the height and width information about a specified Font and
specific character glyphs in that Font.
FontMetrics Methods
Table 12.8 provides a brief description of the methods in FontMetrics class.
Table 12.8 Methods of FontMetrics Class
Method Description
bytesWidth(byte[] data, int off, int len) Width to show a specific array of bytes in this font is returned.
charsWidth(char[] data, int off, int len) Width to show a specific array of character in this font is
returned.
getAscent() Font ascent is determined by it.
getDescent() Font descent is determined by it.
(Contd)
388 Programming in Java
Output
Explanation
L1–2 The required packages are imported. as per the mixture of colors specified as numbers.
L3 A class named DemoFontMetrics extending L8 paint() method is defined.
the Applet class is declared. L9 An integer variable named fontSize is
L4 init() method is overridden. declared.
L5 The arguments passed to the constructor, L10 A method named setFont() is used to set
Color(), are responsible for the output color, which font and its size.
you are seeing in the output window, in Fig. 12.13. L11 A FontMetrics object fm is created.
These arguments are integer values signifying red, L12 A string is declared.
green, and blue colors respectively (in the range of L13 An integer variables w has been created to
0–255). Once the Color object is created, in L6, it denote the width of string.
is passed to setBackground() method, responsible L14–15 Two integer variables (w and h ) are
declared for positioning of string. w and h actually
for setting the background of the applet window
denote the width and height of the applet.
390 Programming in Java
L16 x coordinate is calculated by subtracting the L21–22 It will fill pink color into the specified area.
string width from the width of the applet and then L23–24 We have drawn a red line below the string
dividing it by 2. This will form the x coordinate of using drawLine() method.
the string to be printed on the applet. L25–26 We have drawn a blue line above the
L17–20 In these lines, we have calculated String using drawLine() method.
baseline, ascent, fontHeight, descent, values L27–28 drawString() method is called to draw
for positioning of string using getMaxAscent(), the string and setColor() is used for setting black
getAscent(), and getMaxDescent() methods. color.
{
L26 g.setFont(new Font("Courier New", Font.ITALIC, 20));
L27 g.drawString(d.toString(),30,20);
L28 g.drawString("Different Format " +df.format(d),30,40);
}
}
Output
Fig. 12.14
Explanation
L1–4 Imports the required packages: java. DateFormat is an abstract class so it cannot be
util, java.applet, java.awt, and java.text. instantiated directly. It is instantiated in L14 using
Date and Calendar classes belong to java.util the getInstance() static method of the DateFormat
package; Applet class belongs to java.applet class which returns an instance of the DateFormat
package, Graphics class is of java.awt package class.
and DateFormat belongs to java.text package. L15–24 The run method for the thread is defined
L5 The applet html tag (commented) is inserted. which specifies what the thread is supposed to do.
This html statement is commented so that it is The method is supposed to extract the current date
ignored by the complier, as this code does not belong and time and set it in the Date object. The current
to Java. This html tag is inserted for running the date and time is extracted using the abstract class
applet through the appletviewer utility. Calendar whose instance is created in L19 using
L6 Public class DigitalClock is declared to the static method getInstance() of the Calendar
inherit the Applet class and Runnable interface. class. The getTime() method is used on the Calendar
All applets have to be publicly defined and they instance to obtain Date object. L21 uses the sleep
must be subclasses of the Applet class. In case you method to delay the thread by one second. Even in
wish to create threads in an applet, it must inherit case of an exception, the paint() method is invoked
the Runnable interface. by invoking the repaint() method.
L7–10 Instance variables of type Thread, Date, L25–28 All display functionality in an applet lies
Calendar, and DateFormat are defined within the within the paint() method, so it is the responsibility
applet. The objects of these types will be used of the paint() method to display date and time
throughout the DigitalClock applet. stored in the Date object. L26 uses setFont method
L11–14 init method is defined for the applet. on the Graphics object to set the font and its size.
All one time activities for the Digital clock can drawString() is used in L27 to write strings on
be done here. So we have initialized the Thread the applet at a particular x,y location. The first
and started it. We have also used the DateFormat argument to this method is the Date object which
class in our example to specifically show how to displays the string in its standard format (see first
represent the date and time in a different format. line of the output). L28 shows how to format the date
392 Programming in Java
using the DateFormat object created in L14. The output). The first line of the output display time in a
format() method of the DateFormat class is used to 24 hr format with day of the week and month name.
format the Date object passed to it as an argument. The second line of the output display Date and Time
This method returns a formatted time string which in a 12 hr format with AM and PM along with date,
is passed to the drawString method and hence it month, and year in numeric format.
is displayed on the applet (see second line of the
Note DigitalClock applet cannot inherit the Thread class because it has already inherited the
Applet class. Therefore Runnable interface is used. (Remember: Java does not support
multiple inheritances among classes)
SUMMARY
We have explained the meaning and the use of applets states of applet life cycle are: Born, Running, Idle, and
in this chapter. Applets are small programs which can Dead. Different methods such as init(), start(),
be downloaded from a remote server in its bytecode stop(), and destroy() are respectively called to
form and executed on the client, to do a specific job. force an applet to different state. We have given you
The differences between applets and applications have an insight of how to handle images and audio files and
already been listed out. have a basic understanding of graphics.
In Java, applets are discussed in two different We have not discussed all the methods of the Applet
packages. One is the conventional applet, which has class. But of course, we have dealt with many of them
directly evolved from Applet class. These applets use
in great detail. By now, you must have got an insight
Abstract Window Toolkit (AWT) to get the GUI features.
of the applet programming and the way the methods
Other one uses swings, which we have not taken up
are used in applet programming. Now that the building
in this chapter. These applets can be executed on the
blocks for applets have been covered in this chapter,
clients, with the help of either a Java-enabled browser
or a utility known as appletviewer (comes as a part the very essence of applet programming will seem
of JDK). We have discussed many methods belonging to be more meaningful when we talk about the GUI
to the Applet class. Applets have a proper life cycle in environment presented by ‘Event Handling and AWT’,
which an applet moves from one state to other. These in Chapter 13.
EXERCISES
Objective Questions
1. Which of the following is not a method of an 5. Which class provides the functionality to draw
applet’s lifecycle? different shapes?
(a) init (b) start (a) Line (b) Graphics
(c) sleep (d) stop (c) Shapes (d) Graph
2. Which tool is used to compile an applet? 6. Which method is used to know the directory name
(a) java (b) javac from where the Applet class is loaded?
(c) appletviewer (d) appletc (a) getCodeBase()
(b) getDocumentBase()
3. Which tool is used to execute an applet? (c) getClassName()
(a) java (b) javac (d) getAppletLoadClass()
(c) appletviewer (d) appletrunner
7. setFont method belongs to which of the following
4. Which method implicitly calls paint on an applet? classes?
(a) paint (b) repaint (a) Component (b) Object
(c) start (d) callPaint (c) Thread (d) Font
Applets 393
8. Which of the following does the same job as the 10. Which method of the AppletContext interface
paint method? enables your applet to transfer the control to any
(a) init (b) update other URL?
(c) stop (d) destroy
(a) showPage() (b) showDocument()
9. What methods are called as soon as an applet
(c) displayDocument() (d) show()
is loaded?
(a) init, start, paint (b) init, start
(c) init (d) start, paint, stop
Review Questions
1. What are applets? Differentiate them from 6. Differentiate update() and repaint() methods.
application. 7. How can a message from a HTML page be
2. State the different ways of executing an applet. passed to an applet?
3. What is the significance of Applet class in 8. Explain the different parameters of APPLET tag.
creating an applet? Also explain the hierarchy 9. State the names of the respective classes which
of Applet class. the following methods belong to. Also explain the
4. Describe the complete life cycle of an applet. use of these methods:
5. Explain the use of overriding the following showStatus() drawstring ()
methods for an applet getCodeBase() getDocumentBase( )
init() start() getBackground() getForeground()
stop() destroy() setBackground() setForeground()
paint() getParameter()
Programming Exercises
1. Write a program that shows a screen shot with 4. Write an applet to get the foreground and
an applet running inside the applet viewer. The background colors of the above applet.
applet should display your name. 5. Write a program to display the URL of the
2. Write an applet that places a rectangle, a rounded directory containing your .class file and .html file.
rectangle, a 3D rectangle, and a fill rectangle 6. Write an applet that reads an indefinite number
of random sizes and colors inside the applet’s of strings from PARAM tags and draws them.
visible area. 7. Write an applet that draws a circle, a line, an arc,
3. Create an applet having the background color and a polygon inside the applet’s visible area.
as black and the foreground color as white.
learn three ways of event handling: listeners, adapters, and inner classes
13.1 INTRODUCTION
We have learnt about objects and classes in the previous chapters. An object resides in a particular
state until it is made to transit to the other state. This transition occurs due to an event.
For example, we want an object to invoke a function when an action is generated, e.g.,
pressing a key on the keyboard, moving the mouse, clicking on a button, etc. The object which
generates the event, i.e., the source of the event is known as the event generator. If a button
is pressed for an operation, the button is the event generator. The object that is responsible for
performing the task when the event occurs is called the event handler. There may be more than
one event handlers for one single event generated; each event handler responsible for doing a
unique activity on account of that particular event. Now the question is, how do these handlers
know that a particular event has occurred so that they can perform their activity? For this,
there is a registration process, undertaken by the event object, for each of its event handlers.
This registration involves the event handler simply asking the event generator to inform about
the occurrence of an event. By registering, the event generator is able to keep track of all the
registered event handlers.
This chapter deals with the event handling mechanism of Java. Without these concepts, it is
impossible to enter into the world of GUI programming.
Event Handling in Java 395
Herein, we will discuss the events defined by AWT. Various possible events in Java are predefined
as classes. Some of the main event classes defined in java.awt.event package are shown in
Table 13.1.
Table 13.1 Event Classes
Event classes Description
ActionEvent Generated when a component-defined action occurred (on button, List, Menu).
AdjustmentEvent When scrollbar is adjusted.
ContainerEvent When an element is added or removed from a container.
FocusEvent When a component gains or loses focus.
KeyEvent When input is received from keyboard.
ComponentEvent When a component is moved, changed size, or changed visibility (also, the
root class for the other component level events).
MouseEvent An event which indicates that a mouse action occurred in a component.
InputEvent The root class for all component-level input events.
TextEvent When an object’s text is changed.
WindowEvent When a window has changed its status.
MouseWheelEvent When a wheel was rotated in a component.
ActionEvent Class
An actionEvent class is defined in Java as
public class ActionEvent extends AWTEvent
ActionEvent is an event which indicates that a component-defined action has occurred. This event
is generated by a component (such as a Button) when the component-specific action occurs (such
as a click). The event is passed to an ActionListener object which is registered to receive the
event notification using the component’s addActionListener method. The object that inherits
the ActionListener interface is passed to the ActionEvent when an event occurs. Some of the
fields, constructors, and methods associated with the ActionEvent class are given in Table 13.2.
Table 13.2 ActionEvent Class
Field Summary
Field Name Description
ACTION_FIRST The first number in the range of IDs used for action events.
ACTION_LAST The last number in the range of IDs used for action events.
ACTION_PERFORMED This event ID indicates that a meaningful action occurred.
ALT_MASK The alt modifier, an indicator that the alt key was held down during the
event.
CTRL_MASK The control modifier, an indicator that the control key was held down
during the event.
(Contd)
Event Handling in Java 397
AdjustmentEvent Class
AdjustmentEvent class is defined in Java as,
public class AdjustmentEvent extends AWTEvent
The adjustment events are generated by adjustable objects like scroll bar. There are some
adjustment events defined by AdjustmentEvent class, identified by corresponding integer
constants. These constants and their meanings are shown in Table 13.3. It also enlists the
constructor and methods of AdjustmentEvent class.
Table 13.3 AdjustmentEvent Class
Field Summary
Field Name Description
ADJUSTMENT_FIRST Marks the first integer id for the range of adjustment event ids.
ADJUSTMENT_LAST Marks the last integer id for the range of adjustment event ids.
ADJUSTMENT_VALUE_CHANGED The adjustment value changed event.
(Contd)
398 Programming in Java
KeyEvent Class
This class is defined in Java as,
public class KeyEvent extends InputEvent
This low-level event is generated by a component object (such as a text field, Applet, frame)
when a key is pressed, released, or typed. The event is passed to a KeyListener object which
is registered to receive the event notification using the component’s addKeyListener method.
KeyEvent is an event which indicates that a keystroke occurred in a component. There can be
three types of key events, which are identified by integer constants. These are
KEY_PRESSED (it is generated when any key is pressed)
KEY_TYPED (it is generated if a valid unicode character could be generated)
KEY_RELEASED (it is generated when any key is released)
There are some more integer constants that are defined in KeyEvent. Table 13.4 shows a few of
them. All fields of this class are public static and final. It also lists the constructors and methods
of the keyEvent class.
Event Handling in Java 399
The list is very long and we are unable to incorporate the complete exhaustive list here. Apart
from the constants shown in Table 13.4, we have integer constants such as, VK_0 through VK_9,
VK_A through VK_Z, VK_ALT, VK_Cancel, VK_SHIFT, VK_PAGE_DOWN, VK_ENTER,
VK_ESCAPE, VK_CONTROL, etc., as members of the KeyEvent class.
Table 13.4 KeyEvent Class
Field Summary
Field Name Description
char CHAR_UNDEFINED KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode
character use this for the keyChar value.
int KEY_FIRST Denotes the first number in the range of ids used for key events.
int KEY_LAST Denotes the last number in the range of ids used for key events.
int KEY_LOCATION_LEFT A constant indicating that the key pressed or released is in the left key location
(there is more than one possible location for this key).
int KEY_LOCATION_NUMPAD A constant indicating that the key event originated on the numeric keypad or
with a virtual key corresponding to the numeric keypad.
int KEY_LOCATION_RIGHT A constant indicating that the key pressed or released is in the right key
location (there is more than one possible location for this key).
int KEY_LOCATION_ A constant indicating that the key pressed or released is not distinguished as
STANDARD the left or right version of a key, and did not originate on the numeric keypad
(or did not originate with a virtual key corresponding to the numeric keypad).
int KEY_LOCATION_UNKNOWN A constant indicating that the keyLocation is indeterminate or not relevant.
int VK_ACCEPT Constant for the Accept or Commit function key.
int VK_ALL_CANDIDATES Constant for the All Candidates function key.
int VK_ALPHANUMERIC Constant for the Alphanumeric function key.
int VK_COMMA Constant for the comma key, “,”
int VK_COMPOSE Constant for the Compose function key.
int VK_CONTEXT_MENU Constant for the Microsoft Windows Context Menu key.
int VK_WINDOWS Constant for the Microsoft Windows “Windows” key.
Constructor Summary
Constructor Name Description
KeyEvent (Component
Constructs a KeyEvent object, where
source, int id, long
Source—the component that originated the event.
when, int modifiers, int
keyCode, char keyChar)
Id—an integer identifying the type of event.
When—a long integer that specifies the time the event occurred.
Modifiers—the modifier keys down during event (shift, ctrl, alt, meta) Either
extended _DOWN_MASK or old _MASK modifiers should be used, but
both models should not be mixed in one event.
(Contd)
400 Programming in Java
MouseEvent Class
MouseEvent class is defined in Java as,
It is an event which indicates that a mouse action occurred in a component. A mouse action
occurs in a particular component if and only if the mouse cursor is over the defined part of the
component’s bounds when the action happens.
There are eight types of mouse events defined in the MouseEvent class. The MouseEvent class
defines them as public static integer constants to identify each of these events. These are shown
in Table 13.5. It also shows the constructor and methods of MouseEvent class.
Table 13.5 MouseEvent Class
Field Summary
Field Summary Description
MOUSE_MOVED Event occurs when mouse wheel is moved.
(Contd)
Event Handling in Java 401
FocusEvent Class
FocusEvent class is defined as,
This event is generated when a component gains or loses focus. There are two types of focus
events: permanent and temporary. Permanent focus event occurs when the user explicitly changes
focus from one component to other, e.g., by pressing the tab key. Temporary focus event occurs
when the focus is lost due to operations like window being deactivated. In this case, when the
window will again be activated, the focus will be on the same component. The fields, constructors,
and methods of FocusEvent class are shown in Table 13.6. All the fields of FocusEvent class are
public static integer constants.
Table 13.6 FocusEvent Class
Field Summary
Fields Name Description
FOCUS_FIRST First to gain focus.
FOCUS_LAST Last to gain focus.
FOCUS_GAINED Component focus gained.
FOCUS_LOST Component focus lost.
Constructor Summary
Constructor Name Description
FocusEvent(Component src, int id) Creates a FocusEvent object with src specifying the source of
event and id is like FOCUS_GAINED or FOCUS_LOST.
FocusEvent(Component src, int id, In addition to the above constructor, temp identifies change is
boolean temp) temporary or not.
FocusEvent(Component src, int id, In addition to the above, opp identifies the other component
boolean temp, Component opp) involved in change.
Method Summary
Methods Name Description
Component getOppositeComponent() Return the component that either got focus or lost focus.
boolean isTemporary() Tells whether event is temporary or permanent.
String paramString() Returns a string identifying the event.
ItemEvent Class
ItemEvent class is defined as,
public class ItemEvent extends AWTEvent
It is an event which shows whether an item was selected or de-selected. This event is generated
by an ItemSelectable object (such as a list), where the event is generated when an item of
the list is either selected or de-selected. The event generated is passed to every ItemListener
object which is registered to receive such events. The method addItemListener() is used for
this registration process. The fields, constructors, and methods of ItemEvent class are shown
in Table 13.7. All fields of this class are public static integer constants.
Event Handling in Java 403
TextEvent Class
TextEvent class is defined as,
This event indicates the change in the object’s text. This event is generated by an object (such as a
TextComponent) whenever its text changes. The event is passed to every TextListener object which
is registered to receive such events. The method addTextListener() is used for this registration
process. The fields, constructor, and methods of TextEvent class are shown in Table 13.8.
Table 13.8 TextEvent Class
Field Summary
Field Name Particulars
TEXT_FIRST The first number in the range of ids used for text events.
TEXT_LAST The last number in the range of ids used for text events.
TEXT_VALUE_CHANGED This event id indicates that object’s text changed.
Constructor Summary
Constructor Name Particulars
TextEvent(Object source, int id) Constructs a TextEvent object.
Methods Summary
Method Name Particulars
String paramString () Returns a parameter string identifying this text event.
404 Programming in Java
The classes pertaining to these GUI components will be discussed in detail in Chapter 14 (AWT).
Each of these listener interfaces have certain number of methods, which are given in brief below.
KeyListener Interface
This interface has three methods defined within it:
void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
keyPressed() is invoked when a key is pressed, keyReleased() is invoked when a key is released,
and keyTyped() is invoked when a character is typed.
MouseListener Interface
This interface has five methods, having the signatures as follows:
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseExited(MouseEvent e)
Event Handling in Java 405
ItemListener Interface
This interface has only one method defined as,
void itemStateChanged(ItemEvent e)
itemStateChanged() is invoked when the state of the item changes.
ActionListener Interface
This interface has only one method having the signature,
void actionPerformed(ActionEvent e)
The method, actionPerformed() is invoked when any action event is performed.
TextListener Interface
This interface has only one method having the signature,
void textChanged(TextEvent e)
This method is invoked whenever there is a change in text field or text area.
FocusListener Interface
This interface has two methods,
void focusGained(FocusEvent e)
void focusLost(FocusEvent e)
focusGained() is invoked when the component obtains keyboard focus and focusLost() is
invoked when the component loses the keyboard focus.
WindowListener Interface
This interface has seven methods defined in it, with the following signatures:
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
406 Programming in Java
void windowClosing(WindowEvent e)
void windowOpened(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowIconified(WindowEvent e)
void windowDeiconified(WindowEvent e)
windowActivated() is invoked when window is activated, windowDeactivated() is invoked when
the window is deactivated, windowClosed() is invoked when the window is closed, windowOpened()
is invoked when the window is opened, windowClosing() is invoked when the window is
being closed, windowIconified() is invoked when the window is iconified (minimized), and
windowDeiconified() is invoked when the state of the window changes from minimized to normal state.
ComponentListener Interface
This interface has four methods, having the signatures as follows:
void componentResized(ComponentEvent e)
void componentMoved(ComponentEvent e)
void componentHidden(ComponentEvent e)
void componentShown(ComponentEvent e)
componetResized()is invoked when the size of the component is altered, componentMoved() is
invoked when the component is moved, componentHidden() is invoked when the component is
hidden, and componentShown() is invoked when the component is shown.
ContainerListener Interface
This interface has two methods defined in it. They are
void componentAdded(ContainerEvent e)
void componentRemoved(ContainerEvent e)
Both of the above methods, componentAdded() is invoked when a component is added to the
container and componentRemoved() is invoked when a component is removed from the container.
AdjustmentListener Interface
The interface has only one method, defined as
void adjustmentValueChanged(AdjustmentEvent e)
The method is invoked when an adjustment event occurs.
In the above method, Type is the type of the event and tl is the reference to the event listener for
that particular event. Different types of event listeners available in Java can be seen in Table 13.10.
Event Handling in Java 407
Some sources allow more than one listener to get registered to receive the event, while some
allow only one listener to get registered to receive the event. Former is the case of multicasting
an event while the latter is unicasting an event.
These listeners, once registered for events from a particular source, can get unregistered also.
The form of method used for this unregistration process is as follows:
public void removeTypeListener(TypeListernertl)
Once the listener objects are registered, they must implement the methods to receive and process
the event notifications sent by source. These methods are defined in various interfaces of
java.awt.event package.
Steps involved in using the event delegation model:
1. Implement the appropriate event listener interface so as to receive and process the type
of event desired.
2. Register event listener with event source, as the recipient for event notification using
the registration methods which have the following form:
addTypeListner(TypeListener)
Note If the component generates more than one event, then each event needs to be registered
separately. An object may be registered to receive several types of events, but it must also
implement all the interfaces that are required to receive these events.
Let us take an example to show how listener interfaces are used for handling events. The following
example shows how MouseMotionListener can be used to track mouse movements.
Output
Explanation
L1–3 All the required packages are imported, so interface. This class would override the methods
that their members can be used inside the program. of MouseMotionListener interface and now
L4 Handler class with the name MouseMotionEx this classes object will be passed in registration
declared. This class extends Applet class and method: addMouseMotionListener (new Demo()).
implements the MouseMotionListener so that it can Note now MouseMotionEx will not inherit the
receive the type of event desired. MouseMotionListener interface. Example 13.1(a)
L5–6 Instance variables, xcord and ycord, to shows this concept.]
store the value of x-coordinate and y-coordinate are L10–12 paint() is defined and implemented,
declared to be of integer type. where the drawstring() method of the graphics
L7–9 Inside init() method of applet, the class is used to display the string at x and y
MouseMotionListener is registered as the recipient
coordinates. The string here is the value of x and y
of the event notification. coordinates inside parenthesis.
L8 The MouseMotionListener have been
L13–17 mouseMoved() defined in MouseMotion-
registered on the Applet itself (event source).
Listener interface is implemented. This method
The question arises: Why is ‘ this ’ passed as
actually takes care of the action to be performed on
an argument to add MouseListener method?
a mouse event (see the MouseEvent object being
Because the MouseMotionEx has implemented
MouseMotionListener interface and overrides the
passed as argument to the method in L13). Instance
methods of the interface, the current object will tell variables, xcord and ycord, declared earlier as in-
how to handle the event once the mouse is moved tegers are used to store the values of x-coordinate
or dragged. So ‘this’ (current object) is passed as and y-coordinate returned by the getX() and getY()
an argument to addMouseMotionListener method. methods of MouseEvent, respectively (L14 and L15).
[We can also create another class (e.g., Demo ) In L16, repaint()is called, which ultimately calls
which would implement MousemotionListener the paint method.
We can rewrite Example 13.1(a) as follows to show how another class object can be used to
process the events.
Event Handling in Java 409
Demo(MouseMotionEx m)
{
this.m=m;
}
public void mouseMoved(MouseEvent me) {
m.xcord = me.getX();
m.ycord = me.getY();
m.repaint();
}
public void mouseDragged(MouseEvent me){}
}
Explanation
One important thing to note is that while Demo’s tionEx need to be set based on mouse movements
objects have been registered for event notification, and later MouseMotionEx needs to be repainted. So
the current object (i.e., MouseMotionEx object) has we need a reference to MouseMotionEx to perform
been passed to the Demo object. The reason is we this task and that’s why the object of MouseMotionEx
need to paint the applet (i.e., MouseMotionEx object) (represented by this keyword) has been passed in
based on mouse movement which are being tracked Demo’s constructor.
by demo’s object now. The coordinates of MouseMo-
410 Programming in Java
See the empty curly braces for the above two methods, which simply show the body of the
methods to be empty.
13.7.1 How to Use Adapter Classes?
If you are not using adapter classes, your event handler class needs to implement listener
interface as,
public class HandlerClass implements MouseMotionListener
{
………………………………………………
………………………………………………
……………………………………………
}
And as mentioned earlier, the handler class, which is here named as HandlerClass has to implement
all the methods inside that MouseMotionListener (as shown in Example 13.1 (a)).
Now if you use the adapter class, the handler class will inherit from adapter class by extending it.
Event Handling in Java 411
Due to inheritance, all the methods of the MouseMotionAdapter class will be available inside
our HandlerClass. As the adapter classes have already provided definitions with empty bodies,
you do not have to provide implementations for all the methods again. It simply means we only
need to override our methods of interest. Let us take Example 13.1(a) where we had to override
all the methods of MouseMotionListener within the handler class. But in order to achieve the
same objective as in Example 13.1(a), we now show the use of adapter classes and how its use
makes things simpler in writing the code. Note that in the following adapter class example, it
is not mandatory to override all the methods of MouseMotionlistener; only the method (here,
mouseMoved()) is overridden.
Output
Explanation
L6–8 Applet’s init() method is implemented, L12 The end of the class AdapterDemo specified
where in MouseMotionListener is registered. An by closing parenthesis.
interesting thing which is to be noted here is the L13 Class MouseDemo, extending MouseMotion-
method of registration. See the argument passed Adapter is declared.
through the method of registration in L7. Till the L14 A reference to AdapterDemoclass is created.
last example we passed the current class’s object L15–17 A constructor of MouseDemo is declared and
to this method. But here, we pass the object of object of AdapterDemo class is passed as an argument
the current class (AdapterDemo) to the constructor to this constructor (L15). The member of the object
of the class extending the adapter class (i.e., constructed by the constructor is initialized with the
MouseDemo) and ultimately the object of the class object of class AdapterDemo (L16).
extending the adapter class is passed as an argument L18–22 The mouseMoved() method with Mou-
seEvent object as argument is defined and imple-
to the addMouseMotionListener() (L7), used
mented. MouseEvent object is used to call the getX()
for registering the MouseMotionListener as the
and getY() methods in L19 and 20, respectively.
recipient of mouse event notifications. All this is
getX() returns the value of x-coordinate and getY()
done, so that the methods of different classes can
returns the value of y-coordinate. In L16, repaint()
communicate with each other through their objects. of the Applet class is called using the reference of
L9–11 Graphics object is used to call the draw- class AdapterDemo, which extends the Applet class.
String() method inside paint method to display the Calling repaint() will call the paint()method
values of x-coordinate and y-coordinate. elaborated in L9 and L10.
L6 addKeyListener(new InnerClass());
L7 }
L8 class InnerClass extends KeyAdapter {
L9 public void keyPressed(KeyEvent ke){
L10 showStatus("key Pressed");
L11 }
L12 public void keyReleased(KeyEvent ke){
L13 showStatus("key Released");
L14 }
L15 }
L16 }
Explanation
L4 A class named as OuterClass, inherits the KeyListener interface is implemented (L9 and L12,
Applet class. respectively). Using adapter classes, KeyAdapter
L5–7 Applet’s init() method is implemented, eliminates the compulsion of implementing all
where the addKeyListener() method is used for the methods belonging to KeyListener interface.
registering the KeyListener to get the key events. The showStatus() is used at L10 and L13 in two
Object of the inner class InnerClass is passed as different methods; whatever has been passed as an
argument to the registration method (L6). argument to the showStatus() will be displayed
L8–15 Inner class with the name InnerClass is in the status window of the applet. Closing
defined to extend the adapter class KeyAdapter (L8). parenthesis at L15 signifies the end of the inner
Note that this inner class is part of the outer class class, ‘InnerClass’.
itself. Inside this inner class two of the three methods, L16 It signifies the end of the outer class,
keyPressed() and keyReleased() belonging to ‘OuterClass’.
Note What is magical here is that the compiler will just separate out these inner classes and create
separate class files for them. The names of these inner class files will be preceded with the
outer class name. You can check it simply by finding the following class file in the directory,
once you compile the above code.
OuterClass$1InnerClass.class
and on the release of that key, the status bar displays “Key Released”. Example 13.4 has been
rewritten to show how anonymous inner classes can be used.
Output
Fig. 13.3 Key Pressed Event Fig. 13.4 Key Released Event
Explanation
The most surprising code in the program is from L6 The anonymous class is defined as an
L6 to L13 argument to the addKeyListener method. This
addKeyListener(new KeyAdapter (){ anonymous class will inherit from KeyAdapter
public void keyPressed(KeyEvent ke){ class and will have two methods keyPressed and
showStatus("Key Pressed"); keyReleased defined inside the enclosing braces.
} keyPressed method is executed when any key is
public void keyReleased(KeyEvent me){
pressed as shown in Fig. 13.3 and keyReleased
showStatus("Key Released");
}
method is called as shown in Fig. 13.4.
});
416 Programming in Java
/* creates a Filled Polygon with 3 points where last (x,y) and the first
(x,y) coordinates are connected*/
L16 g.fillPolygon(x,y,n);
/* fills the eye ball with green color when clicked on nose else black
and mouth open else closed */
/* if user presses the mouse button while mouse pointer is on nose of
the cartoon*/
L19 if(mma.move)
{
L20 g.setColor(Color.green);
L21 g.fillOval(78,81,10,10); // green left pupil
L22 g.fillOval(131,81,10,10); // green right pupil
// open mouth with green color
L23 g.fillArc(70,125,80,40,180,180);
L24 mma.move=false;
}
L25 else
{
L26 g.fillOval(78,81,10,10); // black left pupil
L27 g.fillOval(131,81,10,10); // black right pupil
}
}
// Adapter class defined for handling Mouse Events
L34 class MyMouseAdapter extends MouseAdapter
{
/* Applets reference is created so that its paint method can be invoked from
this class based on mouse events*/
L35 Cartoon g;
L36 boolean move;
/* The current object passed in L9 is stored within the constructors argument
and assigned to the instance variable of type cartoon */
L37 MyMouseAdapter(Cartoon g)
{
L38 this.g = g;
L39 move = false;
Event Handling in Java 419
/* whenever mouse is pressed its coordinates are extracted and based on that
the flag is set and applet is painted again*/
// extract y coordinates
L42 int y = me.getY();
/* check for mouse click on nose*/
L43 if(x>85 && x<115 && y>100 && y<130)
{
L44 move = true; /* set the Boolean variable*/
L45 g.repaint(); /* call paint() of cartoon applet*/
}
L46 else /*if mouse clicked anywhere else*/
{
L47 move = false; /* reset the Boolean variable*/
L48 g.repaint(); /* call paint() of cartoon applet*/
}
}
}
Output
Fig. 13.7 (a) Cartoon displayed normally or when mouse is not pointed on nose and clicked.
(b) Cartoon is laughing with mouth wide open and green eyes when mouse is pointed on nose
and clicked.
420 Programming in Java
/* if you move the mouse pointer over nose of the cartoon, the color of its eyes
should change and it should laughs with mouth wide open. If you move your mouse out
of the nose the default cartoon with black eyes and smile should appear. */
L6 MyMouseMotionAdapter mma;
L7 public void init()
{
// Instantiates the MouseMotionAdapter
L8 mma = new MyMouseMotionAdapter(this);
/* fills the eye ball with green color when mouse is over its nose else black
and mouth open else eyes are black and mouth closed */
L18 if(mma.move)
{
L19 g.setColor(Color.green);
L20 g.fillOval(78,81,10,10); // green left pupil
L21 g.fillOval(131,81,10,10); // green right pupil
L22 g.fillArc(70,125,80,40,180,180); // mouth
}
L23 else
{
L24 g.fillOval(78,81,10,10); // black left pupil
L25 g.fillOval(131,81,10,10); // black right pupil
/* drawArc method is used; arc is drawn with black color but it is filled with
green color always once the mouse pointer is removed from nose. It is because
green color is there since last paint method call, as we have used update to
remove the flickering effect. It fills the background with the colors used and
then only paints the changes. The background is not cleared. If we want to
display the arc back once the mouse is moved out of the nose, we can invoke
the paintAll method within update method or call super.update(g) from update
method. But both methods would add flickering effect back to the cartoon, thus
defeating the purpose of adding update method */
/* to reduce the flickering effect when mouse is moved very quickly over the applet,
update method is overridden and paint is called from within it*/
422 Programming in Java
/* Using paintAll resolves the problem of green colored filled arc being displayed
when mouse is not over nose because it paints the entire applet but adds the flicker-
ing effect to the applet */
L34 //paintAll(g);
/* calling update of the super class solves the problem but adds flickering effect.
So how do we solve the problem? */
L35 // super.update(g);
}
}
L39 MyMouseMotionAdapter(CartoonVr2 g)
{
L40 this.g = g;
L41 move = false;
}
/* whenever mouse is moved its coordinates (x,y) are extracted and based on that the
flag is set and applet is painted again*/
}
Event Handling in Java 423
Output
/* if you move the mouse pointer over nose of the cartoon, the color of its eyes
should change and it should laugh with mouth wide open. If you move your mouse out
of the nose the default cartoon with black eyes and smile should appear. */
MyMouseMotionAdapter mma;
public void init()
{
mma = new MyMouseMotionAdapter(this);
addMouseMotionListener(mma);
}
if(mma.move)
{
/* wipes out the smile with white colored arc */
g.setColor(Color.white);
g.drawArc(70,125,80,40,180,180);
/* set the color as green and draws green pupil instead of black*/
g.setColor(Color.green);
g.fillOval(78,81,10,10); // green left pupil
g.fillOval(131,81,10,10); // green right pupil
else
{
g.fillOval(78,81,10,10); // black left pupil
g.fillOval(131,81,10,10); // black right pupil
/* To solve the problem we turn the color to white and then draw a filled arc with white
color. This white arc covers the green color and then we set the color as black and
draw the arc */
g.setColor(Color.white);
g.fillArc(70,125,80,40,180,180); // mouth
g.setColor(Color.black);
Event Handling in Java 425
g.drawArc(70,125,80,40,180,180); // mouth
MyMouseMotionAdapter(CartoonVr3 g)
{
this.g = g;
move = false;
}
int x = me.getX();
int y = me.getY();
if(x > 85 && x < 115 && y > 100 && y < 130)
{
move = true;
g.repaint();
}
else
{
move = false;
g.repaint();
}
}
}
426 Programming in Java
Output
SUMMARY
In this chapter, we have emphasized on the features this model. Actually applets are event-driven programs
that enhance the GUI capabilities of Java by using that use a GUI to interact with the users. The modern
event handling. But before moving to the AWT approach to event handling uses event delegation
components in Java, it was imperative to discuss model where a source generates events, which are
about the event handling model of Java, as the sent to one or more listeners. These listeners receive
knowledge about the use of applets and other GUI- the event notifications, which are handled as required
based programs is incomplete without the study of by the different methods of event classes.
EXERCISES
Objective Questions
1. Which of the following statements are true? (d) componentAdded(ContainerEvent e){}
(a) All events will be processed in the order, the 3. What will happen when you attempt to compile
listeners were added and run the following code?
(b) Using the adapter approach to event handling
means creating blank method bodies for all import java.awt.*;
event methods import java.awt.event.*;
(c) A component may have multiple listeners public class Demo extends Applet im-
plements MouseListener{
associated with it
public static void main(String argv[])
(d) Listeners may be removed once added
{
2. Which of the following are correct event handling Demo s = new Demo();
methods? }
(a) mousePressed(MouseEvent e){} Demo() {
(b) MousePressed(MouseClick e){} this.addMouseListener(this);
(c) functionKey(KeyPress k){} }
Event Handling in Java 427
4. How is the concept of inner classes used for 5. What is the advantage of having anonymous
event handling? classes while handling events in Java?
Programming Exercises
1. Create an applet which when gains focus shows interface and displays appropriate messages for
“Focus gained” in the status bar. each of the methods in the interface.
2. Create an applet to identify the key pressed in 4. Use the concept of adapter class in the previous
the window and display the character associated exercise.
with the key in the status window. 5. Create an anonymous inner class for handling
3. Create an applet that inherits MouseListener mouse entered event into an applet.
14.1 INTRODUCTION
The Abstract Window Toolkit (AWT) provides many classes—which can even be used inside
applets—for programmers to use. It is the connection between your application and the native
GUI. The AWT hides the complexities of the GUI your application will be running on.
The Java foundation classes (JFC) provide two frameworks for building GUI-based application
and interestingly both rely on the same event handling model:
AWT
Swing
AWT relies on the underlying operating system on a specific platform to represent its GUI
components (i.e., components in AWT are called heavyweight), while swing implements a new
set of lightweight GUI components that are written in Java and has a pluggable look and feel.
These lightweight components are not dependent on the underlying window system.
In this chapter, we will put emphasis on AWT, while swings will be covered in the next chapter.
AWT API can be used in any Java program by importing the java.awt.* package.
At the lowest level, the operating system transmits information from the input devices to the
program as input, and provides the output. The AWT was designed so that programmers need
not worry about tracking the mouse movements or reading the keyboard characters or writing
to the screen. The AWT is a well-designed object-oriented interface between the application and
the low-level resources.
The advantage of AWT is that it preserves the native look and feel of the platform on which the
AWT application is running because the components (user interfaces) in AWT are implemented
using the native GUI toolkit. On the other hand, the drawback is that the applications will have
different look and feel when executed on different platforms.
14.1.2 java.awt Package
The package java.awt contains all classes used for creating graphical user interfaces, paint-
ing graphics, images, colors, and fonts. A user interface element such as a button or a textbox
is called a component. The Component class is the superclass of all AWT components. These
components fire events when users interact with these components, e.g., when a user clicks on
a button. These events are handled by event handling classes, i.e., AWTEvent and its subclasses.
A container is one which contains components and other containers. A container has a layout
manager that determines the visual placement of components in the container. The java.awt
package contains several classes which are used for laying out components in a container.
The package java.awt contains many interfaces and classes. It is very difficult to elaborate
all these members of this package here. Some of the commonly used classes in the package are
given in Table 14.1.
Table 14.1 Classes in AWT Class
Classes Description
AWTEvent The root event class for all AWT events.
Lays out components in a container according to five regions: north, south, east, west,
BorderLayout
and center.
Button Creates a button.
Represents a blank rectangular area of the screen onto which drawing can be done or
Canvas
from which input events from the user can be trapped.
CardLayout Layout manager which can contain other layouts.
Checkbox A component that can be in one state: either “on” (true) or “off” (false) state.
CheckboxGroup Groups together a set of checkboxes so that they work as radio buttons.
CheckboxMenu Item This class is used for creating a checked menu item.
Choice Opens up a pop-up menu of choices.
Color Represents colors in the RGB or arbitrary color spaces as identified by a ColorSpace.
A component is an object having a graphical representation that can be displayed on the
Component
user screen and the users can interact with it.
Container Contains other AWT components.
(Contd)
Abstract Window Toolkit 431
Component Button
Canvas
TextComponent
Checkbox
TextArea
Container Choice
TextField
Label
Panel Window
List
The object of the Component, which is to be added, is passed as the argument to the above method.
This method returns the reference to the ComObj.If you wish to remove a Component from a
window, you can use remove() method for the same.
Abstract Window Toolkit 433
(Contd)
434 Programming in Java
14.3 BUTTON
Button() throws HeadlessException
Button(String str)throws HeadLessException;
The first constructor, when called, creates a Button with no label displayed on it. The second
constructor creates a Button, displaying the string ‘str’ on it.
Now, how is a Button actually created? See the syntax below,
Button buttonName = new Button(Str);
where buttonname is the name of the button object and str is the text which you want to set
as the caption of the button. Once the object for Button is created, it needs to be added to the
applet, frame or any other container. The syntax for it is as follows:
add(buttonname);
The methods like setLabel() and getLabel() are used for changing the button’s label and getting
the label’s text respectively. The signatures of these methods are
void setLabel(String str)
String getLabel()
Abstract Window Toolkit 435
Table 14.3 lists other methods that belong to the class Button.
Table 14.3 Methods of Button Class
Method Description
void addActionListener(ActionListener Adds the specified action listener to receive action events
al) from this button.
void addNotify() Creates the peer of the button.
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this button.
String getActionCommand() Returns the command name (caption of the button) of the
action event fired by this button.
ActionListener[] getActionListeners() Returns an array of all the action listeners registered on
this button.
String paramString() Returns a string representing the state of this button.
void processActionEvent (ActionEvent ae) Processes action events occurring on this button by dis-
patching them to any registered ActionListener objects.
void processEvent(AWTEvent awte) Processes events on this button.
void removeActionListener Removes the specified action listener so that it no longer
(ActionListener al) receives action events from this button.
void setActionCommand (String command) Sets the command name for the action event fired by this
button.
Example 14.1 shows an example that demonstrates how to create buttons and handle their events
using the listener approach of handling events.
L17 white.addActionListener(this);
L18 blue.addActionListener(this);
L19 }
L20 public void actionPerformed(ActionEvent ae){
L21 String str = ae.getActionCommand();
L22 if (str.equals("Red")) {
L23 setBackground(Color.red);
L24 }
L25 else if (str.equals("white")) {
L26 setBackground(Color.white);
L27 }
L28 else if (str.equals("blue")){
L29 setBackground(Color.blue);
L30 }
L31 repaint();
L32 }
L33 }
Output
Fig. 14.2(a) Applet with White Background When it is Displayed for the
First Time or When the White Button is Pressed
Fig. 14.2(b) Applet with Red Background When the Red Button is Pressed
Fig. 14.2(c) Applet with Blue Background When the Blue Button is Pressed
Abstract Window Toolkit 437
Explanation
L1–3 All the facilities of the applet and the AWT reference names red, white, and blue are registered
that Java has to offer are imported by using the * by the addActionListener() method (L16–18). Note
wildcard. that all components (buttons) are registered with the
L4 An applet with the name of ButtonClass , Listener interface because we want to capture events
extending the Applet class and implementing the from all buttons.
ActionListener interface, is defined. L20–31 When an action takes place, the default
L7–19 The init()method of the applet is defined handleEvent method calls the action method
and implemented, wherein three buttons having of our component. If it is not a button event, we
labels, red, white, and blue, respectively, are created simply return. Otherwise check the button’s label to
(see L8–10). Then the three buttons and a label determine which button was pressed. Then set the
(created in L11) are added to the current applet background to the appropriate color, and repaint and
window (see L12–15). These buttons with the update the screen.
14.4 LABEL
This component is the simplest one in Java’s AWT. Labels consist of a text string for display
only and they never call an action method. The constructors responsible for creating labels are
given in Table 14.4.
Table 14.4 Constructors of Label Class
Constructor Name Description
Label() Creates an empty label.
Label(String label) Creates a new label with the specified string of text, left justified.
Label(String label, Constructs a new label that presents the specified string of text with
int alignment) the specified alignment.
Example 14.2 uses the second type of constructor mentioned in Table 14.4.
Label labelname = new Label("This label is for demonstration.");
Here, a label’s object is created with the name ‘labelname’, with the string ‘This label is for
demonstration’ displayed on it. A label can be justified LEFT, RIGHT, or CENTERED. The
following line will create a label that is right justified:
Label labelname = new Label("This label is for demonstration.", Label.RIGHT);
Apart from setting the text on label, we can also get the label’s text using the method as shown
below,
String labelText = labelname.getText();
438 Programming in Java
We can change the alignment or get the alignment of a label with the methods shown as follows:
labelname.setAlignment(Label.CENTER);
or
int labelAlignment = labelname.getAlignment();
Output
Explanation
L1–2 We import all the facilities of the AWT and extending the Applet class.
applet that Java has to offer by using the * wildcard. L5–11 Three labels are created and added to the
L3 An applet with the name LabelClass is defined, applet window inside the init() method of applet.
14.5 CHECKBOX
Checkboxes are used as on-off or yes-no switches since every time you click on one, you toggle
to the opposite selection, i.e., if you click on an unchecked checkbox, it will get checked and if
Abstract Window Toolkit 439
you click on the checked box, it will get unchecked. You can check as many checkboxes as you
wish to, as there is no constraint on selecting the number of checkboxes. Your program can be
made to respond as per the state of each checkbox. An element-like button might be needed to
trigger an event to check the state of the checkboxes. The checkboxes are the objects of Checkbox
class, which support the following constructors:
Checkbox()
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, CheckBoxGroup cbg, boolean on)
The first form of constructor creates a checkbox whose label is blank initially and the state of
the checkbox is unchecked. In the other forms of constructors, string argument accounts for the
label of the checkbox, boolean argument (true/false) accounts for whether the checkbox will be
created checked or unchecked, i.e., if the argument passed is true, the created checkbox will be
initially checked, otherwise if the argument is false, the checkbox will be initially unchecked
and the CheckBoxGroup argument is accountable for specifying the checkbox group (the group
argument is used for radio buttons which are a special kind of checkboxes).
The following line will create a checkbox with Names as a label, null as a placeholder for a
group argument, and false to indicate that it is not selected:
Checkbox names = new Checkbox("Names", null, false);
Once you create the Checkbox, just add it to the applet (or other container) by entering the
following command:
add(names);
where names is the Checkbox name. A few of the methods belonging to the Checkbox class are
given in Table 14.5.
Table 14.5 Methods of Checkbox
Method Description
void addItemListener (ItemListener il) Adds the specified item listener to receive item events from
this Checkbox.
CheckboxGroup getCheckboxGroup() Returns the associated checkbox’s group.
ItemListener[] getItemListeners() Returns an array of all the item listeners registered with this
checkbox.
String getLabel() Returns string in the form of Checkbox text.
Object[] getSelectedObjects() Returns an array (length 1) containing the Checkbox label or
null if the Checkbox is not selected.
boolean getState() Returns boolean in the form of true or false, depending on
whether the Checkbox is selected or unselected.
String paramString() Returns a string representing the state of the Checkbox.
void processEvent(AWTEvent awte) Processes events on this Checkbox.
void processItemEvent(ItemEvent ie) Processes item events occurring on this checkbox by
dispatching them to any registered ItemListener objects.
(Contd)
440 Programming in Java
Method Description
void removeItemListener Removes the association between item listener and Checkbox.
(ItemListener l)
void setCheckboxGroup (CheckboxGroup Sets this checkbox’s group to the specified checkbox group.
ckbg)
void setLabel(String label) We can change the Checkbox label and set it to the argument,
‘label’.
void setState(boolean state) Changes the checkbox’s state to true (for selected) or false
(for unselected).
Example 14.3 illustrates how checkboxes can be created and used. The button ‘SUBMIT’
created in the program triggers an event in order to check which boxes are selected. A list of
selected names is then painted on the applet window.
L31 if (name2.getState())
L32 g.drawString("Ramesh",50,80);
L33 if (name3.getState())
L34 g.drawString("Naresh",50,100);
L35 }
L36 }
Output
Explanation
L4 An applet implementing ActionListener with L19 ActionListener is registered with the button.
the name of CheckboxClass is created. L21–24 actionPerformed() is overridden. If
L5–8 Reference variables for Button checkboxes submit button is pressed, repaint the applet.
and Font are created. L26–35 paint() is defined. The font defined in
L9 The init() method for applet has been defined. L13 is set using setFont(). setColor() is used to set
L10–14 Checkboxes and the button are instantiated. the color of the text to be written as blue. Depending
L13 instantiates the font name as Arial, specifies the
upon which checkbox is selected, its name is written
style to be italicized, and the size of the font as 14
on the applet. getState() returns true if the checkbox
point.
L15–18 Checkboxes and the button are added to is selected, else false.
the frame.
Once you create the checkbox group, add the individual checkboxes to that group. There are
three arguments to be specified in the constructor. The first argument is the radio button label,
the second argument is the group of which it is a part of, and the third is the state, true or false,
depending on whether the button is selected or not.
add(new Checkbox("mango", fruits, false));
add(new Checkbox("papaya", fruits, false));
add(new Checkbox("guava", fruits, false));
add(new Checkbox("apple", fruits, true));
The same checkbox methods that were mentioned in the previous section can be used with radio
buttons in the group. Some of these methods are
void setLabel(String str)
String getLabel()
boolean getState()
void setState(boolean b)
The methods getCheckboxGroup() and setCheckboxGroup() can be used to access and
change the group of a given checkbox group. To get the currently selected checkbox, you
can use the getSelectedCheckbox() method and in order to set a checkbox, you can use
setSelectedCheckbox(chkbox) method. The argument ‘chkbox’ is the checkbox that you want
to be selected.
The example below shows how radio buttons can be used to change the background color of
the applet window. Remember, only one radio button can be selected at a time.
L20 white.addItemListener(this);
L21 green.addItemListener(this);
L22 }
L23 public void itemStateChanged(ItemEvent ie){
L24 String str = (String) ie.getItem();
L25 if (str.equals("Red")){
L26 setBackground(Color.red);
L27 }
L28 else if (str.equals("White")) {
L29 setBackground(Color.white);
L30 }
L31 else if (str.equals("Green")){
L32 setBackground(Color.green);
L33 }
L34 repaint();
L35 }}
Output
Explanation
L1–3 Necessary packages are imported. as the third argument passed in the constructor of
L4 Applet class is defined and it inherits the checkbox is false.
ItemListener interface for handling the events L13–15 Labels are instantiated and added to the
related to the checkbox. applet.
L5 Three checkbox references are created. L16–21 All radio buttons are added to the applet
L6 CheckboxGroup reference is created. and they are registered with their associated listener
L7 The init() method is defined. for capturing events.
L8 A label is added to the applet. L23–34 ItemListener interface has one method,
L9–12 The CheckboxGroup instantiated along with i.e., itemStateChanged(ItemEvent e) which is
three checkboxes is. The checkboxes are made part overridden. This method checks which radio button
of a group (L10–12) so that they behave as a radio has been checked and then changes the color of
button and only one from the group can be selected at the background according to the name of the radio
a time. All radio buttons are not selected by default, button. The getItem() method of the ItemEvent
444 Programming in Java
class returns the caption of the checked radio button of the background using the setBackground(Color.
as an object of type Object class which is then cast XXX) method and then repaint the applet.
to String. Based on this String, we change the color
In the default constructor case, only one item can be selected at a time. In the second constructor,
you can specify the number of rows in the list that you want to be always visible. In the third
one, if the boolean value is set to true, it simply means that the user can select more than one
item at a time from the list. If it is set to false, then only one item of the list can be selected at a
time.
The simplest form of List that does not allow multiple selections can be created by the
following syntax:
List anyList = new List();
If you want to create a list that does allow multiple selections, use the following command line
which creates a list with 10 visible entries and multiple selections turned on.
List anyList = new List(10, true);
Once you have created the list, the add method enables you to add new entries. Table 14.6 shows
the methods of List class.
anyList.add("apple"); anyList.add("mango");
anyList.add("guava");
To add an item at a particular location in the list, e.g., the first position, use the following line
of syntax:
anylist.add("Coffee", 0);
Adding an item to (position–1) or at a higher position than the number on the list, adds it to
the end of the list.
Implementation of ActionListener interface is necessary for handling list events. A double
click on a particular list item generates an ActionEvent object. As used in the case of buttons,
getActionCommand() can be used to get the name of the double clicked item. If selection or de-
selection of an item takes place because of a single click, an ItemEvent is generated. Whether
this ItemEvent is generated because of selection or de-selection can be determined by the use
of getStateChange() method of ItemEvent class.
Abstract Window Toolkit 445
Let us take an example which creates two lists. One list is filled with items while the other
list is empty. As you select items from the first list and click on the button with the right arrows,
the selected item is deleted from the first list and added in the second list. The clear button will
clear the second list and reset the first list to its original values. The code for the applet is listed
in Table 14.6.
Table 14.6 Methods of List Class
Method Name Particulars
void add(String item) Adds the specified item to the end of scrolling list.
void add(String item, int index) Adds the specified item to the scrolling list at the position
indicated by the index.
void addActionListener (ActionListener l) Adds the specified action listener to receive action events
from this list.
void addItemListener(ItemListener il) Adds the specified item listener to receive item events
from this list.
void deselect(int index) De-selects the item at the specified index.
AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this list.
ActionListener[] getActionListeners() Returns an array of all the action listeners registered on
this list.
String getItem(int index) Gets the item associated with the specified index.
int getItemCount() Gets the number of items in the list.
ItemListener[] getItemListeners() Returns an array of all the item listeners registered on this
list.
String[] getItems() Gets the items in the list.
Dimension getMinimumSize() Determines the minimum size of this scrolling list.
Dimension getMinimumSize(int rows) Gets the minimum dimensions for a list with the specified
number of rows.
Dimension getPreferredSize() Gets the preferred size of the scrolling list.
Dimension getPreferredSize(int rows) Gets the preferred dimensions for a list with the specified
number of rows.
int getRows() Gets the number of visible lines in this list.
int getSelectedIndex() Gets the index of the selected item on the list.
int[] getSelectedIndexes() Gets the selected indexes on the list.
String getSelectedItem() Gets the selected item on this scrolling list.
String[] getSelectedItems() Gets the selected items on this scrolling list.
Object[] getSelectedObjects() Gets the selected items on this scrolling list in an array of
objects.
int getVisibleIndex() Gets the index of the item that was last made visible by
the method makeVisible.
(Contd)
446 Programming in Java
L1 8 b2.addActionListener(this);
L1 9 }
L20 public void populateList(){
L21 original.add("Grocery");
L22 original.add("Fruits");
L23 original.add ("Ice-cream");
L24 original.add("Shop");
L25 original.add("Vegetables");
L26 original.add("Books");
L27 original.add("AC");
L28 original.add("Garments");
L29 original.add("Baby Food");
L30 }
Output
Explanation
L1–3 Packages are imported. handling events of the button. Apart from this, a
L4 Class declaration. label is also added.
L5 Two list references have been created which L31–43 The actionPerformed() method has been
are instantiated in L7 and L8. The first argument in overridden to handle the button event. If the user
the constructor specifies the number of items in the has selected an item in the original list (original.
getSelectedIndex()) and pressed the button >>>>,
list to be shown and the second argument specifies then the selected item is copied to list copy using
whether multiple selections are allowed or not. copy.add(original.getSelectedItem() ) and
L9 The method populateList() is defined in removed from the list original using the original.
L20–L30 for adding items into the list: original. remove(original.getSelectedIndex()). If the clear
L10 The list original is added to the applet. button is pressed, then all items in the list copy and
L11–18 Two buttons are created, added to the original are removed using the removeAll() and the
applet and registered with ActionListener for original list is populated again using populateList()
method.
Once you have created the choice, the add method enables you to add new entries.
c.add("Red");
c.add("Green");
The currently selected item can be changed by using select() method. The selection can be
made based on name or index. For example,
c.select("Red");
or
c.select(0);
The getSelectedIndex() method would return the position of the selected item and the
getSelectedItem() returns the name of the selected item, respectively.
The listener for handling Choice change events is ItemListener. The following example shows
how a choice can be used to change the background color of an applet.
L6 Choice theOptions;
L7 Label l;
L8 public void init(){
L9 add(l = new Label("Make a choice from the choice box"));
L10 theOptions = new Choice();
L11 theOptions.add(" ");
L12 theOptions.add("Red");
L13 theOptions.add("Green");
L14 theOptions.add("Blue");
L15 theOptions.add("White");
L16 theOptions.add("Cyan");
L17 theOptions.add("Yellow");
L18 theOptions.addItemListener(this);
L19 add(theOptions);
L20 }
L21 public void itemStateChanged(ItemEvent evt){
L22 currentColor = theOptions.getSelectedItem();
L23 repaint();
L24 }
L25 public void paint(Graphics g){
L26 if (currentColor.equals("Red")) {
L27 setBackground(Color.red);
L28 l.setBackground(Color.red);
L29 }
L30 else if (currentColor.equals("Blue")){
L31 setBackground(Color.blue);
L32 l.setBackground(Color.blue);
L33 }
L34 else if (currentColor.equals("Green")){
L35 setBackground(Color.green);
L36 l.setBackground(Color.green);
L37 }
L38 else if (currentColor.equals("Cyan")){
L39 setBackground(Color.cyan);
L40 l.setBackground(Color.cyan);
L41 }
L42 else if (currentColor.equals("Yellow")){
L43 setBackground(Color.yellow);
L44 l.setBackground(Color.yellow);
L45 }
L46 else {
L47 setBackground(Color.white);
L48 l.setBackground(Color.white);}}}
450 Programming in Java
Output
Fig. 14.7(b) Color of the Frame Changes Based on the Selection in the Choice
Explanation
L1–3 Packages are imported. to the applet. The Choice object is registered with
L4 Applet class defined to implement ItemListener the ItemListener to receive change events when an
interface for handling events of the component item in the Choice object is selected.
Choice. L21–23 itemStateChanged(ItemEvent e) method
L5–7 Label and choice reference variables are of the ItemListener is overridden. When an item is
created. A string is also defined that represents the selected by the user, the current color is set based on
current color of the background. the selection of the items in the choice and then it is
L8 The init() method for the applet is defined. repainted using the repaint() method.
L9 The label is instantiated and added to the applet. L24–48 Within the paint method, the value of
L10–19 The C h o i c e object is instantiated. currentColor is matched with various colors and if
Individual items are added to the Choice object using true, the background of the applet is set according to
the add() method and later the choice object is added the color mentioned in the currentColor along with
the background of the label.
Abstract Window Toolkit 451
The Textfield can also be initialized with some text when it is created.
TextField plaintext = new TextField("First Name Last Name");
Tables 14.7 and 14.8 list the constructors and methods of TextField and TextArea, respectively.
Table 14.7 TextField Class
Constructors of TextField
Constructor Description
TextField() Constructs a new textfield.
TextField(int columns) Constructs a empty textbox with the number of columns specified as
argument.
TextField(String text) Constructs a new textbox initialized with the specified string.
TextField(String text, Constructs a new textbox initialized with the specified string, and specified
int columns) number of columns.
Methods of TextField
Method Description
void addActionListener Adds the specified action listener to receive action events from this
(ActionListener l) textfield.
boolean echoCharIsSet() Indicates whether or not this textfield has set a character for echoing.
AccessibleContext
Returns the AccessibleContext associated with this textField.
getAccessibleContext()
ActionListener[]
Returns an array of all the action listeners associated with the textfield.
getActionListeners()
int getColumns() Returns the number of columns in this textfield.
char getEchoChar() Returns the character that is to be used for echoing.
Dimension getMinimumSize() Returns the minumum dimensions for this textfield.
Dimension getMinimumSize Returns the minumum dimensions for a textfield with the specified number
(int columns) of columns.
Dimension getPreferredSize() Returns the preferred size of this textfield.
Dimension getPreferredSize Returns the preferred size of this textfield with the specified number of
(int columns) columns.
String paramString() Gets a string representing the state of this textField.
void process Processes action events of the textfield by dispatching them to any
ActionEvent(ActionEvent e) registered ActionListener objects.
(Contd)
452 Programming in Java
Output
Fig. 14.8(c) Focus Gained by Button Fig. 14.8(d) Enter Pressed While Focus on
TextField Generates an ActionEvent
Explanation
L1 An Applet is created which inherits three TextField. The methods of the interfaces have been
interfaces: TextListener for tracking changes in implemented later in the program.
TextField, FocusListener for determining which L2–4 Label, TextField, and Button reference
component has focus, and ActionListener for per- variables are created.
forming an action when the user presses enter in a L5 init() methods defined for the applet.
Abstract Window Toolkit 455
L6–8 tf, l and b are instantiated. The text passed are overridden, i.e., focusGained(FocusEvent e)
as an argument to the TextField constructor will and focusLost(FocusEvent e). L19 checks the
be displayed in the TextField. The button when source of the event, i.e., which component has
displayed will have the caption ‘Submit’ which is focus. If it is TextField, the label is set with the
passed in the constructor of the Button object. The text FocusGainedbyTextbox, else if the focus is on
label is assigned an orientation, i.e., Label.CENTER Button, the label is set with the text ‘Focus Gained
which displays the caption of the label in the middle. by Button. Focus lost by the TextField is actually
L9 FocusListener is registered on button to focus gained by the Button and when the focus is lost
capture focus lost and gained status. by the Button, it is gained back by the TextField.
L10–12 TextListener , FocusListener , and If the ALT+TAB key combination is pressed, the
ActionListener are registered on TextField to window loses focus and the other window gains
capture various events. focus. The focusLost method is called in that case
L13 The Text in the TextField is already selected (see Fig. 14.8(e)).
when it is displayed to the user. selectAll() is used L25–26 If ENTER is pressed in the TextField,
for this purpose (see Fig. 14.8(d)). an ActionEvent is generated and passed to the
L14 The layout of the applet is changed to actionPerformed method which sets the text of the
BorderLayout. label to the ActionEvent.
L15–17 The label is added to NORTH, TextField L27–28 If the value in the TextField changes,
in CENTER, and button in SOUTH. the T e x t E v e n t is generated and passed to
L18–24 The methods of FocusListener interface textValueChanged method which sets the text of the
label to Trying to change Text (see Fig. 14.8(b)).
The Panel class is a direct subclass of the Container class. We have made so many applets by now.
The Panel class is a superclass of the applet that makes all the applets be drawn on the surface of
the panel. Panel is a window that does not contain a title bar or a menu bar. Components (such
as label and button) can be added to the panel object by using the add() method. This add()
method actually belongs to the Container class, the superclass of the panel class. The constructors
responsible for constructing panels are listed in Table 14.9.
Table 14.9 Constructors of Panel Class
Constructor Description
Panel() Creates a new panel using the default layout manager.
Panel(LayoutManager layout) Creates a new panel with the specified layout.
panel.add(someOtherComponent);
If you want to add to an external container, then you have to call the add() method in the
following ways:
container.add(panel);
or if you want to add from within a container, then call the add() method directly,
add(panel);
14.10.2 Window
This class creates a top-level window. Top-level window means that it is not contained within
any other object. It has the following signature:
public class Window extends Container implements Accessible
A Window object is a window with no borders and no menubar. The default layout for a window
is BorderLayout, which we have covered later in the chapter. A window must have a frame,
dialog, or another window defined as its owner when it is constructed, out of which only Frame
is most often used.
14.10.3 Frame
If you are not creating an applet, then you will be most likely creating a Frame window. The
constructors responsible for creating a Frame are
Frame()
Frame(String title)
Abstract Window Toolkit 457
The first constructor simply creates a Frame window without any title, while the second one
creates a Frame with the title specified as string in the argument. Some of the methods that can
be used while working with the Frame object are given in Table 14.10.
Table 14.10 Methods of Frame Object
Method Description
void setSize(int width, int height) It is used to set the dimensions of the window. The new
dimension in the form of width and height is passed as argument.
void setSize(Dimension size) Sets the size of the frame with dimension specified.
Dimension getSize() It is used to return the current size of the window, contained
within the width and height fields of Dimension object.
void setVisible(boolean flag) It is used to make the window visible after its creation. The
component is visible only if the argument passed is true.
void setTitle(String title) The title in the frame window can be used to set to a new title,
passed as argument.
Example 14.8 demonstrates how frames are created and used.
Output
Creating a framed application is easy. The typical procedure for frame development is as follows:
1. Create an instance of the main frame.
2. Set the frame width and height.
3. Display the frame.
Explanation
L2 FrameDemo class extends the java.awt.Frame calling the constructor of the superclass. L5 signifies
class. the end of the constructor method.
L3–5 The constructor belonging to the Frame class L6–10 In these lines, main()method is elaborated.
sets the frame instance title. So, the FrameDemo class In L8, the setSize()method is used to set the width
accepts a string as parameter for title of the frame. and height of the frame to 200 and 300 pixels,
In L4, the super keyword is used to set the title by respectively.
14.11 LAYOUTS
Java has the mechanism to specify the type of layout schemes, where components can be added
to a Frame instance. This mechanism is specified by LayoutManager, which is used to specify how
the components can be arranged inside a container, say a Frame. The various LayoutManagers
available in AWT are children of this interface and explained in the sections to follows:
This LayoutManager is actually an interface in java.awt, defined as
public interface LayoutManager
The above interface is defined for classes that know how to layout Containers. The various
methods defined in the interface are
void addLayoutComponent(String name, Component comp)
If the layout manager uses a string per component, the above method adds the component, ‘comp’
to the layout, associating it with the string specified by ‘name’.
void removeLayoutComponent(Component comp)
The method removes the specified component, ‘comp’ from the layout.
Dimension preferredLayoutSize(Container parent)
The method returns the preferred size dimensions for the specified container, ‘parent’, given
the components it contains.
Dimension minimumLayoutSize(Container parent)
Returns the minimum size dimensions for the specified container, ‘parent’, given the components
it contains.
void layoutContainer(Container parent)
The method is responsible for laying out the specified container, ‘parent’. Some of the famous
layouts in Java are discussed below.
Abstract Window Toolkit 459
14.11.1 FlowLayout
There is class belonging to the package java.awt, named as FlowLayout, having the following
signature:
public class FlowLayout extends Object implements LayoutManager, Serializable
Constructors of FlowLayout
Constructor Name Particulars
FlowLayout() Constructs a new FlowLayout with a centered alignment and a default 5-unit
horizontal and vertical gap.
FlowLayout(int align) Constructs a new FlowLayout with the alignment specified as argument and
a default 5-unit horizontal and vertical gap.
FlowLayout Constructs a new FlowLayout with the indicated alignment and the indicated
(int align,int hzgap, int horizontal and vertical gaps.
vrgap)
Methods of FlowLayout
Method Name Particulars
void addLayoutComponent Adds the component specified as the argument to the layout.
(String name, Component
comp)
int getAlignment() Returns the alignment for the layout.
boolean Returns true in case of vertical alignment of components along their baseline.
getAlignOnBaseline()
int getHgap() Returns the horizontal gap between components and between the components
and the borders of the container.
int getVgap() Returns the vertical gap between components and between the components
and the borders of the container.
void layoutContainer
Lays out the container.
(Container target)
Dimension
Returns the minimum dimensions needed to layout the visible components in
minimumLayoutSize
the target container.
(Container target)
Dimension preferredLayout Returns the preferred dimensions for this layout, given the visible components
Size(Container target) in the target container.
void
removeLayoutComponent Removes the component, specified as, ‘comp’ from the layout.
(Component comp)
void setAlignment(int
Sets the alignment for this layout, as per the argument.
align)
void setAlignOnBaseline Sets whether or not components should be vertically aligned along their
(boolean alignOnBaseline) baseline.
void setHgap(int hgap) Sets the horizontal gap between components and also between the
components and the borders of the container.
void setVgap(int vgap) Sets the vertical gap between components and also between the components
and the borders of the container.
String toString() Returns a string representation of the FlowLayout object and its values.
Abstract Window Toolkit 461
Output
The output of the program shows the six buttons arranged or added to the applet window in the
FlowLayout fashion.
Explanation
L1–2 All the necessary classes belonging to the L4 A reference to the LayoutManager class is
packages like java.applet and java.awt are declared as ‘flowLayout’.
imported. L5 An array of buttons of button type with the name
L3 An applet with the name FlowLayoutDemo is ‘Buttons’ is declared.
declared. L6–16 A constructor, FlowLayoutDemo() , is
declared at L6. In L8, the reference declared at L4,
462 Programming in Java
as flowLayout, is created. In L9, the setLayout() the setLabel() method of the Button class. After the
method is used to set the layout of the window by labels are set for each button, the buttons are added to
passing the object of the FlowLayout class as its the applet window. In order to avoid setting the label
argument. In L10, an array of six buttons is created. for each button and then adding it to the container, a
In L11–15, the labels of the six buttons are set using for loop is used for simplifying the purpose.
14.11.2 BorderLayout
It is the default layout of the frame. The class belonging to java.awt, named as BorderLayout,
has the following signature:
public class BorderLayout extends Object implements LayoutManager2, Serializable
The BorderLayout is a layout where the components can be arranged and resized to fit in five
different regions: north, south, east, west, and center. There can be only one component in each
region and the regions are identified as constants: NORTH, SOUTH, EAST, WEST, and CENTER. Any
of these five constant names can be used while adding a component to a container. For example:
Panel pnl = new Panel();
pnl.setLayout(new BorderLayout());
pnl.add(new Button("submit"), BorderLayout.NORTH);
By default, if you do not mention the string specification, BorderLayout interprets the absence
of a string specification the same as the constant CENTER:
Panel p2 = new Panel();
p2.setLayout(new BorderLayout());
p2.add(new TextArea()); // Same as p.add(new TextArea(),
// BorderLayout.CENTER);
The various fields, constructors, and methods belonging to the BorderLayout class are mentioned
in Table 14.12.
Table 14.12 BorderLayout Class
Fields of BorderLayout
Field Name Particulars
String AFTER_LAST_LINE Same as PAGE_END, given below.
String AFTER_LINE_ENDS Same as LINE_END, given below.
String BEFORE_FIRST_LINE Same as PAGE_START, given below.
String BEFORE_LINE_BEGINS Same as LINE_START, given below.
String CENTER Middle of container.
String EAST The east layout constraint (right side of container).
String LINE_END The component goes at the end of the line direction for
the layout.
String LINE_START The component goes at the beginning of the line
direction for the layout.
(Contd)
Abstract Window Toolkit 463
Fields of BorderLayout
Field Name Particulars
String NORTH The north layout constraint (top of container).
String PAGE_END The component comes after the last line of the layout’s
content.
String PAGE_START The component comes before the first line of the
layout’s content.
String SOUTH Bottom of container.
String WEST The west layout constraint (left side of container).
Constructors of BorderLayout
Constructor Name Particulars
Constructs a new border layout with no gaps between
BorderLayout()
components.
BorderLayout(int hgap, Constructs a border layout with the specified horizontal
int vgap) and vertical gap between components.
Methods of BorderLayout
Method Name Particulars
void addLayoutComponent (Component comp, Adds the specified component to the layout, using the
Object constraints) specified constraint object.
Object getConstraints (Component comp) Gets the constraints for the specified component.
int getHgap() Returns the horizontal gap between components.
float getLayoutAlignmentX (Container parent) Returns the alignment along the x-axis.
float getLayoutAlignmentY (Container parent) Returns the alignment along the y-axis.
Component getLayoutComponent(Container Returns the component that corresponds to the given
target, Object constraints) constraint location based on the target container’s
component orientation.
Component getLayoutComponent (Object Gets the component that was added using the given
constraints) constraint.
int getVgap() Returns the vertical gap between components.
void invalidateLayout (Container target) Invalidates the layout, indicating that if the layout
manager has cached information it should be discarded.
void layoutContainer(Container target) Lays out the container argument using this border
layout.
Dimension maximumLayoutSize (Container Returns the maximum size as dimension object for this
target) layout given the components in the specified target
container.
Dimension minimumLayoutSize (Container Determines the minimum size of the target container
target) using this layout manager.
Dimension preferredLayout Size(Container Determines the preferred size of the target container
target) using this layout manager, based on the components in
the container.
(Contd)
464 Programming in Java
Methods of BorderLayout
Method Particulars
void removeLayoutComponent (Component comp) Removes the specified component from this border
layout.
void setHgap(int hgap) Sets the horizontal gap between components.
void setVgap(int vgap) Sets the vertical gap between components.
String toString() Returns a string representation of the state of this
border layout.
Let us take an example for BorderLayout. Since the default layout manager for frames is
BorderLayout, we do not explicitly set the layout manager.
Output
In the above frame, components placed within a region extend to fit it. For example, components
in NORTH and SOUTH have stretched themselves horizontally to fit in that entire region and similarly,
components in the EAST and WEST have stretched themselves vertically. The component in the
CENTER stretches both horizontally and vertically to fill any leftover space.
Explanation
L2 Class BLayoutDemo declared to extend the used to set the title by calling the constructor of the
frame. superclass. In L5–9, button objects are created and
L3–11 The constructor belonging to the Frame added to the frame using the add() method. The
class sets the Frame instance title. Likewise, the constraints for the button are specified as the second
BlayoutDemo class accepts a string as parameter argument, i.e., BorderLayout.NORTH and so on. L9
for the title of the frame. In L4, super keyword is signifies the end of the constructor method.
If no constraint is specified and add(Component c) is used for adding buttons, then by default, all
buttons would be placed in center and they will occupy the entire frame. The button added in the
end would be displayed on top of the frame. The remaining buttons will be beneath the top button
displayed to the user. Figure 14.11(b) shows when buttons are added using add(Component c).
The code that produces the above output is shown below:
add(new Button("North"));
add(new Button("South"));
add(new Button("East"));
add(new Button("West"));
add(new Button("Center"));
14.11.3 CardLayout
CardLayout class inherits Object class and implements LayoutManager2, serializable interfaces.
Object of cardLayout acts as layout manager for a container. In a container each component is
466 Programming in Java
treated as a card by cardLayout object. Each card is kept on another like a stack and only one
card can be visible at a time. When the container is displayed after adding the first component,
then the first component is visible.
The ordering of cards is determined by the container’s own internal ordering of its component
objects. CardLayout defines a set of methods that allow an application to flip through these cards
sequentially, or to show a specified card. The various constructors and methods belonging to the
cardLayout class are mentioned in Table 14.13.
Output
Explanation
This example shows the CardLayout manager. (p1, p2, p3) will constitute different cards. A panel
Pressing any one of the three buttons available will button is created.
show a different “card”. L9 Method declaration.
L4–8 In these lines, we have created reference L10 A cardPanel that will contain cards created
variables for panels, buttons, and card layout. The in this program.
cardPanel will hold various cards. Three panels L11 We have created a CardLayout object named
as cLayout.
Abstract Window Toolkit 469
L12 Sets the layout of the cardPanel as CardLayout. cardPanel. These will be flipped based on the user
L13–18 In these lines, three dummy panels are interaction with these three buttons.
created to show the cards, and their backgrounds are L32 Sets the layout of the frame as BorderLayout.
set with three different colors: red, green, and yellow. L33–34 Both panels, button panel (buttonP) and
L19–24 We have created three buttons and added card panel (cardPannel), are added to the frame.
the ActionListener to it. L38 Closes the window when cross is clicked on
L25–28 A panel (buttonP) is created and buttons the frame.
are added to this panel. L40–45 If red button is clicked, the panel with
L29–31 Three panels (p1, p2, p3) are added to red background is shown. Panels in card layout are
switched using show() method.
14.11.4 GridLayout
The class belonging to java.awt, named as GridLayout, has the following signature:
public class GridLayout extends Object implements LayoutManager, Serializable
The GridLayout class is a layout manager that lays out a container’s components in a rectangular
grid. This is a layout manager which can be used to arrange controls in a container. GridLayout
has a specified number of rows and columns, where the container is divided into equal-sized
rectangles, and one component is placed in each rectangle.
The GridLayout arranges the components in rows and columns order. Each component fills
up its respective grid cell. Table 14.14 describes the constructors and methods of GridLayout.
Table 14.14 GridLayout Class
Constructors of GridLayout
Constructor Name Particulars
GridLayout() Creates a grid layout with a default of one column per component, in
a single row.
GridLayout(int row, int cols) Creates a grid layout with the specified number of rows and columns.
GridLayout(int row, int cols, Creates a grid layout with the specified number of rows and columns
int hzgap, int vrgap) with horizontal and vertical gap.
Methods of GridLayout
Method Name Particulars
void addLayoutComponent (String Adds the specified component with the specified name to the layout.
name, Component comp)
int getColumns() Gets the number of columns in this layout.
int getHgap() Returns the horizontal gap between components.
int getRows() Gets the number of rows in this layout.
int getVgap() Returns the vertical gap between components.
void layoutContainer(Container Lays out the specified container using this layout.
parent)
(Contd)
470 Programming in Java
Methods of GridLayout
Method Name Particulars
Dimension minimumLayoutSize Determines the minimum size of the container argument using this
(Container parent) grid layout.
Dimension preferredLayout Determines the preferred size of the container argument using this
Size(Container parent) grid layout.
void removeLayoutComponent Removes the specified component.
(Component comp)
void setColumns(int cols) Sets the number of columns in this layout to the specified value.
void setHgap(int hgap) Sets the horizontal gap between components to the specified value.
void setRows(int rows) Sets the number of rows in this layout to the specified value.
void setVgap(int vgap) Sets the vertical gap between components to the specified value.
String toString() Returns a string representation of the grid layout’s object.
Output
Explanation
L1–2 java.awt and its sub-package awt.event is specified as 20, and vertical gap between the rows
are imported. is specified as 50.
L3 A frame is created. L7–17 Components are added to the panel. Labels
L4 Constructor for the class is defined. and TextFields are added to the panel object along
L5 The constructor of Frame is called using the with two other buttons. The panel object is added to
super keyword. The string passed to it is used as
frame using add(Component c)method.
the title of the frame.
L18–19 The size of the frame is set and the
L6 A Panel object is created to hold the component.
visibility of the frame is set to true.
The layout for Panel object is specified as an
argument in the constructor. The layout specified is L20–25 WindowListener is registered with frame
GridLayout with number of rows as 5, number of so that when the cross on the frame title bar is pressed,
columns as 2, horizontal gap between the columns the application frame is closed.
14.11.5 GridBagLayout
GridBagLayout class extends Object and implements interfaces LayoutManager2 and Serializable.
Using GridBagLayout class, we can arrange components in a more controlled way in horizontal
as well in vertical direction. In GridBagLayout, the components need not be of same size in a
row. We can arrange different sizes of components by specifying their position within the cell
of a grid in the same row. One more advantage is that each row can contain dissimilar number
of columns. In GridBagLayout, the size and position of components are dependent on set of
constraints linked to it.
472 Programming in Java
An object called GridBagConstraint contains the constraint which includes the height, width
of a cell, placement, and alignment of components. Each GridBagLayout object maintains a
rectangular grid of cell. A component can occupy one or more cells and it is called its display
area. ComponentOrientation class controls the orientation of the grid.
We need to customize GridBagConstraints objects to use GridBagLayout effectively associated
with its components. Customization of a GridBagConstraints object can be done by setting one
or more of its instance variables. These instance variables are discussed below.
gridx and gridy
The initial address of cell of a grid is gridx = 0 and gridy = 0. GridBagConstraints.RELATIVE
(the default value) is used to specify that the component be aligned immediately following the
component that was added to the container just before addition of this component.
gridwidth and gridheight
gridwidth constraint specifies the number of cells in a row and gridheight specifies number of
columns in display area of the components. The default value is 1.
fill
When the requested size of components is smaller than the size of display area, then we use this.
We can also use it to resize the component. It is used to determine whether (and how) to resize
the component. Values for this field are as follows:
GridBagConstraints.NONE (default value–does not grow when the window is resized)
GridBagConstraints.HORIZONTAL (this value fills all the horizontal display area of a
component, but it does not change height).
GridBagConstraints.VERTICAL (it changes the height of a component, but does not
change its width)
GridBagConstraints.BOTH (makes the component fill its display area horizontally and
vertically, both).
ipadx and ipady
The ipadx and ipady fields are used for internal padding of components in given layout. If
ipadx is specified, the width of the component will be the minimum width plus ipadx pixels.
Similarly, ipady plus minimum height is the height of the component.
insets
The insets field is used for external padding of components. It is used for spacing between the
component and the edges of its display area. For example,
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(int top, int left, int bottom, int right)
anchor
The anchor field specifies the position of a component in its display area. There are three types
of possible values: absolute, orientation-relative, and baseline-relative.
Abstract Window Toolkit 473
Absolute Values are used to place components at specific locations. These absolute values can
be any of the following:
GridBagConstraints.NORTH
GridBagConstraints.SOUTH
GridBagConstraints.WEST
GridBagConstraints.EAST
GridBagConstraints.NORTHWEST
GridBagConstraints.NORTHEAST
GridBagConstraints.SOUTHWEST
GridBagConstraints.SOUTHEAST
GridBagConstraints.CENTER (The default)
Orientation-relative Values are relative to the orientation of container. These can be any of
the following:
GridBagConstraints.PAGE_START
GridBagConstraints.PAGE_END
GridBagConstraints.LINE_START
GridBagConstraints.LINE_END
GridBagConstraints.FIRST_LINE_START
GridBagConstraints.FIRST_LINE_END
GridBagConstraints.LAST_LINE_START
GridBagConstraints.LAST_LINE_END
Baseline-relative Values were added by JDK 6. With the help of these values, you can place a
component vertically relative to the baseline of row. Possible values are as follows:
GridBagConstraints.BASELINE
GridBagConstraints.BASELINE_LEADING
GridBagConstraints.BASELINE_TRAILING
GridBagConstraints.ABOVE_BASELINE
GridBagConstraints.ABOVE_BASE LINE_LEADING
GridBagConstraints.ABOVE_BASELINE_TRAILING
GridBagConstraints.BELOW_BASELINE
GridBagConstraints.BELOW_BASELINE_LEADING
GridBagConstraints.BELOW_BASELINE_TRAILING
Output
Explanation
L1 Imports the java.awt package. of the frame.
L2 Class definition begins. L6–13 Label, TextField, and two Buttons are
L3 Constructors defined. created and added to the frame. All the components
L4 The layout is set to GridBagLayout() using are displayed by default in a single row and center
setLayout method. aligned.
L5 setTitle method is used for setting the title L14–15 Sets the size and visibility of the frame.
Example 14.13 does not place any constraint on the alignment of the components. In the next
example, we would place constraint like fill, gridx, and gridy on the components. The fill
attribute specifies whether components should occupy the entire available space horizontally,
vertically, in both directions or not. The gridx and gridy attributes specify the row and column
combination to display the components.
Output
Fig. 14.15(a) GridBagLayout with Fig. 14.15(b) Output is Displayed when the
fill, gridx, and gridy Constraints Fill Attribute is None (L7 is commented)
Specified
Explanation
L6 GridBagConstraints object is created. values 0 and 1, respectively. The gridx constraint
L7 The fill attribute is set as HORIZONTAL. is assigned 0 to indicate first column and gridy is
The fill attribute makes the component fill the assigned 1 to indicate second row.
space horizontally in its display area and aligns L14–15 A button is added with all the constraint
all the components (see Fig. 14.15(a)). If this line mentioned above, i.e., the button will be added in
is commented, the output displayed is shown in second row, first column (see Fig.14.15(a)).
Fig.14.15(b). Note the size of the TextField. L16–17 Specifies gridx and gridy constraints with
L8–9 Label is instantiated and added to the frame values 1 and 1, respectively. The gridx constraint is
along with the constraints specified as second assigned 1 to indicate second column and gridy is
argument in the add method. assigned 1 to indicate second row.
L10–11 TextField is instantiated and added to the L18–19 Another button is added with a new
frame along with the constraints specified as second constraint mentioned above, i.e., the button will be
argument in the add method. displayed in second row, second column (see Fig.
L12–13 Specifies gridx and gridy constraints with 14.15(a)).
In Example 14.14, we had used only gridx, gridy, and fill constraints. But still the components
are displayed only in the center of the frame. To distribute the extra horizontal and vertical space
in the rows and columns, the weightx and weighty attributes are used.
L3 public GBLayoutDemo3() {
L4 setLayout(new GridBagLayout());
L5 setTitle("GridBagLayout with weightx, weighty and ipady Constraints");
L6 GridBagConstraints c = new GridBagConstraints();
L7 c.weighty = 1;
L8 c.weightx = 1;
L9 c.fill = GridBagConstraints.BOTH;
L10 Label l = new Label("Name");
L11 add(l,c);
L12 TextField t = new TextField();
L13 add(t,c);
L14 c.gridx = 0;
L15 c.gridy = 1;
L16 Button b = new Button("Submit");
L17 add(b,c);
L18 c.fill = GridBagConstraints.NONE;
L19 c.gridx = 1;
L20 c.gridy = 2;
L21 c.ipady = 30;
L22 Button b1 = new Button("Reset");
L23 add(b1,c);
L24 setSize(200,200);
L25 setVisible(true); }
L26 public static void main(String args[])
{
L27 GBLayoutDemo3 d = new GBLayoutDemo3();
}
}
Output
Explanation
L7–8 weightx and weighty are specified as only weighty is specified, then components occupy
1 and the fill attribute is specified as BOTH, the area vertically (see Fig. 14.16(c)) because extra
so the components fill up the area horizontally vertical space is distributed among rows.
and vertically (see Fig. 14.16(a)). If only weightx L18 The fill attribute is specified as none for
is specified, then components occupy the area the reset button.
horizontally (see Fig. 14.16(b)) because the extra L21 The ipady attribute is used to specify the
vertical pad for the reset button. Take a note of the
horizontal space is distributed among columns. If
size of the reset button in Fig. 14.16(a).
14.12 MENU
Menu is a class which inherits MenuItem class and two interfaces: MenuContainer and Accessible.
Menubar deploys a menu object which is a dropdown menu component. It shows a list of menu
choices. To implement this concept, we use three classes: MenuBar, Menu, and MenuItem. The
various fields, constructors, and methods belonging to the Menu class are mentioned in Table 14.15.
A menubar may contain more than one menu objects and each menu object contains a number
of MenuItem objects. CheckboxMenuItem can also be used as a menu option. MenuComponent is an
abstract class which inherits the Object class and implements the Serializable interface. All
these menu classes are basically the subclasses of MenuComponent, not Component. So they are
placed on the container in a way different from other components (e.g., buttons, labels, etc.).
The method setMenuBar() of the Frame class is used to set the menubar on the frame. Menubar
cannot be placed on the applet because they are not subclasses of Frame and these do not inherit
the setMenuBar() method, so there is no way of placing a menubar on the applet. A menubar
contains some shortcut keys for menu items. A menu item can have an instance of MenuShortcut.
Menu subclass overrides the method and does not send any event to the frame until one of its
subitems is selected. The setMenuBar() method is used to associate a menu bar with frame. The
constructors and methods belonging to the MenuBar class are mentioned in Table 14.16.
Abstract Window Toolkit 479
L1 import java.awt.event.*;
L2 import java.awt.*;
L3 public class DemoMenu extends Frame implements ActionListener {
L4 public void demoMenu() {
L5 setTitle("MenuDemo");
L6 setSize(250,150);
L7 MenuBar menuBar = new MenuBar();
L8 setMenuBar(menuBar);
L9 MenuShortcut n = new MenuShortcut(KeyEvent.VK_N);
Abstract Window Toolkit 481
L51 System.exit(0);
}
L52 else if(action.equals("Cut")){
L53 System.out.println("Cut");
}
L54 else if(action.equals("Copy")){
L55 System.out.println("Copy");
}
L56 else if(action.equals("Paste")){
L57 System.out.println("Paste");
}
}
L58 public static void main(String[] args) {
L59 DemoMenu demo= new DemoMenu();
L60 demo.demoMenu();
} }
Output
Fig. 14.17(b) A Sample of Output Displayed from Menu by Pressing Shortcut Keys
Abstract Window Toolkit 483
Explanation
L7–8 MenuBar object is created and it is set on the L23–28 Three menu items created in L14–16 are
frame using the method setMenuBar. added to the fileMenu using the add method. A
L9–11 Three MenuShortcuts have been created separator (line) is added after every menu item using
with the keys n, o, and x. Pressing Ctrl + n would addSeparator method.
refer to a menu onto which it is added. L 29 fileMenu is added to MenuBar.
L12–13 Two menus have been created: fileMenu L30–32 Three menu items (created in L17–19) are
and editMenu. registered with ActionListener for receiving event
L14–16 Three MenuItems have been created and notifications.
shortcuts have been specified for all the three as L33–38 Three menu items created in L17–19
arguments in the constructors (these will be added are added to the editMenu using add method. A
to file menu). separator (line) is added after every menu item using
L17–19 Three other MenuItem have been created addSeparator method.
without any shortcuts (these will be added to edit L39 The editMenu is added to the menu bar.
menu). L46–57 If New menu item is clicked or ctrl+n
L20–22 The menu items are registered with key is pressed, then L47 is executed and so on for
ActionListener for receiving event notifications. the rest of cases.
14.13 SCROLLBAR
Scrollbars are used to select continuous values through a range of integer values (the range set
between maximum and minimum). These scrollbars can either be set horizontally or vertically.
The scrollbar’s maximum and minimum values can be set along with line increments and page
increments.
For creating a scrollbar, you have to create an instance of the Scrollbar class. This class
defines the following constructors:
Scrollbar() throws HeadlessException
Scrollbar(int direction) throws HeadlessException
Scrollbar(int direction, int initValue, int pageSize, int min, int max) throws
HeadlessException
The first constructor does not have any argument; by default it creates a vertical scrollbar.
In the second and third constructors, the direction as argument specifies the orientation of the
scrollbar. If the directions can either be specified as Scrollbar.VERTICAL or Scrollbar.HORIZONTAL,
then vertical or horizontal scrollbars respectively are created. The third constructor can have the
initial value of the scrollbar passed as argument initValue, the number of units represented by
height of the page that gets incremented or decremented when the scrollbar is clicked between
the arrow and the scroll box is passed as argument pageSize and the minimum and maximum
values for the scrollbar passed as argument ‘min’ and ‘max’.
Fig. 14.18
484 Programming in Java
The following line will create a vertical scrollbar with a starting position of 0, a thumb (bubble)
size of 5, a minimum value of 0, and a maximum value of 255:
Scrollbar demoScroll2 =new Scrollbar(Scrollbar.VERTICAL, 0, 5, 0, 255);
There are three different parts of a scrollbar that allow you to select a value between the maximum
and minimum in different ways. The arrows increment or decrement with the line updates which
can be set to a small unit. By default its value is 1. If you click anywhere within the maximum
and minimum range on a scrollbar, the page value will be either incremented or decremented
by a value 10 (default value). The bubble in the middle allows you to traverse the scrollbar
quickly from one end to the other by clicking and dragging it. The visible portion is represented
by the bubble (box in scrollbar). The size of the bubble is represented by the third argument
(5) as shown in the constructor. Table 14.19 lists the methods that can be used with scrollbars.
Interaction with the scrollbar generates an AdjustmentEvent object. The getAdjustment()
method of the AdjustmentEvent class is used to obtain the type of adjustment. The types which
can be returned by this method are
BLOCK_DECREMENT: means ‘page-down event been generated.
BLOCK_DECREMENT: means ‘page-event event has been generated’
TRACK: means ‘absolute tracking event has been generated’
UNIT_DECREMENT: means ‘line-down button in the scrollbar has been generated’
UNIT_INCREMENT: means ‘line-up button in the scrollbar has been generated’
Table 14.19 Methods of Scrollbar
Method Description
void setValues(int initValue, int The parameters here mean the same as in the third
pageSize, int min, int max) constructor mentioned above. If you have used either of
the first two constructors to create a scrollbar you set the
values by the above method so that the values of the above
parameters are set for the scrollbar.
int getLineIncrement() To determine the value of the line increment.
void setPageIncrement(int pageSize) To set the page increment.
int getPageIncrement() To determine the value of the page increment.
int getMinimum() To determine the minimum value.
void setUnitIncrement(int newUnitInc) To set the unit increment by new value.
int getValue() To determine the current position of the scrollbar in terms
of value.
int getMaximum() To determine the maximum value.
void setValue(int newValue) To set the current position.
void setBlockIncrement (int newBlockInc) To set the block increment for page-up and page-down by
a new value.
Abstract Window Toolkit 485
Output
Fig. 14.19
Explanation
L1–2 Imports the necessary packages. L15 The layout is set to BorderLayout.
L3 Frame is created which inherits AdjustmentLis- L16–18 The three components: horizontal scroll-
tener for tapping scrollbar events. bar, vertical scrollbar, and label are added in the
L4–6 Two scrollbar references (one for horizontal EAST, SOUTH, and NORTH directions, respectively.
and another for vertical scrollbar) have been created L19–20 Both scrollbars are registered with
with one label for displaying the position of the AdjustmentListener.
horizontal and vertical scrollbars. Two integer
L21–23 The initial value for the horizontal and
variables, X and Y, are defined for specifying the
exact position of the scrollbars. Also, these two vertical scrollbar is set as 100 and 150 respectively
variables form the width and height of our oval (see using the setValue method and initial scrollbar
Fig. 14.19(b)). values are set as text of the label in L23.
L7 Constructor for the class has been defined. L24–28 The size of the frame and its visibility is
L8–9 Horizontal and vertical scrollbars are set. Apart from this, the frame is registered with the
instantiated. Their orientations have been specified WindowListener to track window closing event.
as Scrollbar.HORIZONTAL and Scrollbar.VERTICAL. L29–33 The method of the AdjustmentListener
L10 Label is instantiated to show the value of the is overridden, i.e., adjustmentValueChanged
scrollbar. (AdjustmentEvent e). This method will be invoked
L11–12 The maximum range is set for both the whenever the scrollbar is adjusted. As the scrollbars
scrollbars using the method setMaximum(400) . are moved, the x and y values change and so the
Actually if you click on the arrow in the scrollbar width and height of the oval. The label is set with the
and scroll it till the maximum, the value that the label current values of the horizontal and vertical scrollbar
will show will be 390 because the size of the bubble
and then the frame is repainted.
is 10 by default. So the range is actually 0 to 390.
L13 The background color is set as cyan. L34–35 paint method is overridden and oval is
L14 The title of the frame is set using the method drawn using the drawOval method of the Graphics
setTitle(). object. The first two coordinates in the oval are fixed.
Abstract Window Toolkit 487
The width and height are variables and they depend L36–37 In the main method, the frame is
upon the scrollbar movements. The signature of instantiated.
drawOval method is shown below:
g.draw Oval (int x, int y, int width, int
height)
/* Anonymous inner classes are defined for all buttons. If listener approach (for
event handling) is used and ActionListener is implemented by the Applet class for
handling button events, then for all five buttons, we have a single "actionPerformed"
method. In the "actionPerformed" we use the if...else..if conditional statement for
knowing which button has been pressed and then we perform the desired task within
that. So there will be five if conditions, one for each button, and these conditions
will be checked every time the button is pressed till a match is found. In our ex-
ample below, each button is registered with its own Event handler, thereby eliminat-
ing the annoying multiple if statements and saving execution time*/
488 Programming in Java
/*creates an Anonymous inner class for hospital button. As soon as the hospital but-
ton is pressed, the actionPerformed of this class is invoked which sets the hospital
Boolean variable to true and repaints the applet. Explicit class name is not provid-
ed by the programmer but the compiler generates the .class file for this inner class
with the name "CityMap$1.class" */
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*sets the Boolean variable to true and repaints the applet*/
hospital = true;
repaint();
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*sets the Boolean variable to true and repaints the applet*/
mall = true;
repaint();
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*sets the Boolean variable to true and repaints the applet*/
pstation = true;
repaint();
}
});
b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*sets the Boolean variable to true and repaints the applet*/
po=true;
repaint();
}
});
b5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*sets the Boolean variable to true and repaints the applet*/
stadium = true;
Abstract Window Toolkit 489
repaint();
}
});
}
g.drawLine(106,41,106,167);
g.drawArc(77,150,30,30,-10,-70);
g.drawLine(6,180,95,180);
g.drawLine(400,41,400,200);
g.drawLine(410,210,600,210);
g.drawArc(400,191,18,20,-90,-90);
g.drawArc(590,210,18,20,-10,90);
g.drawLine(609,222,609,319);
g.drawArc(590,309,18,20,0,-90);
g.drawLine(550,400,603,327);
g.drawArc(545,400,20,20,110,90);
g.drawLine(545,407,545,541);
g.drawLine(220,550,538,550);
g.drawArc(213,550,20,20,90,90);
g.drawArc(524,530,20,20,0,-90);
g.drawLine(170,180,250,180);
g.drawArc(160,180,20,20,90,90);
g.drawArc(240,180,20,20,90,-90);
g.drawLine(260,190,260,230);
g.drawArc(260,220,20,20,-180,90);
g.drawLine(270,241,320,241);
g.drawArc(307,241,20,20,90,-90);
g.drawLine(327,252,327,283);
g.setColor(Color.GREEN);
/* The drawOval of fillOval method creates a circle if width and height of oval is
same. creates a circle which is filled with green color*/
g.fillOval(305,165,60,60);
/* creates an inner circle with white color at x=310 (5 pixels ahead of the previous
circle) and y=170 (5 pixels below the previous circle)
with width and height=50*/
g.setColor(Color.WHITE);
g.fillOval(310,170,50,50);
/*creates an unfilled circle with black color within the broad lined circle created above */
490 Programming in Java
g.setColor(Color.BLACK);
g.drawOval(330,190,10,10);
g.drawArc(306,273,20,20,0,-90);
g.drawLine(170,293,315,293);
g.drawLine(160,190,160,283);
g.drawArc(160,272,20,20,-180,90);
g.drawLine(400,240,546,240);
g.drawArc(532,240,20,20,0,90);
g.drawLine(552,250,552,315);
g.drawArc(531,305,20,20,0,-70);
g.drawLine(500,400,548,323);
g.drawArc(497,398,10,10,110,130);
g.drawLine(498,408,498,510);
g.drawArc(477,498,20,20,0,-90);
g.drawLine(400,519,488,519);
g.drawArc(390,498,20,20,-90,-90);
g.drawLine(390,250,390,510);
g.drawArc(390,239,20,20,90,90);
g.drawRoundRect(6,200,115,230,20,20);
g.drawLine(6,480,112,480);
g.drawArc(98,480,20,20,0,90);
g.drawLine(116,486,150,570);
g.drawLine(212,561,220,580);
g.drawOval(170,330,150,150);
g.setColor(Color.YELLOW);
g.fillOval(220,70,10,10);
g.fillOval(300,550,10,10);
g.fillOval(110,500,10,10);
g.fillOval(420,200,10,10);
g.fillOval(500,350,10,10);
pstation=false;
}
/*if post office button is pressed*/
if(po)
{
g.setColor(Color.BLUE);
g.fillOval(80,150,10,10);
g.fillOval(100,350,10,10);
g.fillOval(500,80,10,10);
g.fillOval(590,400,10,10);
g.fillOval(390,550,10,10);
po=false;
}
/*if stadium button is pressed*/
if(stadium)
{
/*sets the color as black and creates 10 adjacent Circles. First Circle at
(x=170,y=330), second at (x=171,y=331), third at (x=172,y=332) and soon.*/
g.setColor(Color.BLACK);
for(int i=0;i<10;i++)
g.drawOval(i+170,i+330,150,150);
stadium=false;
}
}
}
Output
Fig. 14.20(a)
492 Programming in Java
Figure 14.20(a) shows the map of a city with roads, buildings, round circles, and a stadium.
Fig. 14.20(b)
Figure 14.20(b) highlights the hospitals in the map as the hospital button is clicked.
SUMMARY
In this chapter, we have emphasized on those comput- For this purpose, AWT package has a class known
ing aspects of Java that use graphical user interface as ‘Container’. It may be noted that Panel class is a
(GUI) for input and output. Java has a package named superclass of Applet class. Frame is a subclass of
as java.awt , having various classes responsible Window class. An object of Window class does not have
for generating various GUI frameworks. There are any border or menubar, while a Frame can have these.
various AWT components helpful in providing these frames are therefore generally used as containers.
GUI structures. These components include Button, AWT defines ways to lay the AWT components in
Scrollbar, Choicebox, List, TextField, etc. In the containers. There are many layout managers in AWT
previous chapter, we had studied the basics of event like FlowLayout, GridLayout, GridBagLayout, and
handling model. In this chapter, we used the same CardLayout, available for setting out different patterns
event delegation model, where events are generated for arranging components in containers.
through various GUI components. Menu is a class that inherits MenuItem class and
The Component class is at the root of all AWT two interfaces: MenuContainer and Accessible. The
components whose direct subclasses include: menubar deploys a menu object which is a dropdown
(a) button , (b) canvas , (c) checkbox , (d) choice, menu component. It shows a list of menu choices.
(e) label, (f) list, and (g) scrollbar. A GUI environment To implement this concept, we use three classes:
always needs a container to hold these components. MenuBar, Menu, and MenuItem.
Abstract Window Toolkit 493
EXERCISES
Objective Questions
1. What will be the result of compiling and running (a) FlowLayout (b) GridLayout
the following code? (c) CardLayout (d) BorderLayout
import java.awt.*; 5. What is the default layout for Applet?
import java.applet.*; (a) FlowLayout (b) GridLayout
public class Test extends Applet { (c) CardLayout (d) BorderLayout
Label l = new Label("Hello");
6. What method is used to change the layout of a
public void init() {
setSize(200,100); container?
setVisible(true); (a) setLayout (b) setFlowLayout
l.setBackground(new Col (c) setBorderLayout (d) setCardlayout
or(0,100,180)); 7. Using BorderLayout, you can place components
setLayout(new GridLayout(1,1)); along
add(l); (a) NORTH (b) CENTER
setLayout(new FlowLayout()); (c) SOUTH (d) All of the above
1.setBounds(0,0,100,24); 8. Which listener is associated with MenuItem
}
class?
}
(a) ActionListner (b) MouseListner
(a) The label will fill half the display area of the
(c) ItemListner (d) EventListner
applet.
9. What are the possible types of values of an
(b) The label will be wide enough to display the
anchor field in a GridBagLayout?
text “Hello”
(a) absolute
(c) The label will not be visible.
(b) orientation-relative
(d) The label will fill the entire display area of the
(c) baseline-relative
applet
(d) all the above
2. Which of the following are valid constructors for
10. Which of the following is true about GridBagCon-
a TextField?
straints?
(a) TextField();
(a) It contains the constraint which includes
(b) TextField(int cols);
the height, width of a cell, placement and
(c) TextField(int rows, int cols);
alignment of components.
(d) TextField(int cols, String txt);
(b) Each GridBagLayout object maintains a
3. What is the default layout for a Dialog?
rectangular grid of cell.
(a) FlowLayout (b) GridLayout
(c) A component can occupy one or more cells
(c) CardLayout (d) BorderLayout
and it is called its display area.
4. What is the default layout for Frame? (d) None of the above.
Review Questions
1. What are the component and container classes? 5. What are the different types of AWT components?
2. Which method of the component class is used How are these components added to containers?
to set the position and size of a component? 6. Explain the process of creating a frame and
3. What is the difference between the Font and adding a button to it.
FontMetrics class? 7. Compare the different layout managers in brief.
4. Explain the hierarchy of classes in the java.awt 8. What are the methods used to set foreground
package. and background colors?
494 Programming in Java
Programming Exercises
1. Write an AWT program to create checkboxes for keyboard (via Textfield). A Textfield should be
different courses belonging to a university such used to display the converted temperature. Use
that the courses selected would be displayed. the following formula for the conversion:
2. Create a frame having Menubar and MenuItems Celsius = 5/9*(Fahrenheit–32)
attached to it as follows: 7. Write an application that plays ‘guess the number’
as follows:
Your application chooses the number to be
guessed by selecting an integer at random in the
range 1–1000. The application then displays the
following in a label:
I have a number between 1 and 1000. Can you
guess my number?
Please enter your first guess.
A Textfield should be used to input the guess.
As each guess is input, the background colour
3. Create a frame and set the color of the frame to should change to either red or blue. A label
red. should display either ‘Too High’ or ‘Too Low’ to
help the user zero in. When the user gets the
4. Create a list of vegetables. If you click on one of
correct answer, ‘Correct’ should be displayed,
the items of the list, the item should be displayed
in a textbox. and the TextField used for input should be
changed to be uneditable. A button should be
5. Write a program using AWT to create a simple
provided to allow the user to play the game
calculator. (Hint: Use proper Layout Manager)
again. When the button is clicked, a new random
6. Write a temperature conversion program that
number should be generated and the input
converts from Fahrenheit to Celsius. The
TextField changed to be editable.
Fahrenheit temperature should be entered from
15.1 INTRODUCTION
AWT is used for creating GUI in Java, but the components in java.awt are heavyweight
components. AWT provides graphical user interface with certain limitations. One major limitation
is the translation of various components into their corresponding, platform-specific equivalents
or operating system equivalents. The look and feel of a component is not defined by Java but by
the platform itself. The components of AWT use native code resource and are therefore called
heavyweight components. These components look different on different platforms and even
they act differently on different platforms. Heavyweight components also have a restriction
that they are always rectangular. It is very difficult to work with AWT, for example, if we want
to re-position a button slightly to the right or left, we have to do various modifications in our
source code and recompile it again.
Swing (javax.swing) is the solution for the problems faced in AWT. Swing is the set of GUI-
related classes supplied with JDK1.2 and later. Swing components use modelview-controller
architecture for all its components, thus providing greater flexibility. All swing components have
a model, view, and a controller. Model manages the state and the behavior of the component.
View manages the display of the component depending upon the state, and controller governs
the interaction of the user with the model. Controller basically determines when and how the
state of the model will change.
496 Programming in Java
Swing GUI components are event-driven. Swing provides a very good programming approach
to build a GUI application using OOP concepts. It is included in Java as a part of JFC (Java
foundation classes). It contains all the features of AWT but swing components are called
lightweight because they are developed using Java and hence they are platform independent. In
other words, they do not depend on native counterparts (peers) to handle their functionality. In
total, swings have 18 packages but generally, most programmers use the following packages:
javax.swing
javax.swing.event
It has a number of built-in controls: trees, tabbed panes, sliders, toolbars, tables, etc.
We can customize our GUI application, e.g., we can change the border, text alignment,
or add an image to almost any control, and also we can separate internal representation
from visual appearance.
A very attractive feature of swing is its pluggable look and feel. You can change the
After Java 5, components can be added using add (Component c) method. Earlier they
Swing is not thread safe. When creating a swing GUI, you need to take extra care if
Note You can use either swing or AWT for your Java program development, but avoid mixing the two.
15.2 JFrame
Swing provides a top-level container to which components are added, e.g., JFrame, JApplet,
etc. JFrame is a subclass of java.awt.Frame and therefore, it inherits all the features of an AWT
frame. Whenever you create a top-level container, an intermediate container of the top-level
container named root pane (JRootPane) is automatically created. This root pane has four sub-
level containers (layers) as shown in Fig. 15.1.
Every root pane will always have a layered pane, content pane, and a glass pane. The menu
bar is optional. A layered pane is a container that positions components into three-dimensions.
Actually it adds depth to the container and components can be placed one over the other. The
layered pane is responsible for managing the content pane and the menu bar. The glass pane
is transparent. It is basically used for intercepting events so that they cannot reach the content
pane. The menu bar is used to set the menu on the root pane.
All components are added to a content pane which is an intermediate container. There are two
ways of getting a content pane:
Every container has a content pane. The content pane is obtained using getContentPane()and it
returns a Container object (recommended). Prior to JDK 5, the content pane has to be obtained
explicitly by using getContentPane() and then add() is used on it, e.g., getContentPane().
add(Component). But now there is no need to obtain the content pane explicitly. You can
directly use add() method as shown in Example 15.1.
Build your own content pane. It is common to create a new panel for the content pane and
tell the window to use this new panel as its content pane. For example,
class Demo extends JFrame{
...
// JPanel is a also container with FlowLayout as default layout
// so we can use it as our own content pane and add contents to it.
JPanel panel = new JPanel( );
panel.add(...);
panel.add(...);
...
panel.setOpaque(true);
setContentPane(panel); // set JPanel as the content pane for the JFrame
...
}
Example 15.1 shows a small program that uses swing components to print a message.
// size of window
L5 setSize(300,200);
L6 setDefaultCloseOperation(EXIT_ON_CLOSE);
L8 add(label);
Output
Fig. 15.2(a) Output if the Pack Method is Fig. 15.2(b) Output if the Pack Method (L9)
Commented and SetSize is Used is executed
Explanation
L1 For creating a GUI using swing, we have to L6 setDefaultCloseOperation (int operation)
import the package javax.swing.* is a method that specifies the operation to be
L2 The class inherits from JFrame. A class needs performed when the user closes the frame. The
to be a subclass of JFrame for creating frames following values can be passed as an argument in
using swings. (Note that JFrame is one of the four this method. All parameters have been defined by
heavyweight classes present in the javax.swing WindowConstants interface to control the window
package. The others being JApplet, JDialog, and closing operations.
JWindow.) DO_NOTHING_ON_CLOSE does nothing. It requires
L3 Method demoSwing has been defined. you to handle the event using traditional
L4 setTitle “{First Swing Program}” sets the windowClosing method.
title of the frame as FirstSwingProgram shown in HIDE_ON_CLOSE hides the frame after invoking any
Fig. 15.2(a). registered WindowListener objects.
L5 The method setSize (300,200) sets the size
H DISPOSE_ON_CLOSE hides and disposes the frame
of the frame. 300 is an integer specifying width in
after invoking any registered WindowListener
pixels. 200 is an integer specifying height in pixels.
objects.
500 Programming in Java
EXIT_ON_CLOSE (This has been defined in the which components are added. add(label) method is
class JFrame). It exits the application using the used to add labels to our frame. The add() method
System exit method. In the previous chapter, we is inherited by JFrame from Container class of
have seen the same effect when the following AWT. By default, content pane of JFrame uses
code was written: BorderLayout.
add Window Listener (new Window
L9 It is commented. When you try to run this
Adapter() example with this line uncommented, the output will
{ be as shown in Fig. 15.2(b). The pack() method
public void windowClosing() cases a Window to fit according to the preferred size
{ and layouts of its subcomponents. Using the pack()
System.exit(0); method, we need not specify the size of window.
} L10 setVisible (true) sets the visibility of frame
}); to true. If this method is not used, the frame will
L7 JLabel is a component to display information not be visible. By default, the visibility of window
like text or icon. The text to be displayed is passed is false.
to the constructor. L11–12 An object of DemoSwing is created and the
L8 All top-level containers have a contentpane to method demoSwing is invoked.
15.3 JApplet
JApplet is used for creating applets using swings. JApplet is a Container class like JFrame,
so it possesses all the panes. Components are added to JApplet as they are added in JFrame.
JApplet extends Applet class, so it contains all the features of AWT applet. A class needs to be
a subclass of JApplet for creating applets in swings. We have already seen how applets can be
created using the Applet class in Chapter 12. The lifecycle of a JApplet is same as the life cycle
of an applet. You can override any of the life cycle methods whichever is required by your swing
applet. In swings, painting is avoided in paint() method.
The example below shows a JApplet with an init() which places three buttons within the
applet (Fig. 15.3).
L1 import java.awt.*;
L2 import javax.swing.*;
/* <applet code = "JAppletDemo.class" width = "300" height = "100"></applet>*/
L3 public class JAppletDemo extends JApplet {
L4 public void init(){
L5 setLayout(new FlowLayout());
L6 add(new JButton("Button 1"));
L7 add(new JButton("Button 2"));
L8 add(new JButton("Button 3"));
}}
Swing 501
Output
Explanation
L1–2 Packages java.awt (for FlowLayout class) L6–8 Within init() , three buttons have been
and javax.swing are imported. added. The class for button in swing is JButton. It
L5 The JApplet layout is changed to FlowLayout. has been instantiated and string argument is passed in
By default, the JApplet has BorderLayout. the constructor which forms the caption of the button.
15.4 JPanel
JPanel is a lightweight container used for holding components which include JButton, JLabel,
JList, JToggleButton, etc. If you want to put a component to JPanel, then simply add it using
add(Component c) method, then add the JPanel to its top-level container like JFrame. However,
JPanel can also act as a replacement for Canvas class, as there is no JCanvas class in the swing
package. If JPanel is used in place of canvas, you need to follow two additional steps. Firstly,
set the preferred size via the method setPreferredSize (the preferred size of a canvas is its
current size, whereas a JPanel (or panel) determines its preferred size from the components they
contain). Secondly, you should use paintComponent method for drawing, not paint. In addition
to that, you should first clear the screen by super.paintComponent.
JPanel j = new JPanel(); //assumes double buffer and flowlayout
j.add(new JLabel("Name")); //adds Jlabel to JPanel
j.add(new JTextField(" ",15)); // adds JTextField to JPanel
j.add(new JButton()); // adds JButton to jpanel
add(j);
.
.
.
502 Programming in Java
Example 15.3 shows three components: checkbox, radio button, and toggle button, and how
event handling is done for JToggleButton (Fig. 15.5).
L14 c1.addItemListener(this);
L15 c2.addItemListener(this);
L16 add(c1);
L17 add(c2);
L18 m = new JRadioButton("Male");
L19 f = new JRadioButton("Female");
L20 ButtonGroup bg = new ButtonGroup();
L21 bg.add(m);
L22 bg.add(f);
L23 m.addItemListener(this);
L24 f.addItemListener(this);
L25 add(m);
L26 add(f);
L27 tb = new JToggleButton("Change Color");
L28 lbl = new JLabel();
L29 add(lbl);
L30 tb.addItemListener(this);
L31 add(tb);
L32 setVisible(true);
}
Output
Fig. 15.5(a) Frame Showing Check Boxes, Radio Buttons, and Toggle Button
Fig. 15.5(b) On Selection of Toggle Button, the Fig. 15.5(c) On De-selection of Toggle Button,
Color of the Frame Turns Blue the Color of the Frame Turns Red
Fig. 15.5(d) On Selection of Checkbox, the Label is Set with the Text
Fig. 15.5(e) On Selection of Radio Button, the Label is Set with the Text
Swing 505
Explanation
L1–5 The reference variables for various com- L25–26 The radio buttons are added to the JFrame.
ponents are created like JRadioButton, JCheckBox, L27 Toggle button is created with caption passed
JToggleButton, and JLabel. A reference variable as an argument to the constructor of JToggleButton.
for container is also created for content pane. These The constructors of this class are shown in Table 15.5.
variables have been declared outside the method L28–29 A new JLabel is instantiated and added
because the instances will be required in other meth- to the frame.
ods as well. L30 The ItemListener is registered with JToggle-
L12–13 Two checkboxes have been created with Button . Whenever you select or de-select the toggle
the captions passed as arguments to the constructors button, the state of toggle button changes generat-
as string. The constructors for JCheckBox are shown ing an ItemEvent which is passed to the method
in Table 15.3. itemStateChanged(ItemEvent e).
L14–15 Both checkboxes are registered with L31 Adds the toggle button to JFrame.
ItemListener to handle events using the method L33 Method itemStateChanged(ItemEvent e)
addItemListener(this). is overridden. As soon as a checkbox is checked or
L16–17 Both checkboxes are added to the frame. radio button selected or a toggle button selected/
L18–19 Two radio buttons are created and their deselected, an ItemEvent is generated and this
captions are passed as argument to the constructor. method is invoked.
The constructors for JRadioButton are shown in L34–45 Checks who generated the event using
Table 15.4. getItem() and what is the state of the component:
L20 An instance of ButtonGroup is created. This SELECTED or DESELECTED. The state can be
class is used to group components into a group so that obtained using the method getStateChange() .
only one may be selected out of them. Typically it is Different event handing code is written for different
used for JRadioButton and ToggleButton. We are components depending upon which component
using it for JRadioButton in this example. generated the event, e.g., if toggle button is selected,
L21–22 Both radio buttons are added to a button we have changed the color of content pane to blue and
group. Now only one can be selected. when it is de-selected, we have changed the color of
L23–24 Both radio buttons register themselves content pane to red. For check box and radio button,
with ItemListener using addItemListener method the label is set with a string whenever a checkbox or
for listening event. a radio button is checked.
15.6.1 SpringLayout
The SpringLayout is a very flexible layout in the sense that it does not place components on its own
but according to the constraints specified by the putConstraint method. The constraints specify
the distance between two edges of component or distance between the edges of a component
and its container. The edges can be in any direction: north, south, east, or west. Let us take an
example to illustrate this concept (Fig. 15.6).
L9 contentPane.setLayout(layout);
L10 setSize(250,100);
Output
Explanation
L1–2 Packages java.awt (because getContent- e is the edge of the dependent component
Pane() returns an object of type java.awt.Con- c is the dependent component
tainer) and javax.swing are imported. p is the distance between edge e of c and edge
L8 SpringLayout object is created. e1 of c1
L9 setLayout method is used to set SpringLayout e1 is the edge of the anchor component
to the content pane. c1 is the anchor component
L11 Label is created with the caption as Name.
The possible set of values for edges can be
L12 JTextField object is created with two
arguments. First is a default string to be displayed SpringLayout.EAST
in the text field and second is the number of columns SpringLayout.WEST
that determines the width of the field. If it is made 0 SpringLayout.NORTH
and the program is executed, the frame is displayed SpringLayout.SOUTH
as shown in Fig. 15.7. In the frame below, notice SpringLayout.VERTICAL_CENTER
the width of the text field. Table 15.6 shows the SpringLayout.HORIZONTAL_CENTER SpringLay-
constructors for JTextField. out.BASELINE
L13–14 Label and text field are added to the
In this line, we set the constraints for component label
content pane.
L15–16 A button is created with a caption Submit and that the distance between west edge of label and
and added to the content pane. west edge of content pane is just 5 pixels.
L17 putConstraint method is used to specify the L18 The north edge of the label is just 5 pixels away
location of a component in the JFrame. The signature from the north edge of the content pane.
of putConstraint method is as follows: L19 The west edge of the text field is 5 pixels away
public void putConstraint(String e,Component c, from the east edge of the label.
int p, String e1, Component c1) L20 The north edge of the text field is just 5 pixels
It specifies the distance between edges e and e1 of away from the north edge of the content pane.
components c and c1, respectively as p, where
L21–22 L21 places the button in the horizontal negative value moves the component upwards from
center of the content pane. An integer value of 0 is southern edge of the content pane and specifying a
specified so that it remains in the center. L22 specifies positive value moves it towards the southern edge
the distance between the south edge of the button and of the content pane.
south edge of the content pane as –5. Specifying a
15.6.2 BoxLayout
The BoxLayout places all the components in a single row or column. Without making it complex,
we can put more than one panel in horizontal and vertical directions, similar to GridBagLayout.
The BoxLayout manager is designed with an axis parameter that specifies the type of layout.
This can be done in four ways:
X_AXIS—Components are placed horizontally from left to right.
Y_AXIS—Components are placed vertically from top to bottom.
LINE_AXIS—Components are placed in a line, based on the container’s ComponentOrientation
property.
PAGE_AXIS—Components are placed the way text lines are written on a page, based on the
ComponentOrientation property of container.
Tables 15.7 and 15.8 list the ComponentOrientation property of Page_Axis and Line_Axis.
Table 15.7 Page_Axis
Component Orientation Components Layout
Horizontal Horizontally, else vertically placed.
Horizontal;left to right Placed left to right, otherwise else right to left.
Vertical orientations Laid from top to bottom
Output
Explanation
L3 BoxLayout object is created. The constructor L5–7 Three buttons are added to the content pane.
has two arguments: They are displayed according to their axis (see Figs
public BoxLayout (Container target, int axis) 15.8 and 15.9).
L4 setLayout method sets the layout of the content
pane.
This method is overridden by the class that inherits the ListSelectionListener and wants to
capture the ListSelectionEvent. This method is executed whenever the items in the list are
selected.
The JList supports single selection, multiple selections, as well as multiple interval selection.
The setSelectionMode(int sm) method is used to set the selection mode.
The integer sm can take any one of the three possible values as shown in Table 15.9.
Example 15.6 illustrates the usage of JLabel. Selection is done on JList, the selected item is
displayed in a JLabel (Fig. 15.10).
Table 15.9 Fields of ListSelectionModel
ListSelectionModel.SINGLE_SELECTION Used for selecting only one item at a time.
ListSelectionModel.SINGLE_INTERVAL_ Used for selecting a single contiguous range of items at
SELECTION a time.
ListSelectionModel.MULTIPLE_INTERVAL_ Used for selecting any number of contiguous ranges of
SELECTION items at a time.
Output
Fig. 15.10 JList with a JLabel to Display the Selected Items in the List
Explanation
L1–3 Packages java.awt ( for BorderLayout // for more constructor see JDK 6 Docs
class), javax.swing, and javax.swing.event are
L15–16 The list model is populated and items
imported.
are added to the list. The addElement method of
L4 Class defined to inherit JFrame and ListSelec-
DefaultListModel is used to add individual items
tionListener. On selection of an item in the JList,
to the list.
ListSelectionEvent is generated which is captured
by ListSelectionListener. public void add Element (Object o)
L5–6 Three instance variables have been defined of L17 List is registered with its associated lis-
type JList, Jlabel, and DefaultListModel so that tener, i.e., ListSelectionListener to listen for
they can be accessible from any method in the class. ListSelectionEvent generated on change in the
L12–13 The DefaultListModel is instantiated selection on JList.
and applied to the JList. The constructor of JList L18–19 The scroll pane is added to the top, i.e.,
accepts a ListModel. NORTH and the label is added to the bottom, i.e.,
L14 A JScrollPane consists of a scroll bar SOUTH.
(JScrollBar) as well as a view port (JViewport). The L20 Visibility is set to true.
view port is used to manage the view of data which is L21–22 The valueChanged method is overridden
scrollable. A JScrollPane is required when the size to capture the ListSelectionEvent. This method
of data model or source exceeds the size of the frame. extracts the selected value from the list using a
The component that needs a scroll pane is passed as method getSelectedValue(). This method returns
an argument to the JScrollPane constructor. In this an object of type Object class which is then cast to
case, the horizontal and vertical scroll bars appear string type and then set as the caption for the label
automatically whenever required, i.e., the data model using setText method of the JLabel. This setText
exceeds the frame size area. method accepts a string, so cast of object to string
JScrollPane j = new JScrollPane(Component c) had to be performed.
Swing 513
Output
Explanation
L1–2 Two instances of JPanel are created for each newContinuouslayout is a boolean value indicating
portion that will be split by JSplitPane. whether components will be redrawn or not when
L3–4 Two labels are created, one for each panel the divider is moved.
with caption ‘First Area 1’ and ‘Second Area 2’. c1 denotes that the component will be displayed in
L5–6 JLabel are added to JPanel. the top portion (in case of VERTICAL_SPLIT) and
L7 JSplitPane object is created. The constructor left portion (in case of HORIZONTAL_SPLIT).
used in the example is shown below:
JSplitPane (int orientation, boolean c2 denotes that the component will be displayed in
newContinuouslayout, Component c1, Component c2) the bottom portion (in case of VERTICAL_SPLIT)
where orientation can take two values: JSplit- and right portion (in case of HORIZONTAL_SPLIT).
Pane.HORIZONTAL_SPLIT and JSplitPane.VERTICAL L8 setOneTouchExpandable (true) method of
SPLIT. HORIZONTAL_SPLIT will divide the entire JSplitPane is used to provide up/down arrow on
horizontal area into parts. VERTICAL_SPLIT will di- the divider. Clicking on the arrows expands/contracts
vide the entire vertical area into parts (see Fig. 15.11). the split pane.
15.9 JTabbedPane
JTabbedPane allows a user to switch between different tabs containing components or a group
of components (see Fig. 15.12(a) and (b)). The individual tabs will have a title and may contain
icons as well. Table 15.10 shows the constructors for JTabbedPane.
Table 15.10 Constructors of JTabbedPane
Constructor Description
JTabbedPane() Creates a tabbed pane with a default tab placement,
i.e. JTabbedPane.TOP.
JTabbedPane(int tabPlacement) Creates a tabbed pane with tab placement specified.
The tab placement can take any one of the following
values:
JTabbedPane.TOP
JTabbedPane.BOTTOM
JTabbedPane.LEFT
JTabbedPane.RIGHT
or
public void addTab(String title, Icon i, Component c)
Output
Explanation
L7–9 JLabel is created with text Label in Tab1 String getToolTipTextAt(int index)
and added to JPanel. When you place your mouse over the tab, you will
L10–12 JToggleButton is created with the caption see the tooltip text appears as shown in Figs 15.12(a)
ChangeColor and added to another JPanel. We have and (b).
not registered the Toggle button for event handling, so L18–20 The JTabbedPane and JLabel are added
nothing will happen once you click on Toggle button. to the content pane.
L13 JTabbedPane instance is created with default L23–25 An anonymous inner class is defined here
placement. to handle the ChangeEvent generated when the user
L14–15 Individual tabs are added to the tabbed clicks on a tab. JTabbedPane registers itself with
pane using addTab method. This method also ChangeListener using addChangeListener method.
specifies what the individual tabs will contain. For The anonymous inner class will inherit the interface
ChangeListener and the method stateChanged
example, Tab1 contains panel1 and Tab2 contains
(ChangeEvent e) (L 24) will be a part of that class.
panel2.
This method sets the value of the JLabel(txt)with
L16–17 Tooltip can be set/get for the tabs using
a string concatenated with the selected index of the
the following methods:
tab. The selected index of the tab is obtained by
void setToolTipTextAt(int index, String tooltip) getSelectedIndex() method of JTabbedPane.
15.10 JTree
The JTree class is used to display hierarchical data. A JTree object provides a view of the data.
The tree obtains its data by querying its data model. The snapshot of a JTree is shown in Fig. 15.13
JTree displays the data vertically. Each row contains exactly one node. There are three types
of nodes in a JTree: root node, branch node, and leaf node. All nodes will have a common
root node at the top of the tree. A node can either have children or cannot have children. Nodes
that have children are called branch nodes and nodes that do not have children are called leaf
Swing 517
/* Another hierarchy of branch node has to be added within the branch node one */
L12 DefaultMutableTreeNode oneInNumber=new
DefaultMutableTreeNode("1");
/* Leaf node created for node Labeled "1". The second argument to the con
structor specifies that this node will not have children*/
518 Programming in Java
L25 add(jt);
L26 setSize(200,200);
L27 setVisible(true);
}
L28 public static void main(String args[])
{
L29 new JTreeDemo("My Tree");
}
}
Swing 519
Output
Fig. 15.14(b) Node One is Expanded and Nodes TreePath (i.e., [Numbers, One])
and Name is Displayed on Command Prompt
Fig. 15.14(c) Sub Node 1 is Expanded and Node’s TreePath and Name is
Displayed on Command Prompt
520 Programming in Java
Fig. 15.14(d) Node One is Collapsed and “Collapsed” is Printed on the Screen
Fig. 15.14(e) Root node is Collapsed and “Collapsed” is Printed on the Screen
Explanation
L1–3 Import the required packages. T h e nodes of JTree, we use DefaultMutableTreeNode
javax.swing.tree sub package is imported because (which inherits the TreeNode interface) class. The
we want to use DefaultTreeModel and DefaultMu- caption for the node is passed within the constructor
tableTreeNode class in our program. of the DefaultMutableTreeNode.
L4 Class declaration. First of all a root node (dtm1) is created using
L5–7 Reference variables of JTree, Default- DefaultMutableTreeNode class. The branch nodes
TreeModel and DefaultMutableTreeNode are created. and their child branch nodes are also created using
L8 Constructor declaration. DefaultMutableTreeNode class and are added to their
L9 Sets the title of the frame. respective parent branch nodes. The branch nodes
We want to create our own tree structure so we are added to the root node. Lastly the root node is
need to create a TreeModel . The constructor of added to the DefaultTreeModel object (dtm), which
JTree accepts a TreeModel object. TreeModel is an is passed in the constructor of JTree object.
interface in the java.swing.tree package, so we use L10 Creates the first node (root node, i.e., dtm)
DefaultTreeModel class which inherits the TreeModel using DefaultMutableTreeNode class. The statement
interface. We have passed the DefaultTreeModel creates a node labeled as “Numbers” with no parent
object within JTree constructor. A TreeModel will and no child but allows children.
have nodes. The constructor of DefaultTreeModel L11 Creates a branch node (i.e., one) using
accepts an object of type TreeNode which is an DefaultMutableTreeNode class. The statement
interface in java.swing.tree package. For creating creates a node labeled as “One” with no parent and no
Swing 521
child but allows children. This is a branch node within passed within the constructor of DefaultTreeModel.
the root node so it will be added to root node in L16. The boolean argument in the constructor of
L12 Creates another branch node to be added DefaultTreeModel specifies that any node can have
within the branch node labeled “One”. children including the last nodes. If we omit this
DefaultMutableTreeNode oneInNumber=new
statement and add dtm1 (root node object) directly to
DefaultMutableTreeNode("1");
the JTree, then the last branch nodes like 2, as in our
case, are not considered for TreeExpansionListener
L13 Creates a leaf node labeled as “1.1” to be event. (Try to see the difference in output by adding
added within branch node labeled as “1”. The second dtmto JTree and later by adding dtm1to JTree.)
argument (false) to the constructor specifies that this L22 Adds the DefaultTreeModel to the JTree
node will not have children. object.
DefaultMutableTreeNode oneInNumber2=new De- L23 Uses an anonymous inner class for handling
faultMutableTreeNode(“1.1”, false); tree events. TreeExpansionListener is used
for handing TreeExpansionEvent. This event
L14 Shows how to add leaf node labeled “1.1” to is raised as soon as the Tree is expanded or
node “1”. collapsed. TreeExpansionListener has two
oneInNumber.add(oneInNumber2); methods: treeCollapsed and treeExpanded. These
two methods are overridden in the anonymous inner
L15 Branch node labeled “1” is added to node
class with a print statement within them. As the node
labeled as “One”.
is double clicked, treeExpanded method is invoked.
one.add(oneInNumber); This method prints the TreePath of the node on which
L16 Branch node labeled as “One” is added to root the user has double clicked. The TreePath is obtained
node “Numbers”. using the getLeadSelectionPath method of JTree
dtm1.add(one); class. TreePath is path of the node starting from the
root node up to the node on which the user has clicked
L17–20 Creates another hierarchy of branch node
(see output). The node label can also be obtained
within the root node. The node labeled “2” is added
using the getLastSelectedPathComponent() of the
to node labeled “Two” of the root node.
JTree class.
L21 Creates a DefaultTreeModel object and
L24–29 These have already been discussed in
DefaultMutableTreeNode (root node) object is
various examples.
15.11 JTable
The JTable class lets you display tables of data. Figure 15.15 shows a simple table:
Let us create a JTable for Fig. 15.15 and monitor it for cell selections. As soon as a user selects
a cell, its value is displayed to the user (Fig. 15.16).
L1 import javax.swing.*;
L2 import java.awt.event.*;
L3 class TableDemo extends JFrame
{
L4 JTable jt;
L5 JScrollPane jsp;
L6 TableDemo(String title)
{
L7 setTitle(title);
L8 Object row[][]={{"Kavi","Delhi"},{"Nitin","Dehradun"}};
L9 Object col[]={"Name","Address"};
L10 jt = new JTable(row,col);
L11 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* if this value is set, a column can be selected otherwise the entire row is high
lighted.*/
L12 jt.setCellSelectionEnabled(true);
Output
Explanation
L1–2 Imports the required packages. of the JTable. Anonymous inner class is created for
L3 Class declaration. handling mouse events. We wanted to track mouse
L4–5 A reference variable of J T a b l e and click only, so we have overridden the mouseClicked
JScrollPane is created. (MouseEventme) method only. As soon as the mouse
L6–7 Constructor is declared to accept a string is clicked on a cell, this method extracts the value of
which is used for setting the title of the JFrame. that cell and prints it on the console. The getValue
L8–10 Table is a collection of row and columns. At method of JTable is used to extract the value
Therefore, two arrays have been created in L9 and L10, of particular cell. We want to get the value of the
a two-dimensional array for populating the rows and selected cell, so we have passed the index of the
one-dimensional array for column names. These are selected row (getSelectedRow()) and the selected
added to the JTable by passing in its constructor in L11. column (getSelectedColumn()) in the getValueAt
L11 Exits the application as soon as a user clicks on method.
the X button on the upperleft corner of the JFrame. String string = (String)jt.getValueAt
L12 By default, complete row are selected on user (jt.getSelectedRow(),
clicks. We want to select a particular cell in any row. jt.getSelectedColumn());
So, we have to enable cell selections as shown in
this statement. L14–15 JTable is added to JScrollPane, which is
added to the frame.
L13 MouseListener is registered with JTable to
L16–19 All these lines have already been explained.
track mouse click events on individual cell elements
In the previous example, we have monitored for only cell selections. In the following example
we will be monitoring selection of a complete row and even multiple rows. Let us create another
JTable and monitor it for row selections (Fig. 15.17).
L7 TableDemo2(String title)
{
L8 setTitle(title);
L9 Object row[][]={{"Kavi","Delhi"},{"Nitin","Dehradun"}};
L10 Object col[]={"Name","Address"};
L11 jt=new JTable(row,col);
L12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
L13 /*selectionModel = jt.getSelectionModel();*/
L14 /*selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);*/
L15 jt.addMouseListener(new MouseAdapter(){
}
});
}
L21 public static void main(String[] args)
{
L22 new TableDemo2("Table Demo2");
}
}
Swing 525
Output
Explanation
L6, 13–14 Are commented. They are specifically been selected by the user. This information can be
commented and shown in this example for a purpose. obtained using the getSelectedRowCount() method.
We have allowed multiple row selections. In case Subsequently we extract the number of columns
you wish to allow for a single row selection, these in that table using the getColumnCount() method.
commented statements must be uncommented. As Thereafter we use the getSelectedRows() method to
explained earlier, ListSelectionModel interface obtain the index of all the selected rows. This method
provides the user with an option to set different returns an integer array (i.e., sel[]). To iterate and
selection modes. These modes are provided as print the selected rows a nested for loop is created.
static fields of ListSelectionModel interface and The outer loop is used to iterate through the selected
these modes are used to set the selectionMode field rows and inner for loop is used to print all the column
of JTable class. These modes have already been values of a selected row. The getValueAt() method
discussed in Table 15.9. is used to obtain cell values of selected rows as in
L15 A user can select any number of rows and we the previous example. All the selected row indexes
need to print all the selected rows. So first of all, are stored in an integer array sel, which is passed as
we need to determine the number of rows that have first argument in the getValueAt method.
where parent is the frame in which the dialog will be displayed. msg is the message that will be
displayed in the dialog. title sets the title of the dialog. optiontype may be one of the following:
JOptionPane.DEFAULT_OPTION
JOptionPane.YES_NO_OPTION
JOptionPane.YES_NO_CANCEL_OPTION
JOptionPane.OK_CANCEL_OPTION
This method returns an int value indicating the option selected by the user. The possible return
values could be one of the following: YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION,
CLOSED_OPTION.
The message dialog displays a message to the user. It can be created using the method shown
below:
public static void showMessageDialog(Component parent, Object msg) throws
HeadlessException // creates an information message dialog
or
public static void showMessageDialog(Component parent, Object msg, String
title, int messagetype) throws HeadlessException
It seeks input from the user and returns it as a string. The option dialog displays a list of options
to the user and prompts him to choose one. The following method shows how it can be created
and used:
Swing 527
It requires the user to select an option from the available set of options specified by the Object[]
option. i specifies an image icon for the dialog. initialValue specifies the default value. All
methods throw a HeadLessException which occurs when this code is invoked in an environment
which does not support mouse or keyboard.
l.setText("NO"); }
L19 else if(e.getActionCommand().equals("Option Dialog"))
{
L20 String values[] = { "Car", "Bike", "Bus" };
L21 l.setText((String)JOptionPane.showInputDialog(frame,"Select one", "Enter
Your Choice",JOptionPane.INFORMATION_MESSAGE, null,values,values[0]));
}
}
} // inner class ends here
Output
Fig. 15.18(a) JFrame with Four JButtons Fig. 15.18(b) Message Dialog
Explanation
L1–7 Four buttons are created and ActionListener L15–18 If the user clicked on confirm dialog
is registered with all of them. The JButton along with button, a confirm dialog is displayed. Method
a label are added to the frame. showConfirmDialog is used to create a confirm
L8 A new JFrame is constructed for holding dialog dialog. The title of the dialog is ChooseOne and the
boxes (frame). message inside the dialog is Choose. The user clicks
L9–20 An inner class has been defined for on either yes or no. To check what is the response
capturing JButton events. of the user, we have used if statement and matched
L9 When a button will be clicked, ActionEvent the return value with JOptionPane.YES_OPTION (if
will be handled by MyAction object. yes is clicked) and JOptionPane.NO_OPTION (if no
L10 Method actionPerformed overridden. is clicked). The label is set accordingly.
L11–12 Uses if statement to confirm which button L19–21 If the user clicks an option dialog button,
has been clicked upon. If it is a message dialog an option dialog is displayed. A list of options is
button, the user is shown a message in a message displayed in a lookalike combo box control and the
dialog box. The getActionCommand method returns user makes a single selection in this control. The
the caption of the button as a string. The method used default value can also be specified. L20 shows a
to create a message dialog is showMessageDialog list of all values that will be inserted in an option
which we have already discussed. dialog. L21 creates an option dialog using the method
L13–14 If the user clicked on input dialog button, showOptionDialog as discussed. The selection is
an input dialog is shown to the user. He/she can enter returned as an object of type Object which is then
the value desired which is returned as a string. The cast to a string and set as the caption for the label
returned value is set as text for the string. (Fig. 15.18).
15.13 JFileChooser
JFileChooser class provides a file open dialog where a user can choose to open or save files.
JFileChooser class navigates the file system to choose a file or directory. Figure 15.19 shows
the JFileChooser used to open a file. Note the title of file chooser is “Open” and the two buttons
towards the end are Open and Cancel.
Figure 15.20 shows the JFileChooser save dialog. Please note the title at the top is “Save” and
the two buttons towards the bottom are “Save” and “Cancel”.
The file chooser class is instantiated and the showOpenDialog method is used to show the
Open file dialog and showSaveDialog method is used to show the Save file dialog. Some of the
constructors of JFileChooser class are shown below in Table 15.11. We will be depicting the
practical usage of JFileChooser class in the practical problem (Section 15.17).
15.14 JColorChooser
JColorChooser is a tabbed control which can be used to manipulate and select a color.
Figure 15.21 shows the JColorChooser. As soon as a color is chosen it is added in the list of
Recent: Colors (see Fig.15.21) and the color of the sample text in the preview pane changes
according to the color chosen by the user.
JColorChooser can be created by using a showDialog static method of this class. This method
displays the dialog on top of the container where you can choose a color of your choice. The
chosen color is returned as a Color object on the press of the OK button.
JColorChooser.showDialog(parent component, title, default color)
We will be depicting the practical usage of JFileChooser class in the practical problem (Section
15.17).
Swing 531
Although not part of Java API, the following Look and Feel packages are shipped along with
Java SDK.
com.sun.java.swing.plaf.gtk.GTKLookAndFeel (for Solaris/Linux)
com.sun.java.swing.plaf.motif.MotifLookAndFeel (runs on any platform)
com.sun.java.swing.plaf.windows.WindowsLookAndFeel (only Windows)
A system-defined (native) look and feel shows the GUI according to the look and feel
of the native system.
Synth Using this, you can create your own look and feel
(javax.swing.plaf.synth.SynthLookAndFeel).
Multiplexing Delegates to different look and feel at same time
(javax.swing.plaf.multi.MultiLookAndFeel).
532 Programming in Java
GTK+ This look and feel runs on Solaris and Linux O.S which have GTK+ 2.2 or later
installed in them. The Solaris and Linux O.S without GTK or earlier version of GTK
installed in them will have Motif Look and Feel.
IBM Unix, HP Unix, and Macintosh provide their own Look and Feel.
The look and feel can be get and set using the methods getLookAndFeel() and setLookAndFeel()
of the javax.swing.UIManager class. Their signatures are as follows:
static LookAndFeel getLookAndFeel()
static void setLookAndFeel(LookAndFeel l)
static void setLookAndFeel(String className)
LookAndFeel class is the parent of all the look and feel classes in Java. It has two subclasses,
BasicLookAndFeel and MultiLookAndFeel. The BasicLookAndFeel is inherited by MetalLookAndFeel
and SynthLookAndFeel. The NimbusLookAndFeel class inherits the SynthLookAndFeel class.
The metal look and feel has themes associated with it. The default theme is OceanTheme. Prior
to JDK5 the default theme was DefaultMetalTheme (also known as steel). These themes can be
get/set using MetalLookAndFeel class methods:
public static void setCurrentTheme(MetalTheme m)
public static MetalTheme getCurrentTheme()
Let us take an example to see how look and feel can change according to an event. There are
five buttons in the frame; one for each Look And Feel. The look and feel of the frame changes
as soon as these buttons are pressed.
Container c;
LookAndFeel()
{
setTitle("LookAndFeel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1 = new JButton("Metal");
Swing 533
b2 = new JButton("Motif");
b3 = new JButton("System");
b4=new JButton("Nimbus");
b5=new JButton("Synth");
c=getContentPane();
c.setLayout(new FlowLayout());
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setVisible(true);
pack();
}
public static void main(String args[]) throws Exception
{
L2 SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LookAndFeel();
}
});
}
public void actionPerformed(ActionEvent ae)
{
try{
String str=ae.getActionCommand();
L3 if(str.equals("Metal"))
{
L4 UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
L5 //UIManager.setLookAndFeel(javax.swing.plaf.metal.MetalLookAndFeel);
}
L6 if(str.equals("Motif"))
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
534 Programming in Java
L7 if(str.equals("System"))
L8 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
L9 //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
L10 if(str.equals("Nimbus"))
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
L11 if(str.equals("Synth"))
{
L12 SynthLookAndFeel slaf = new SynthLookAndFeel();
L13 slaf.load(LookAndFeel.class.getResourceAsStream("rules.xml"),LookAndFeel.
class);
L14 UIManager.setLookAndFeel(slaf);
}
}catch(Exception e){}
L15 SwingUtilities.updateComponentTreeUI(c);
}
}
Output
Fig. 15.22(a) Java Metal Look and Feel (Default) Fig. 15.22(b) The Motif Look and Feel
Swing 535
Fig. 15.22(c) The System-defined Look and Feel Fig. 15.22(d) The Nimbus Look and Feel
(on Windows 7)
Fig. 15.22(e) The Synth Look and Feel Fig. 15.22(f) button.png
Explanation
L1 Imports the synth package. The other classes MetalLookAndFeel)that has cross-platform look and
have been referred by their complete names. feel. This class name is passed to setLookAndFeel
L2 As already told, the swing framework is method. The class name can also be directly
not thread safe. A swing programmer has to take mentioned as shown in comments below L5.
care in programming GUI so that his GUI is L6 If Motif button is clicked, the motif look and feel
always responsive. Swing provides three types is set using method UIManager.setLookAndFeel().
of threads, namely initial, eventdispatching, The class name has been directly mentioned "com.
and workerthreads. The job of initial threads is to sun.java.swing.plaf.motif.MotifLookAndFeel".
schedule a task for execution of event dispatching L7–8 If System button is clicked, the native
thread. The task is scheduled using two methods
look and feel is set using the method UIManager.
invokeAndWait and invokeLater. These methods
setLookAndFeel(). The class name has been
are provided by the class, SwingUtilities. The
directly mentioned "com.sun.java.swing.plaf.
responsibility of an initial thread is to create a
windows.WindowsLookAndFeel". The class name can
runnable object which would initialize the GUI and
then schedule the object on an event dispatching automatically be retrieved using the method
thread. Worker threads are used for executing UIManager.getSystemLookAndFeelClassName()
long running task, normally background task. The as shown in commented line below L9.
difference between invokeLater and invokeAndWait L10 If Nimbus button is clicked, the native
is that, invokeLater schedules a job and returns, look and feel is set using the method UIManager.
whereas invokeAndWait schedules a job and then setLookAndFeel(). The class name has been directly
waits for it to complete. mentioned "com.sun.java.swing.plaf.nimbus.
public static void invokeLater(Runnable r) NimbusLookAndFeel".
public static void invokeAndWait(Runnable r) L11–14 If Synth button is pressed, all components
(Note: It should be used in all examples above) on the frame should be shown according to the
L3–4 If Metal button is clicked, the cross-platform Synth Look And Feel.
look and feel is set using the method UIManager. Synth Look and Feel is highly customizable. You
getCrossPlatformLookAndFeelClassName(). This can specify style rules for each Synth component
method returns the LookAndFeel subclass name (i.e., such as button, label, and text field. Each component
536 Programming in Java
has defined region associated with it. Region is a way change automatically. As well as, there is no need to
of identifying all or part of the component. Normally compile the program again and again. The style rules
a component has a single region associated with it (.xml file) are separate from your program. This XML
but some components can have more than one region file is loaded in the program using the load method of
associated with themselves like split pane, tabbed the SynthLookAndFeel class. The load method (L13)
pane, and scrollbar . Regions for various components accepts an object of type InputStream (which refers
are defined as constant in the javax.swing.plaf. to the XML file) along with the resource base (which
synth.Region class. Some of the common regions is the class itself in our case). XML files have to read
are shown in Table 15.12. The style rules are by the class hence we need an InputStream instance
specified using SynthStyle. Using SynthStyle, you that refers to the .xml file. The InputStream instance
can specify style rules that affect the size, layout, is obtained using getResourceAsStream method of
font, color, etc. Even you can specify background the java.lang.Class. The getResourceAsStream
images for components. The most important part of method is used to refer to external resources like
SynthStyle is that different styles can be specified XML configuration files and property files, etc. and
for different components. These styles are obtained return an InputStream instance. You can refer to files
through a SynthStyleFactory . All components using absolute and relative pathnames. An absolute
contact the SynthStyleFactory to obtain synth styles path is preceded by a slash (e.g. /chap 15/rules.
for all its regions. The SynthStyleFactory can be xml) whereas relative path is not preceded by a slash
defined either by creating an XML file or by creating and name is relative to the location from where the
a class. We will be using the first approach of creating method is invoked (e.g., rules.xml) (Fig. 15.22).
an XML file which will contain all the styles rules. L15 Whenever the look and feel is changed, all
The benefit of putting style rules in an XML file is the swing components have to be updated to reflect
that if you want to change the look and feel of any or the look and feel changes. The method used for this
all the components, you just need to change the rules purpose is shown below:
in XML file and the look and feel of your GUI will SwingUtilities.updateComponentTreeUI(c);
The argument passed is the content pane so that all components in the content pane reflect the
new look and feel.
Overview of XML
To understand the XML file, we first need to understand XML along with its structure and its
rules of creation. So let us take an overview of XML.
XML stands for extensible markup language. XML file have an extension .xml and they can
be written in any editor like notepad. XML is a case sensitive language. Unlike HTML, XML
provides a clear cut separation of contents from presentation and is hierarchical in nature. An
XML files contains user defined tags. These tags conform to some rules specified in a DTD
(document type definition) file like
(a) Name of the root tag.
(b) Which tags will have attributes?
(c) What will be name of the attributes?
(d) What is the possible value of these attributes?
(e) Which tags will have text or sub tags or a combination of both etc.?
We will be following a predefined DTD structure so the tags that we are going to use in our xml
file are already defined. There are certain rules that we should know before creating an XML file.
538 Programming in Java
SourceInsets attribute is used to specify width <bind style=” StyleId “ type=”region" key=”.*”/>
and height of the corner areas of an image. We want to specify rules for buttons. The type
The significance of this attribute is that image attribute of the bind tag is used to specify a "region"
should not be stretched at corners beyond these and key will be “button”. The rules apply to all the
values. The four values passed as in this attribute buttons on the frame. In case you wish to apply
correspond to top, left, bottom and right corners separate rules for separate buttons, the bind tags
of the image. should be used in the following way:
L7 Closes the state tag. <bind style="StyleId" type="name" key="name
L8 Closes the style tag. of the button" />
L9 Shows an empty tag <bind>. This tag is used to For example, if the button name is Nimbus and style
bind the style rules mentioned in the above lines to a id is nimbusStyle, then bind tag will be as follows:
component. The identifier of the style tag is passed in <bind style="nimbusStyle" type="name"
the style attribute of the bind tag. You will have more key="Nimbus" />
than one bind statement to bind styles to different L10 Closes the root tag <synth>.
components. In case you wish to apply rules to all
the components used in the GUI, the bind tag will
be as shown below
L14 setContentPane(dp);
L15 setBounds(100,100,600,600);
L16 setVisible(true);
L17 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
L26 newItem.addActionListener(this);
}
L27 public void actionPerformed(ActionEvent ae)
{
/* (title, resizable,closable,maximizable,iconifiable) */
L28 jif=new JInternalFrame("Internal Frame"+count++,
false,true,true,true);
L29 jif.add(new JLabel("This an Internal Frame"));
L30 jif.setSize(300,200);
L31 jif.setLocation(20*count,20*count);
L32 jif.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
L33 jif.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
L37 public void internalFrameOpened(InternalFrameEvent i)
{
L38 System.out.println("New Internal Frame Opened");
}
Swing 541
L49 jif.setVisible(true);
L51 try{
L52 jif.setSelected(true);
L53 }catch(java.beans.PropertyVetoException p){}
L54 /*dp.add(jif);*/
}
L55 public static void main(String args[])
{
L56 SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DemoInternalFrame();
}
});
}
}
542 Programming in Java
Output
Fig. 15.23(b) Another Internal Frame is Created. The Previous Frame (Frame 0) is Deactivated
and New Frame is Opened and Activated
Fig. 15.23(c) Internal Frame 1 is Iconified. So it becomes Deactivated. The Frame Beneath it
Becomes Activated and the Internal Frame 1 is Minimized
Swing 543
Fig. 15.23(e) Internal Frame 1 is Closed. The Closing Method is Called and Frame is
Deactivated. The Frame Beneath it becomes Activated and the Internal Frame 1 is Closed
Explanation
L6 A reference variable of JDesktopPane is created. combination is pressed on the file menu.
It is a subclass of JLayeredPane. It is a container used L28–54 Execute on every New menu item click.
for creating MDI (multiple-document interface). L28 An internal frame is created using the
Internal frames are created using JInternalFrame JInternalFrame class. Five arguments are passed
class and added to the JDesktopPane. within the constructor of JInternalFrame class. The
L7 A reference variable of JInternalFrame is first one specifies the title of the internal frame,
created. second argument specifies whether the internal
L8–9 We want to add file menu to our frame, so frame can be resized or not, third argument specifies
reference variable of JMenuBar and JMenu are created. whether the internal frame can be closed or not, forth
L10 Static variable count is created to keep track argument specifies whether the internal frame can
of the number of internal frames created. be maximized or not, and final argument specifies
L11 Constructor for the class is declared. L11–26 whether the internal frame can be iconified (i.e.,
show the constructor of the class. minimized) or not. The title of the frame includes
L12 Sets the title of the frame. the count variables so as soon as a new frame is
L13–14 JDesktopPane is instantiated in L13. The created, count is incremented and title is set. The
desktop pane is set as content pane of the frame internal frame cannot be resized as second argument
(L14). is specified as false.
L15 setBounds is used to resize the frame. The L29 To show how components can be added to the
top-left corner is specified by x and y coordinates (first internal frames, we have added a label on the internal
two arguments), and the size is specified by width frame using the add method.
and height (third and fourth arguments). L30 The size of the internal frame is set using the
L18–26 We have to create a file menu on the frame. setSize method.
So a JMenuBar is created (L18) and set on the frame L31 Location for the internal frame has been
using setJMenuBar() method (L19). A File menu is specified using the setLocation method. If the
created using JMenu (L20). Mnemonic is set for the location is not specified, new internal frames will
File menu using the setMnemonic method (L21). appear on top of older internal frames once they
Mnemonic is a key which if used in combination are created. In other words they will fully cover the
with alt key activates the menu / menu item on older inner frames. So location is set to show the
which it has been set. Mnemonics are specified as user that internal frames are created and user can
static integer constants in java.awt.event.KeyEvent easily switch between frames. The setLocation
class. We have specified that when key combination method accepts two arguments: x and y coordinates.
alt+f is pressed, the file menu should be opened. We have to specify new coordinates for every inner
So the argument passed is VK_F. The file menu is frame created. The count value increases on every
added to the menu bar in L22. A New menu item is inner frame creation. This value is multiplied with
created in L23 using JMenuItem. A mnemonic for a constant value to achieve new x and y coordinates
New menuitem is set in L24. The key combination for the new internal frame. So whenever you create
used to activate this menu item is alt+n and hence a new frame the new location for the internal frame
the argument to setMnemonic method is VK_N.it is a is somewhere below the older frame (see Fig. 15.23).
part of file menu so it is added to file menu in L25. L32 Specifies the close operation for the internal
Lastly, it is registered with ActionListener (L26) frame. As soon as the cross on the internal frame is
so that the click event on this New menu item can be pressed, the internal frame is disposed.
monitored and handled. L33 The cursor on the internal frame is changed
L27 actionPerformed method is overridden. The using setCursor method. The cursor class has static
ActionEvent is passed to this method as soon as the constants to change the visual display of the cursor.
user clicks on the new menu item or the mnemonic The following values can be specified:
Swing 545
Note Note that we have created a very basic editor. We have purposely not created the entire editor
for you because we want you to create it on your own. Many students find it difficult to start
with a project. So, we have provided a beginning to you. While making enhancements to this
editor, you might change the structure of the program or may create more classes to support
your editor.
546 Programming in Java
mn.add(n);
mn.add(op);
mn.add(saveas);
mn.add(exit);
mb.add(mn);
copy.addActionListener(this);
cut.addActionListener(this);
paste.addActionListener(this);
Swing 547
ed.add(copy);
ed.add(cut);
ed.add(paste);
mb.add(ed);
/*Pop up Menu created which will be displayed once a user right clicks on the editor*/
pum=new JPopupMenu();
/*The pop up menu will have the following options: copy,cut,paste, change
color of the text*/
/*registers pop up menu items with action listener so that something happens
when user clicks on those Pop up menu items*/
pumcopy.addActionListener(this);
pumcut.addActionListener(this);
pumpaste.addActionListener(this);
changecolor.addActionListener(this);
/*adds pop up menu to the editor*/
j.add(pum);
/* On mouse click we want to show the Pop up Menu, so we obtain the (x,y)
position of the mouse click using me.getX() and me.getY() methods and show
the pop up menu on those coordinates using the show() method of pop up menu.
The pop up menu has to be shown on the JEditor so the first argument is the
JEditor object.*/
j.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
if(me.isPopupTrigger())
{
int x=me.getX();
int y=me.getY();
pum.show(j,x,y);
}
}
if(me.isPopupTrigger())
{
int x=me.getX();
int y=me.getY();
pum.show(j,x,y);
}
}
});
setJMenuBar(mb);
c.add(new JScrollPane(j),BorderLayout.CENTER);
setSize(300,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
if(ae.getActionCommand().equals("Open"))
{
if(choose.showOpenDialog(this)!=JFileChooser.CANCEL_OPTION)
{
try
{
/* The toURL of the file class is deprecated so to convert it into URL we first have
to convert it to URI and then the URI object to URL */
URL u=choose.getSelectedFile().toURI().toURL();
j.setPage(u);
}catch(MalformedURLException e){}
catch(IOException e){}
}
}
else if(ae.getActionCommand().equals("New"))
j.setText("");
Swing 549
try{
FileWriter fw=new FileWriter (choose. getSelectedFile());
fw.write(j.getText());
fw.close();
}catch(IOException ie){}
}
else if(ae.getActionCommand().equals("Copy"))
{
j.copy();
System.out.println(j.getCaretPosition());
}
else if(ae.getActionCommand().equals("Paste"))
{
j.paste();
}
else if(ae.getActionCommand().equals("Cut"))
{
j.cut();
}
/* show a dialog on top of the editor where you can choose a color of your choice.
The chosen color is returned as a color object.*/
/* JColorChooser.showDialog(parent component, title,default color) */
/* change the color of the text in the editor as the color chosen by the user.*/
j.setForeground(col);
}
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Editor();
}});
}
}
550 Programming in Java
Output
Fig. 15.24(a) File Menu of the Editor is Displayed Fig. 15.24(b) Edit Menu of the Editor is
When Mouse Click Occurs on File Menu Displayed When Mouse Click Occurs on Edit Menu
Fig. 15.24(c) Pop Up Menu on the Editor is Displayed When Right Mouse Click Occurs on Editor
SUMMARY
Swing is a very powerful API provided by Java for Many new components have been added in
creating graphical user interfaces. The most impor- swings which help in creating more interactive
tant feature of swing components is that they are GUIs. JSplitPane splits the display area into parts.
lightweight, swing components are written in Java, so JTabbedPane groups together a number of components
they are portable and the GUI has a pluggable look and displays them as a unit. JScrollPane has all the
and feel. All component names follow Jxxx format, e.g., functionality of a scrollbar as well as view pane. Dialog
JButton, JPanel, JLabel, JTextField, etc. boxes (provided by other GUI software tools) are also
provided by swing package.
Swing 551
Four types of dialog boxes have been provided, edge over other languages. The cross-platform look
namely confirm dialog, input dialog, option dialog, and feel gives Java GUI a standard look and feel which
and message dialog. New layouts have been added is uniform on all platforms. Apart from this, the native
in swings like BoxLayout and SpringLayout. The look and feel is also supported.
pluggable look and feel feature gives Java an upper
EXERCISES
Objective Questions
1. Why are swing components termed as light- (a) SINGLE_SELECTION
weight? (b) SINGLE_INTERVAL_SELECTION
(a) they depend on native platform (c) MULTIPLE_INTERVAL_SELECTION
(b) they do not depend on native platform (d) MULTI_INTERVAL_SELECTION
(c) they depend on native application 7. Which method is used to make a split pane
(d) they do not depend on native application expand or contract when you click on the divider?
2. Which method is used to close a swing frame? (a) setOneTouchExpandable
(a) setTitle() (b) setExpandable
(b) setDefaultCloseOperation() (c) setExpandContract
(c) setVisible() (d) setDivider
(d) pack() 8. Which method is used to add tabs to a
3. Which pane is used for placing components on JTabbedPane?
a JFrame? (a) addTabbed (b) addTab
(a) content pane (b) root pane (c) setTabAt (d) setTabbedPane
(c) layered pane (d) glass pane 9. The class used to create input dialog box in Java
4. The default layout of a content pane is is
(a) FlowLayout (b) BoxLayout (a) JInputDialog (b) JDialogBox
(c) SpringLayout (d) BorderLayout (c) JOptionPane (d) JConfirmDialog
5. Which method is used to set the selection mode 10. The method used to create a confirm dialog in
for the JList? swing is
(a) setSelectionMode() (a) showInputDialog
(b) setSelection() (b) showMessageDialog
(c) setMode() (c) showOptionDialog
(d) setSelectedMode() (d) showConfirmDialog
6. Which mode is used for setting ‘multiple interval
selection’ mode for a JList?
Review Questions
1. Explain the difference between swing and AWT. 5. What are the various dialog boxes available in
2. Explain the difference between invokeLater and swing and how are they created?
invokeAndWait methods. 6. What are inner frames? What classes are used
3. Explain the pluggable look and feel feature of to create them?
swings along with the look and feels available 7. Explain the role of JFileChooser class.
in Java. 8. How are trees created in a Java GUI?
4. What is the difference between JButton and 9. How can you create a table having multiple rows
JToggleButton? and columns in a Java frame?
552 Programming in Java
Programming Exercises
1. Create a login form which contains a user id, 3. Create a split pane which divides the frame into
password field, and two buttons, submit and two parts. The first part possesses a list and on
reset. If the user id or password field is left blank, selecting an item in a list, the item should be
then on click of submit button, show a message displayed in the other portion.
to the user to fill in the fields. On click of reset 4. Create a tabbed pane and place the login form
button, clear the fields. (Exercise 1) on first tab and the list (Exercise 2)
2. Create two lists using JList class with a button. on second tab.
On click of that button, all selected items in one
list are copied to the other list.
etc.).
554 Programming in Java
JDBC defines a few steps to connect to a database and retrieve/insert/update databases. The
steps are as follows:
Load the driver
Establish connection
Create statements
Execute query and obtain result
Iterate through the results
16.2.1 Load the Driver
If your program needs a database connection, then the first step is to load the driver. JDBC
version 4.0 (works only with Java 6 and above) onwards the manual loading of database driver
was done away with. It is now done automatically, but for learning purpose, we will show you
all the steps involved. The driver is loaded with the help of a static method,
Class.forName(drivername)
Every database has its own driver. Table 16.1 shows the driver names for a few databases.
Table 16.1 Driver Names
Database name Driver Name
MS Access sun.jdbc.odbc.JdbcOdbcDriver
Oracle oracle.jdbc.driver.OracleDriver
Microsoft SQL Server 2000 com.microsoft.sqlserver.jdbc.SQLServerDriver
(Microsoft Driver)
MySQL (MM.MySQL Driver) org.gjt.mm.mysql.Driver
Data source name (DSN) is created by the programmer through ODBC API. DSN keeps a
record of which database needs to be accessed, the location of the database, and the driver needed
to access the database. Optional attributes like user id and password are also maintained with
DSN. There are three types of DSN:
User DSN—for a specific user.
File DSN—for all users who have same drivers installed and the users can be on different
machines.
Anyone of these three can be created using ODBC API depending upon the requirement. The
advantage of using this type of driver is that it is readily available. However, it has the following
disadvantages:
Performance is much low as JDBC calls ODBC and ODBC driver access
Table 16.2 shows the various database URLs for connecting to various databases.
Table 16.2 Few Database URLs
Database Database URL
MS Access jdbc:odbc:<DSN>
Oracle thin driver jdbc:oracle:thin:@<HOST>:<PORT>:<SID>
Microsoft SQL Server 2000 jdbc:microsoft:sqlserver:// <HOST>:<PORT>[;DatabaseName = <DB>]
lot of time. So to increase efficiency, we use precompiled PreparedStatement. In this case, only
the values that have to be inserted are sent to the database again and again.
PreparedStatement ps = con.prepareStatement(String query);
A CallableStatement object is used to call stored procedures. It is created using the preparecall
method.
CallableStatement cs = con.prepareCall(String query);
The method executeQuery is used for executing SQL statements that return a single ResultSet,
e.g., a select statement. The rows fetched from database are returned as a single ResultSet
object. For example,
ResultSet rs = stmt.executeQuery("select * from emp");
The method executeUpdate is used for DDL and DML SQL statements like insert, update,
delete, and create. This method returns an integer value for DML to indicate the number of rows
affected/inserted (also known as update counts) and 0 for DDL statements which do not return
anything. For example,
PreparedStatement ps = con.prepareStatement("update emp set salary = ?
where empid = ?");
The statement is sent to database and is prepared for execution, only the value of the IN (?)
parameters need to be sent.
ps.setInt(1,100000);
ps.setString(2,"Emp001");
ps.executeUpdate();
The PreparedStatement has certain methods that are used to set value for the IN parameters as
shown in the lines of code above. In setInt(1,100000), the first argument is the ordinal position
of the IN parameters. This method will set salary = 100000 and the method setString (2,
"Emp001") sets the second IN parameter in the query, i.e., where empid = ‘Emp001’.
The execute method is used for callable statement when the statement may return more than
one ResultSet or update counts or a combination of both. This happens when stored procedures
are executed.
16.2.5 Iterate ResultSet
The ResultSet is iterated with the help of a method next which returns a boolean value to
indicate that the ResultSet has more rows to be iterated. The next method moves the cursor to
the next row. The individual column data is obtained by using accessor (i.e., getX) methods. For
example, if the first column is a string, the method to fetch its value is getString(1). Similar
methods are available for other data types:
558 Programming in Java
Note A ResultSet object is automatically closed when the Statement object (from which ResultSet
was obtained) is closed, or re-executed.
Example 16.1 shows a program to demonstrate how the data is stored and retrieved from a
database. Assuming that an emp table is already created in MS-Access with three attributes:
EmpId, Name, and Salary. To access the database of dsn by the name ‘sac’ is also created.
ps.setInt(3,10000);
System.out.println("Row inserted : " +ps.execute Update());
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
// obtaining meta data of the result set
ResultSetMetaData rsmd = rs.getMetaData();
int cc = rsmd.getColumnCount();
System.out.println("Number of columns in result set:" +cc);
for(int i = 1;i < = cc;i++)
System.out.print(rsmd.getColumnName(i)+ "\t");
System.out.println();
while(rs.next())
{
System.out.print(rs.getString(1)+ "\t");
System.out.print(rs.getString(2)+ "\t");
System.out.print(rs.getString(3)+ "\n");
}
}
}
Output
C:\javabook\programs\chap 15>java DatabaseConnection
Row inserted : 1
Number of columns in result set: 3
EmpId Name Salary
Emp001 Peter 10000
Table 16.3 Few Methods of ResultSet Interface Used for Scrolling through it
first() Moves the cursor to the first row of the ResultSet.
last() Moves the cursor to the last row of the ResultSet.
previous() Moves the cursor to the previous row of the ResultSet.
absolute(int row) Moves the cursor to the specified row number.
relative(int row) Moves the cursor relative to the current row of the ResultSet.
A negative value can be specified to move backwards and positive value to move forward.
getRow() Returns the current row number.
560 Programming in Java
For example, the Statement object for a scrollable result set having concurrent read only mode
can be created as shown below:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Result Set.
CONCUR_READ_ONLY);
DatabaseMetaData dbm=con.getMetaData();
System.out.println(dbm.supportsResultType(ResultSet.TYPE_FORWARD_ONLY));
System.out.println(dbm.supportsResultType(ResultSet.TYPE_SCROLL_INSENSITIVE));
System.out.println(dbm.supportsResultType(ResultSet.TYPE_ SCROLL_SENSITIVE));
System.out.println(dbm.supportsResultTypeConcurrency(ResultSet.TYPE_ SCROLL_
SENSITIVE,));
Note This feature may not be supported by all JDBC driver. The database meta data can be obtained
from the connection object and queried to know whether a driver supports scrollable result
sets or not as shown below. The supportsResultType method returns boolean values to tell
whether a ResultSet type is supported or not. The method supportsResultTypeConcurrency
also returns boolean to inform whether a type along with concurrency type are supported
together or not.
16.2.7 Transactions
A transaction is a set of statements that if executed should complete it entirety. If any of the
statement fails to execute in a transaction, the entire transaction should be rolled back. To enforce
this and execute SQL statements in a transaction, the auto commit feature should be turned off.
Auto commit feature commits the changes made by SQL statements to the database and is by
default set to true. It can be set using the following method of the connection object:
con.setAutoCommit(false);
Introduction to Advanced Java 561
If any problem occurs during a transaction, it can be rolled back by using the rollback method
on the connection object.
con.rollback();
The following code snippet will show you how a short transaction can be created and in case of
a problem exception occurs and the changes are roll backed.
try {
con.setAutoCommit(false);
Statement stmt1=con.createStatement();
Statement stmt2=con.createStatement();
stmt1.executeUpdate("Query 1");
stmt1.executeUpdate("Query 2");
con.commit(); /* commit the changes to the database and make them
permanent. */
...
} catch(SQLException se)
{
try{
con.rollback(); // roll back the changes made to the database.
}
catch(SQLException){}
}
Another way of carrying out a transaction is using batch updates. In this case, a batch of
statements is created and then the batch is executed as a single transaction. If any of the batch
statement fails to execute, the entire batch is rolled back. The following code snippet shows how
a batch of statements can be created and used.
try {
con.setAutoCommit(false);
Statement stmt1 = con.createStatement();
stmt1.addBatch("Query1");
stmt1.addBatch("Query2");
int[] i = stmt1.executeBatch();
con.commit(); /* commit the changes to the database and make them
permanent. */
...
} catch(BatchUpdateException be)
{
try{
stmt1.clearBatch(); // you can clear the batch by using this method
}catch(SQLException){}
}
The executeBatch method returns an integer array of update counts. The update count refers
to the number of rows that are affected on successful execution of every SQL statement. If a
statement fails to execute, BatchUpdateException occurs.
Sometimes it is desired to allow a transaction to be committed even if one or two last steps
of a transaction fail. For example, if you make a transaction like paying a bill, or purchasing an
item, you get a notification in the end through an SMS/email that the transaction has occurred.
562 Programming in Java
The transaction should not be rolled back just because the SMS/ email alert could not be sent at
the time of the transaction. In such a case, Savepoint is used to roll back a transaction to a set
point in a transaction. It is actually an interface in the java.sql package and was introduced in
JDBC 3.0 API. All changes made up to the save point are committed and after the savepoint are
rolled back. The code below shows you how to rollback upto spl. It means rollback all changes
made after sql and commit all changes before spl.
try {
con.setAutoCommit(false); //
Statement stmt1 = con.createStatement();
Statement stmt2 = con.createStatement();
stmt1.executeUpdate("Query 1");
Savepoint sp1 = con.setSavepoint("SavePoint1");
stmt1.executeUpdate("Query 2");
con.commit(); /* commit the changes to the database and make them
permanent. */
...
} catch(SQLException se)
{
try{
con.rollback(sp1); // roll back the changes up to the savepoint
}catch(SQLException){}
}
16.3 SERVLETS
Servlets are Java server-side programs that accept client’s request (usually http request), process
them and generate (usually http response) responses. The requests originate from client’s web
browser and are routed to a servlet located inside an appropriate webserver. Servlets execute
within a servlet container which resides in a webserver like Apache Tomcat. The newer release
of Tomcat has a JSP (Java server pages) container also in it. Normally, HTTP (hypertext transfer
protocol) is used between web client and servlets, but other protocols like FTP (file transfer
protocol) can also be used.
16.3.1 Lifecycle of Servlets
public void init()
Servlets have their own execution lifecycle. The lifecycle includes
three methods as shown in Fig. 16.5.
public void service()
Whenever a client request is received by the servlet container (part
of a webserver), it
public void destroy()
locates the servlet responsible for handling the request and loads it.
instantiates it.
public void doGet()
initializes the servlet by calling init()method, followed by service
http request. If it is a get request, the doGet()method will be called and if it is a post request,
the doPost() method will be called. The get and post are two methods of http protocol used
for transmitting data to the server-side programs like servlets. The service method is capable
of handling both types of requests (get and post). In that case, you need to override the service
method in your servlet. The signature of service method (see Example 16.2) shows two
arguments: ServletRequest object (to handle client’s requests) and ServletResponse object (to
write responses to the client) which are passed to it by the servlet container. The destroy method
is called by the servlet container before the servlet is unloaded. So clean-up activities like closing
the database connections can be done in this method.
16.3.2 First Servlet
Let us create a simple servlet that outputs the contents to the client.
Explanation
L1–3 The packages javax.servlet.*, javax. (usually html responses) to the client. This method
servlet.http.*, and java.io.* have to be may throw ServletException and IOException.
imported to create an HttpServlet. L6 Before sending any data to client, the type of
L4 The class FirstServlet must be a public class data to be sent to the client has to specified with
and it must inherit HttpServlet, as http protocol is the help of a method res.setContentType ("text/
used for communication between client and server. So plain"). In other words, the MIME type (stands
to handle http request from client and generate http for multipurpose Internet mail extension) has to
response for client, we have to create an HttpServlet. set. Nowadays, web pages contain text, images, and
L5 The s e r v i c e method is overridden. It multimedia. A servlet informs the browser about
accepts two arguments S e r v l e t R e q u e s t and the type of data it will be sending to browser. The
ServletResponse . The entire client’s request is servlet in our example is transmitting plain text, so
encapsulated in ServletRequest object (like http, the MIME type is text/plain. If html (webpage) is
ftp) and passed to the service method by the servlet to be sent to the client, the MIME type is text/html.
container along with ServletResponse object. This L7–8 Using the getWriter() method of the res
ServletResponse object is used to send responses object, we get a PrintWriter object. This method
564 Programming in Java
may throw an IOException that is why we have PrintWriter object is used to write the contents to
mentioned it in the throws clause of the service the client. The string argument to the println method
method definition. The println method of the is written to the client as it is.
Or edit the environment variable classpath and append the above path in it.
2. Steps to install Tomcat 7.0 and execute the servlets and JSP The server used by
us for running servlets and JSP is Tomcat 7.0.40. You can download the webserver
installer from Apache Tomcat website (e.g., apache-tomcat-7.0.40). The webserver is
very easy to install. You just need to double click on the installer and the installation
starts. You need to specify the path where you want to install the webserver (if you do
not specify the path it will be installed in program files of your machine). This server
gets installed as a service in your machine. You can manually start/stop this service by
opening the Control Panel of your machine and clicking on Administrative Tools (see
Fig. 16.6). You can also set up two environment variables as shown below. It is a good
practise and will help you later.
JAVA_HOME = c:\program files\java\jdk1.6.0_01 (base directory of JDK)
CATALINA_HOME = c:\Apache\Tomcat 5.0 (base directory of Tomcat)
Double click on Services and click on the Apache Tomcat 7 entry in the Services window as
shown in Fig. 16.7. The service is already running so you are shown two options, i.e., to Stop
and Restart service. If the service is stopped, then only Start service option will be displayed.
Introduction to Advanced Java 565
All the servlets class files are placed in the classes directory. The file web.xml exists
within the WEB-INF directory. A sample web.xml file is shown below for running the
FirstServlet.class.
Tomcat 7.0
webapps
myproj
WEB-INF
Html/JSP
files Classes
Formdata.
html web.xml FirstServlet.class
ReadData.class
RedirectServlet.class
CookieDemo.class
This file has to be edited every time you add a new servlet class in the classes directory. The
two tags <servlet> and <servlet-mapping> along with their sub-tags must be added for every
servlet in the classes directory specifying the name and URL used to call the servlet.
For example, the <servlet> tag specifies that the servlet class FirstServlet.class will be
referred to as FirstServlet and the <servlet-mapping> tag specifies URL for accessing the
servlet, e.g. http://localhost:8080/myproj/servlet/FirstServlet. The servlet is run in the
Internet explorer and the following output (Fig. 16.10) is displayed on it.
On the other hand, post method overcomes these limitations by sending data to the server as a
part of http header format instead of appending it to the URL. This overcomes both the limitations
of the get method.
Table 16.6 Methods Used to Fetch Values from Client’s Request
Methods Description
String getParameter(String n) This method is used to return the value corresponding to a given
name. The name is specified as an argument (String n). ‘name’
is the name of the control in html. To use this method we should
know the name.
(Contd)
568 Programming in Java
For example, consider an email id registration form that requires the users to fill in their
details like name, id, password, and hobbies. This data is sent to a server-side program like
servlet which is then stored in a database. The users can now login using their id and password
and check mails. We have already seen how a Java program can store data into a database. The
question is how a servlet would fetch client’s data from request? The data in both requests (get
and post) is passed to the server in the form of pairs: name = value pairs. Three methods (Table
16.6) can be used for fetching these names and values from the request.
We will create an html form and send the form data to a servlet. The sample servlet will retrieve
the data and rewrite it back to the client. The html form coding is shown in Example 16.3(a)
followed by how it is displayed in the Internet Explorer.
Example 16.3 (a) HTML File for Sending from Data to Server
<html>
<head><title> form data </title></head>
<body>
<center>
<h1><U> Registration Form </u></h1>
<form method = get action = "servlet/ReadData">
Name <input type = text name = fname><br>
Address <input type = text name = add><br>
User id <input type = text name = uid><br>
Password <input type = password name = pass><br>
Gender:
male<input type = radio name = gender value = male>
female<input type = radio name = gender value = female><br>
Hobbies:
Dancing <input type = checkbox name = hobbies value = dance>
Music <input type = checkbox name = hobbies value = music>
Travel <input type = checkbox name = hobbies value = travel>
<br>
<input type = submit>
<input type = reset>
</center>
</body>
</html>
We have created a webpage using html which contains a form. The form tag has two attributes:
method and action. The method attribute is used to specify the method used to send data to server
Introduction to Advanced Java 569
like get and post. The action attribute is used to specify the URL of the servlet responsible
for handling the request. The form contains textfields (e.g. name, address, and UID), password
field, radio button, and checkboxes. These fields are created with the help of input tag. The input
tag has attributes, type and name. The type specifies the type of input field. Table 16.7 shows
a list of possible types. The name attribute is used to give a name to the control. This name will
be used as an argument in the getParameter(String n) method to fetch its value at the servlet.
Table 16.7 A few Values for the Type Attribute of Input Tag
Values of type attribute Description
type = text Creates a text field.
type = submit Creates a submit button which on click, sends the data in the form to servlet
specified in the action attribute of the form tag. The mode of sending is specified by
method attribute.
type = reset Creates a reset button. It resets all the fields in the form.
type = password Creates a password field. The characters in this field are echoed as dots.
type = button Creates a normal button. If you click on this button, nothing happens (use Java
script for event handling).
type = radio Creates a radio button (single selection).
type = checkbox Creates a checkbox (multiple selection).
The reset button resets the form by clearing all the fields and selections. The submit button sends
all the input data and selections to the servlet specified in the action attribute of the form tag.
On clicking submit, the URL will look like the following:
http://localhost:8080/myproj/ReadServlet?fname = peter&add = London&uid = pet_
007&pass = jennifer&gender = male&hobbies = music&hobbies = dancing
The ‘?’ operator separates data from the address. The ‘&’ operator separates one name/value pair
from another. The form is shown below (Fig. 16.11) as it appears in Internet Explorer.
The servlet used for handling client’s request and generating response is shown in Example
16.3(b) . As a response, our servlet echoes all the data back to the client.
Explanation
L1 Apart from other packages, java.util has L6 The getParameterNames() is invoked through
been imported. The reason for this will be clear in the req object. This method extracts all the names
the explanation below. from the names/value pairs in the request object
L2 A public servlet class has been created, named and returns them as an Enumeration of names.
ReadServlet. This class inherits the HttpServlet Enumeration is a collection interfaces. This interface
class, as we are dealing with http request and http is a part of java.util that is why we have imported
responses. this package in L1.
L3 The doGet method is overridden and used for L7–13 Repeated for each name in the Enumeration.
handling get requests from client. This method accepts L8 Extracts the next name from the Enumeration
two arguments: HttpServletRequest (used only for and stores it in a string variable name.
http client request) and HttpServletResponse (used L9 req.getParameterValues(name) returns all
for sending http response to client). Similar to service values associated with the name as a String array.
method, this method also throws ServletException L10–13 for loop is used to iterate through all the
and IOException. values of the array. HTML tags are written within
Introduction to Advanced Java 571
the quotes in the println method to send html to within doPost, we call doGet method. The reasons
client’s browser. The names are specified in bold <b> for overriding doPost and calling doGet from within
and values have been specified in bold and italicized is that the servlet is capable of handling get as well
<i> as shown in Fig. 16.11. as post request. There is no need to worry about the
L14–15 doPost method has been overridden. It request, whether it is a get request or a post request.
is almost entirely similar to doGet method. From
The response sent by the servlet to the client’s browser will appear as shown in Fig. 16.12.
Explanation
L6 The redirect method of the HttpServletResponse You may choose to use relative URL as shown
object is used to redirect all the request made to this in the example also. As you know all html files
servlet to Formdata.html. Whenever the user enters reside in the root (i.e. myproj) directory. You
the URL: can fire RedirectServlet by invoking the path:
http://localhost:8080/myproj/servlet/ localhost:8080/myproj/servlet/RedirectServlet
RedirectServlet, and from this path you need to move to myproj/
the user is automatically redirected and displayed directory so that Formdata.html can be accessed.
the following page: So we need to move up one level and hence the two
http://localhost:8080/myproj/Formdata.html. dots are specified../ followed by filename.
16.3.5 Cookies
Cookies are basically small pieces of information stored on the client’s machine by the browser. A
cookie contains information like user browsing preferences, user id and password combinations,
session id, and the number of times a user has visited a page. This information is stored in pairs,
i.e., name-value pairs. This information wrapped in a cookie object is sent to the client browser
by a servlet, which stores it somewhere in its temporary Internet files. Whenever a request is
sent to that particular server (from where the cookie was downloaded), all the cookies (stored in
the client’s machine from that very server) are attached to the http request and sent to the server.
The server can then fetch the cookies from the request and then act accordingly.
Example 16.5 keeps a track of how many times a user has visited the page. For this purpose,
the servlet creates a cookie and stores it in the client’s machine with the number of counts in it.
Every time the user requests a page, the value from the cookie is fetched, incremented by one,
and stored back again on the client’s machine. The common misconception is that cookies are
a risk. But in reality, cookies are not interpreted or executed in any way. Moreover, 20 cookies
per site are allowed and not more than 300 cookies can be stored by the browser. The size of a
cookie is limited to 4kb (Fig. 16.13).
Introduction to Advanced Java 573
Output
layer. So whenever an http request is sent from the application layer, a new TCP connection is
created at transport layer. That is why, it’s a new request every time an HTTP request is sent,
even from the same client to the same server for the same resource.
Let us take a scenario to understand the session and its importance. When you login to Gmail
server or Yahoo mail server to view your emails, Firstly you enter your user id and password to
sign in. The request along with the user id and password goes to the webserver where your input
values are authenticated. You are shown your mailbox with options to view mails or compose a
message, etc. When you click on inbox to view your email, it is a new http request (which has
no correlation to the previous request) although it goes from the same server to the same client.
The question is how does the server decide, whose inbox is to be shown on this request? The user
id and password that the user typed in came in the earlier request and not this one. One would
think of sending the user id and password combination every time with any request and get it
authenticated from the database, and generate appropriate responses. That is very impractical,
tedious, time consuming, and risky option.
The real problem is to maintain the state of the client across various requests. We need to
maintain the state of the client (session information) across request. Maintaining a client state
will make him identifiable across requests and the server can then easily generate appropriate
responses for valid clients, i.e., once you login you will be shown your emails only and not
somebody else’s email. The client’s state is maintained till the time a client logs out. Now the
question that arises is who is going to maintain the state of the client? The http protocol is stateless
so it does not maintain client information; for it, every request is a new request (had it been a
stateful protocol no problems would have occurred). Obviously you are left with two choices:
client and server to maintain the client state. Depending on which method is chosen for session
maintenance, either the client or the server will maintain the sessions.
The solution is that the client be provided with a unique identifier whenever it makes a request.
This identifier will be used in all subsequent requests to identify a particular client requests from
other. As soon as a user logs in, a unique session id, associated with that user is created. This
id can be maintained across subsequent request using the following ways: (a) hidden fields,
(b) URL rewriting, (c) cookies, or (d) HttpSession API.
Hidden Fields
Hidden fields are html fields not visible to the users. The state of the client is maintained (at the
client side) in these hidden fields and embedded in the responses generated by the servlet. They
are sent back to the server with the http request and extracted by the servlet. Hidden fields are
inserted in html as shown below:
<form method ="" action="URL">
. . .
<INPUT TYPE="hidden" NAME="Id" VALUE="Unique Identifier">
<INPUT TYPE="hidden" NAME="Customer Name" VALUE="Tom">
<INPUT TYPE="hidden" NAME="Item_1" VALUE="Plastic Bottles" >
<INPUT TYPE="hidden" NAME="Item_1_Qty" VALUE="20" >
<INPUT TYPE=Submit> . . .
</form>
576 Programming in Java
Normally there will be no hidden fields when a page is displayed for the user for the first time.
Subsequent requests by the user will force a servlet to add hidden fields to maintain the history/
state of the client. As soon as the submit button is pressed, all data including hidden fields are
sent to the servlet mentioned in the action attribute. The information can be used by the server
for session tracking. Each time the servlet is activated; it creates and sends an html form on the
client browser in addition to other things. This form will have new items to gather user input (if
required) along with the older items (like items checked by the user on the last page).
Earlier this solution was useful in implementing shopping carts where information of users
along with their item selections have to be maintained and finally according to their selection,
bills are generated. This information can be maintained using hidden fields along with a unique
session id. Every time the user requests for a new page, all fields (including hidden fields) are
sent to the server. These fields are extracted by the servlet and set in a new html form, as hidden
fields, to be sent back to the client as part of the response. This method does not need any special
configuration either from the browser or the server and is available for session tracking. However,
the disadvantage is that they will only be sent to the server once the form is submitted and not
when a user clicks on a hyperlink and moves on the next page. They can be used when the amount
of information to be hidden is less. Hidden fields are hidden (not visible) from the users but by
selecting the “View Source”option in the browser, the entire form, including the hidden fields
can be viewed by the user. Hence, hidden fields cannot be used for security purposes.
URL Rewriting
Another way of achieving session management (at the client side) is using URL rewriting. URL
rewriting is a technique in which history/session information/state of the client is appended to
the URL before sending the page back to the client. This URL has to be rewritten in the action
attribute of the form tag or the anchor tags whatever has been used in the page. For example,
If the original URL is http://server:port/servlet/ServletName
The rewritten URL will be
http://server:port/servlet/ServletName?sessionid=123456 & userid=sac123 &...
This technique does not need any special support from the browser but it is a tedious approach.
All data associated with a user can be fetched according to the user id from the databases. (A
session id can also be a combination of user id and a unique number. The user id can be extracted
from the session id and then user specific data can be extracted from the database.). In this
approach you need to take precaution in maintaining and appending the parameters every time
while rewriting URL’s until the session completes. Moreover, you cannot have static pages; each
page will be dynamically generated if this approach is used.
Cookies
A cookie is a small amount of information stored on the client’s machine within the browser’s
files. Cookie can be used to store state/session information on the client side. It is a key value
pair sent by the server to the client. This pair is automatically attached with every request to the
server from where it was downloaded and then sent to the server. We have already shown how
cookies can be used. The advantage of using this technique of maintaining sessions is that it is
a simple and easy approach. The disadvantage is that if the users disable cookies, the browser
will not be able to save the cookie at client computer and session tracking fails.
Introduction to Advanced Java 577
Session API
Session tracking API is built on top of the methods discussed above. All servers support cookies
for session tracking and if any how it cannot be done through cookies, servers switch to URL
rewriting. It reduces the developer overhead as the servlet container manages the session (either
way automatically by cookies or URL rewriting) and the user need not do it explicitly.
The HttpSession API is used for creating and maintaining sessions among clients and servers.
It is within the javax.servlet.http package. HttpSession is an interface within this package and
it maintains all the sessions. All incoming requests carrying session identifiers are automatically
associated with their respective session objects. In other words, every client is mapped with a
session object.
A session is created using a getSession method of the request object. It returns an HttpSession
object. This method is overloaded; one that does not accept any argument and other that
accepts a boolean value. If true is passed as a boolean value in this method, it returns the
current HttpSession object associated with this request or, if none exists then it creates and returns
a new session. If false is passed in the getSession method and the request does not contain any
HttpSession object, this method will return null. If no value is passed in the getSession method,
it behaves in the same way as getSession(true).
A session object can be used to hold values which can be retrieved whenever required.
But you can only store and retrieve objects from a session. The method setAttribute() and
getAttribute() respectively are used to store and retrieve objects from the session object. The
attributes will be set in key-value pairs. So in case you wish to store primitive type such as int
and float, you will have to use their respective wrapper classes such as Integer and Float. The
following statement shows how to get and set an attribute name to and from the session object
with the value Tom:
session.setAttribute("name","Tom");
String n=(String) session.getAttribute(name);
A session can be destroyed by using the invalidate()function on the session object. All
information corresponding to session will be lost at the server.
along with a hyperlink to Sign out. If the user clicks on Sign Out hyperlink, the Sign Out servlet
invalidates the user session and redirects the user to Login.html.
If the user, at any point of time, clicks on the back button of the browser, the contents of the
previous page are displayed even after the user has signed out, as the html generated by the server
is cached by the browser. To force the browser not to cache the pages, we create a NoCacheFilter.
java class which is actually a Filter class. It forces the browser not to cache the pages but
ask for a fresh copy of the pages from the server every time a URL is accessed. Along with the
NoCacheFilter class we also have an AlreadyLoginFilter.java class which checks whether a
user is logged in or not and if not, all requests are redirected to the Login.html page. This is
basically created for blocking mischievous user requests who try to play tricks and put the URL
of servlets like showAuthenticate and showMessage directly in the address bar without logging.
The Tomcat directory structure of the application is shown in Fig. 16.14.
Tomcat 7.0
webapps
login
WEB-INF
classes
Authenticate.class
ShowAuthenticationDetails.class
ShowMessage.class
SignOut.class
NoCacheFilter.class
AlreadyLogingFilter.class
web.xml
Login.html
Output
Explanation
The page is invoked using the URL: localhost:8080/ body tag. This form has two input fields with two
login (after starting the webserver) as shown in special buttons submit and reset created using input
Fig.16.13. /login is the name of the directory (i.e., tags. One input field is used for entering user id
context root within the webapps directory) that holds (type=text) and other is used for entering password
the webpage. The point to note is that we have not (type=password). Submit (type=submit) and reset
mentioned the name of the file while invoking the (type=reset)buttons are also created using input tag.
html page (i.e., Login.html) but still as soon as On clicking submit button, the data in the form is sent
the above mentioned URL is typed in the browser, to the servlet class mentioned in the action attribute of
Login.html file is displayed. This is because we have the form tag using the method specified in the method
mentioned the welcome-file name in the web.xml attribute of the form tag. As you already know post
method instead of appending the data with the URL
file on the webserver. So as soon as the context root
mentioned in the action attribute, sends data as part
(/login) is invoked, the welcome file for that context
of header. Please note that in the action attribute you
root is displayed. See web.xml file in Example
have to specify the url-pattern mentioned in the
16.6(h). servlet-mapping tag specified in the web.xml file for
The title tag sets the title of the page. You can sending the request to the appropriate servlet without
see the title (login page) on the top blue bar of the the preceding slash.
browser. The form tag is to create a form within the
580 Programming in Java
L14 try
{
L15 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
L16 Connection con=DriverManager.getConnection("jdbc:odbc:auth");
L17 Statement stmt=con.createStatement();
L18 ResultSet rs=stmt.executeQuery(query);
L19 if(!rs.next())
{
L20 response.sendRedirect("/login");
}
L21 else
{
L22 session=request.getSession(true);
L23 session.setAttribute("LOGIN_DONE",true);
L24 session.setAttribute("User-Id",id);
L25 response.sendRedirect("showAuthenticate");
}
Explanation
L1–4 Imports the required packages. name is Login which contains two fields: UserID and
L5 Shows Servlet class declaration. The Servlet Password.
class has to be a public class. L11–13 Used for invalidating any older session (if
L6 As the request that arrives is a post request, the any) present. The getSession method with a false
doPost method is overridden. argument extracts the session from the request (if any
L7 Shows creation of a PrintWriter object so present) and does not create a new session if none is
that responses can be sent to client. The getWriter found. The session, if found, on a user login attempt
method of the response object is used to obtain a in these statements is considered by our application
PrintWriter object. as an old session and is invalidated in if statement
L8–9 Extract the id and password from the request on L15 using the invalidate method.
object using the getParameter method and store L14 try block starts.
them in the separate strings. This id and password L15–18 Statements show how to connect to the
combination will be matched from the database. database. We have used MS-Access 2010 for this
These two fields are submitted by the user in the example. L15 loads the driver, L16 establishes
Login.html page and send to this servlet along with the connection, L17 creates the Statement and
the http request. L18 executes the Statement (query) and obtains a
L10 Shows creation of a SQL query. This query ResultSet object. Note that in jdbc:odbc:auth,auth
is stored in a String variable and will be executed is the data source name. Remember this DSN is
once the database connection is established. Note created in the Data Sources (ODBC) within the
that the id and password extracted from request are Administrative Tools of the Control Panel (see Figs
added to this query to authenticate the user. The table 16.16 and 16.17).
L19–25 On execution of the Query if the result set for servlet-class ShowAuthenticationDetails in the
contains a row it clearly specifies that the user has web.xml file. So to invoke ShowAuthenticationDe-
entered a valid user id and password and rs.next() tails, we are using the name showAuthenticate.
will return true otherwise false. If false, the user is But you would raise one question after having a
redirected back to the context root (/login) on L20 look at the web.xml file in Example 16.6(h) i.e.,
otherwise a new session is created for the valid user
the url-pattern for the said servlet is /auth/
on L22. L23 shows an attribute is set into the new
showAuthenticate and we have just mentioned
session object by the name LOGIN_DONE and value
showAuthenticate in L24. The reason is because
is set as true. We will illustrate its purpose later. L24
sets the user-id into the session object and the user is the user is already in the auth context when the user
redirected to showAuthenticate (i.e., ShowAuthen- invoked/auth/authenticate.
ticationDetails.class) servlet on L25. showAu- L26 Catches the exception raised from the try
thenticate name is specified as the url-pattern block, if any.
Output
Explanation
L1–3 Imports the required packages. As you can see in this line, the title of page is set as
L4 Servlet class declaration. “Welcome” along with the id of the user (see output).
L5 doGet method is overridden as this request (i.e., L11 An h1 heading “Login Successful” is sent
a get request) comes through a hyperlinked URL. to client.
L6 PrintWriter object is created as it is this L12–13 Two hyperlinks are sent to the client:
servlet which will show the user something after it SignOut and ShowMessage. Respective servlets are
is authenticated.
invoked on clicking either of the hyperlinks.
L7 contentType is set as text/html.
L14 An h1 heading “Session Details” is sent to
L8 The session details are acquired from the
request object. The same session created by the client.
Authenticate Servlet is retrieved here. L15–16 Session Id and User Id is sent to the
L9 The user id is extracted and stored in a String client to be displayed.
variable. L17 The requested URI is obtained and sent to
L10 An html is generated for the client and sent the client.
using the println method of the PrintWriter object. L18 html file is closed.
We demonstrated in this particular servlet how to determine that this request belongs to a
particular session and send some details and options back the client.
L6 HttpSession session=request.getSession(true);
L7 response.setContentType("text/html");
L8 PrintWriter out = response.getWriter();
L9 out.println("<HTML>\n" + "<HEAD><TITLE> Show Messages </TITLE>");
L10 out.println(" </HEAD>\n"+"<BODY BGCOLOR=\"#FDF5E6\">\n");
L11 out.println("<H1> Welcome </H1><br>");
L12 out.println("My Session Identifier: "+session.getId()+"<br>");
L13 out.println("My User Id: "+session.getAttribute("User-Id")+"<br>");
L14 out.println("Requested URI: "+ request.getRequestURI () + "<br>");
L15 out.println("<a href=signout> Sign Out</a>");
L16 out.println("</BODY></HTML>");
}
}
Output
Explanation
All similar lines have been explained in the previous showAuthenticationDetails servlets. The user id
example. The important point to note is that the put in the session object is extracted again here and
session id is same in both the ShowMessage and displayed to the user.
Explanation
All similar lines have been explained in the previous session is invalidated and user is redirected to the
example. The important point to note is that the Login.html page.
/*Forces caches to obtain a new copy of the page from the server*/
L7 hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Explanation
This is a filter class and is used for filtering tasks on <filter>
either request or response to and from a resource or in <filter-name>noCacheFilter</filter-name>
both conditions. In other words, a filter’s functionality <filter-class>NoCacheFilter</filter-class>
is either performed before or after the functionality </filter>
of a servlet or a JSP. For example, if a request is <filter-mapping>
made for a servlet on which a filter has been applied <filter-name>noCacheFilter</filter-name>
to allow only authorized user to access the servlet, <url-pattern>/*</url-pattern>
the filter may pass or block the users request on to </filter-mapping>
that servlet depending on which request is legal and Filter, introduced in Servlet 2.3 specification is
which one is illegal. As is evident from Fig. 16.20, actually an interface in the javax.servlet package.
that the request for a resource goes through the filter. This interface has three methods as you can see in
The role of this filter class is to prevent the browser L5, 11, 12. The filtering task is performed in the
cache from storing previous pages but obtain fresh doFilter method. The doFilter method is called by
copy of the pages from the server every time a the container every time a client request for a filtered
resource is accessed. This filter is applied to all the resource which resides at the end of the chain. It may
servlets and is specified in the following fashion be possible that a filter may invoke another filter to
in web.xml file. Note the <url-pattern>/*</url- process a request/response pair. The FilterChain
pattern> specifies that it applies to all. object keeps a track of it. The FilterChain object
586 Programming in Java
allows the request and response to be passed on to L8 Pragma header is part of HTTP/1.0 version. It
the next filter in the chain, if there are more filters to serves the same purpose of not letting the client cache
be processed for a request/response pair and if it is the server responses. This header is basically set for
the last filter in the chain the requested resource is backward compatibility.
invoked. L9 The Expires header specifies the date/time
L6 As doFilter method accepts ServletRequest after which the response is considered stale (old
and ServletResponse types as its arguments, they or expired). An entry marked as stale will not be
need to be cast into HttpServletRequest and returned normally by a cache unless it is validated
HttpServletResponse objects before their respective with the originating server.
methods can be used on them. L10 Shows the FilterChain object calling
L7 Sets an http header “Cache-Control” through the doFilter method. This FilterChain object
the response object. The values are self-explanatory represents a chain of filters which have to be invoked
which specify not to cache, not to store the page one after the other to fulfil a request for a resource.
and ask for a validated copy of the page from the It causes the next filter within the chain of filter to
originating server every time. This header is part be invoked and if the calling filter is the last filter in
of HTTP version 1.1 but some browser and caches this chain, the resource is invoked.
supporting older version of http protocol ignore it L12 When the servlet filter is loaded for the first
so pragma and Expires header should also be set to time, its init() method is invoked.
avoid caching in any circumstance.
Servlet
Http Request
Filter
JSP
L7 if(null == session.getAttribute("LOGIN_DONE"))
{
L8 ((HttpServletResponse)response).sendRedirect("/login");
}
L9 chain.doFilter(request, response);
}
L10 public void destroy(){}
L11 public void init(FilterConfig f){}
}
Introduction to Advanced Java 587
Explanation
The purpose of creating this filter is to allow only </filter>
authorized session holders to view the messages and <filter-mapping>
the authentication detail pages. Unlike the previous <filter-name>checkLoginFilter</filter-
filter, this filter is applied to only to the showmessage name>
and showAuthenticate servlets. This is specified in <url-pattern>/auth/showmessage</url-pat
web.xml file as shown below (see url-pattern tag tern>
below). So, if a user, instead of accessing the login <url-pattern>/auth/showAuthenticate</
page, tries to access the showmessage servlet directly url- pattern>
by typing the following URLin the browser address </filter-mapping>
bar: localhost:8080/login/auth/showmessage, L6 The session is obtained from the request object.
the user is automatically redirected to the login L7–8 Remember we had inserted an attribute in
page. The request is filtered by this filter class and the session object “LOGIN_DONE” with the value
appropriate action is taken. The same happens in true, as soon as user was authenticated and a new
case of showAuthenticate servlet if user tries to session was created. The purpose was to check for
access it directly (localhost:8080/login/auth/ already logged in user holding valid sessions. If the
showAuthenticate) without logging. The following LOGIN_DONE session attribute is not null, it means
tags have to be inserted in web.xml file. the user is authenticated and holds a valid session.
<filter>
<filter-name>checkLoginFilter</filter-
So the requested resource is invoked. But if it is null,
name> it means the user is not authenticated and the user is
<filter-class>AlreadyLogingFilter</filter- redirected to welcome page (/login).
class>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<welcome-file-list>
<welcome-file>Login.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>authenticate</servlet-name>
588 Programming in Java
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>authenticate</servlet-name>
<url-pattern>/auth/authenticate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>showAuthenticationDetails</servlet-name>
<servlet-class>ShowAuthenticationDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showAuthenticationDetails</servlet-name>
<url-pattern>/auth/showAuthenticate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>showmessage</servlet-name>
<servlet-class>ShowMessage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showmessage</servlet-name>
<url-pattern>/auth/showmessage</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>signout</servlet-name>
<servlet-class>SignOut</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>signout</servlet-name>
<url-pattern>/auth/signout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>noCacheFilter</filter-name>
<filter-class>NoCacheFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>noCacheFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Introduction to Advanced Java 589
<filter>
<filter-name>checkLoginFilter</filter-name>
<filter-class>AlreadyLogingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>checkLoginFilter</filter-name>
<url-pattern>/auth/showmessage</url-pattern>
<url-pattern>/auth/showAuthenticate</url-pattern>
</filter-mapping>
</web-app>
Note jspInit() and jspDestroy() methods can be declared in a JSP page but the _jspService()
method cannot be declared in a JSP page as it is dynamically generated by the JSP container.
If the JSP file has been called for the first time then the JSP container parses the page,
is newer than its class and if yes, the translation of JSP to servlet takes place and again
it is compiled, instantiated, and loaded again; otherwise the most updated instance is
already running.
The generated HTML is displayed on the user’s web browser.
(a) page, as the name suggests, is used to specify attributes for the page, for example, what
classes to be imported for the servlet or what will be the content type for the generated
responses by the servlet and so on. Some of the attributes is provided in Table 16.8.
Table 16.8 Attributes of the Page Directive
Attribute Description
contentType Specifies the character encoding scheme.
Extends Specifies a superclass for the generated servlet.
Specifies the packages or classes to be imported similar to the Java import
Import
statement.
Info Specifies a string that can be extracted using the getServletInfo() method.
isThreadSafe Specifies the thread model for the generated servlet.
Language Defines the programming language to be used in the JSP page.
Session Specifies whether or not the JSP page is participating in a session.
isELIgnored Specifies whether expression language within the JSP page will be ignored or not.
isScriptingEnabled Specifies whether scripting elements are allowed or not.
Introduction to Advanced Java 591
If you want to use Date class in your JSP page you will have to import the java.util package
in your JSP page as shown below:
<%@ page import="java.util.*" %>
(b) include directive is used to add the contents of another file into a JSP page. It is used as
shown below:
<%@ include file="includedirective.html" %>
(c) taglib directive is used while creating user defined tags. It can be used as:
<%@ taglib uri=" " prefix="" >
Expressions
To execute Java expressions like (a+b*c), we make use of JSP expression syntax. The result of
expression is directly embedded in the html page. Expressions are enclosed within <%= … %>.
Note that expressions are not terminated with a semicolon. For example,
The result of 2+22 is <%= (2+2-2) %>.The expression in <% %> is evaluated and answer is
added to the html.
<% ="Introduction to JSP" %>. The string “Introduction to JSP” is added to the html sent to
the client. It is similar to the out.prinln() statement.
Note XML equivalent for the expression can also be used like: <jsp:expression> … </jsp:expression>
Scriptlets
If a number of statements have to be executed, scriptlets is the right place. Note that scriptlets
are enclosed within <% %> delimiters and semicolons are used to terminate statements. For
example,
<%
out.println("This following text is visible through a Scriptlet <br>");
d=new Date();
out.println("<br> The Current Date is: "+d+"<br>");
out.println("<br><b> A Sample for Loop</b><br> ");
for (int i=0;i<5;i++)
out.println("Iteration No :" +i+"<br>");
%>
592 Programming in Java
The above code uses out object which is a predefined object in JSP. println and print are
methods of this out object which are responsible for sending strings to the client. In other words
the strings passed as parameter values in print methods are added to the generated html. Table
16.9 lists all implicit objects.
Table 16.9 Implicit Objects in JSP
Object name Description
request The request received by the server normally a ServletRequest or HttpServletRequest.
response The response generated by the server normally a ServletResponseor or HttpServletResponse.
application Provides information on server version, application level initialization parameters; can be
used for logging; common for all session objects; contains all servlets, JSP, html, and other
resources used in the application.
session Unique object associated with a particular user.
pageContext Object is used to either forward request to other resources or include output of other resources.
Apart from that it is used to maintain attributes at four levels: page level, request level, session
level, and application level.
exception An instance of java.lang.Throwable class; valid only of is ErrorPage attribute of the
page directive is set to true.
page Object is used to refer to the current servlet (similar to this keyword).
config Object is used to access the initialization parameters of the servlet mapping besides the servlet
context and servlet name.
out Object is used to write the contents back to the client.
Note XML equivalent for the scriptlet can also be used like: <jsp:scriptlet> … </jsp:scriptlet>.
Declarations
If you wish to declare any item it should be done here. Note that declarations are enclosed
within <%! %>. A variable can be declared in scriptlet as well. The difference between declaring
a variable in scriptlet and through declarations is that all the scriptlet code goes into the service
method of the JSP page (when it is converted to servlets) and all declarations reside on top of
the service method within the class. Semicolons are allowed while declaring a variable or object
in a JSP page. For example,
<%! Date d;%>
Note JSP container creates a servlet automatically for every JSP page. The expression, scriptlets,
and html found in the JSP page are used by JSP container to create Java code for the
automatically generated _jspService() method of the servlet. This method is analogous to
service() method of the servlets.
Actions
Actions are JSP elements that use, create or modify other objects and they follow strict XML
syntax. Table 16.10 lists the JSP actions.
Introduction to Advanced Java 593
Note We will discuss some actions later when we discuss Java beans.
Let us put all that we have discussed into practice and create a simple JSP page. We will call it
JspElements.jsp. We will be creating a html table to display directives, expressions, scriptlets,
declarations, actions, and important implicit objects in a single JSP page, and try to show how
most of them can be used in a JSP page.
Tomcat 7.0
bin
cont
lib
webapps
login
WEB-INF
JspElements.jsp
includedirective.html
</td>
<td><h3> Actions </h3></td>
<td><h3> Some Important Implicit Objects </h3></td></tr>
<tr>
<td>There are three types of directives:<br><em>page, include and taglib.</
em><br>The following text is generated using a include directive. <br>
<em><%@ include file="includedirective.html" %></em>
<%@ page import="java.util.*" %>
</td>
<td> The result of 2+2-2 is : <%= (2+2-2) %><br>
<%= "Introduction to JSP Elements" %>
</td>
<td> if a number of statements have to be executed, scriptlets is the
right place. <br>The following scriptlet includes a print statement,
statement to instantiate a Date object and a for loop.
<!-- Starting of scriptlet -->
<%
out.println("This following text is visible through a Scriptlet<br>");
d=new Date();
out.println("<br> The Current Date is: "+d+"<br>");
out.println("<br><b> A Sample for Loop</b><br> ");
for (int i=0;i<5;i++)
out.println("Iteration No :" +i+"<br>");
%>
<!-- Ending of Scriptlet -->
</td>
<td>
If you wish to declare any item it should be done here.<br> we are declaring a Date
here which is instantiated in a scriptlet.
<%!Date d;%>
</td>
<td>
<jsp:useBean><br>
Introduction to Advanced Java 595
<jsp:include><br>
<jsp:forward><br>
<jsp:getProperty> <br>
<jsp:setProperty><br>
</td>
<td>
request<br>
response<br>
session<br>
application<br>
out<br>
</td>
</tr>
</table>
<h5> NOTE: </h5>
<em>
JSP container creates a servlet automatically for everyJSP page. The expression,
scriptlets and html found in the JSPpage is used by JSP container to create the
Java code for the automatically generated _jspService() method of the servlet. This
method is analogous to service() method of the servlets
</em>
</body>
</Html>
Output
Explanation
The above example clearly shows Java code being file is not html. The meaning of all tags used in the
embedded in html file. Note that the extension of example is shown in Table 16.11.
596 Programming in Java
h1, h2, h3, h4, h5, h6 Used for headings. h1 is the biggest and h6 is the smallest.
<%@include file = "includedirective. JSP include directive is used to include the contents of
html" %> includedirective.html file within the JspElements.jsp
page.
<%@ page import = "java.util.*" %> JSP page directive is used to import util package.
JSP expression is used to evaluate the expression and send the
<%= (2+2-2) %><br>
result to the client embedded in the generated html.
JSP expression is used to send the string to the client embedded
<%= "Introduction to JSP Elements" %>
in the generated html.
<% JSP scriptlet is used to depict a number of statement can be
out.println("This following text is embedded in html. Predefined object out is used in this scriptlet
visible through a Scriptlet<br>"); to write strings to the client. The output of all these statement is
d=new Date(); embedded in the generated html sent to client.
out.println("<br> The Current Date is:
"+d+"<br>");
out.println("<br><b> A Sample for
Loop</b><br> ");
for (int i=0;i<5;i++)
out.println("Iteration No :"
+i+"<br>"); %>
Introduction to Advanced Java 597
Properties should be modified and accessed through setter (setXXX) and getter
Supporting customization thus allowing users to alter the appearance and behavior of
a bean.
Supporting events which allow beans to fire events and inform application builder tools
A special case is for boolean properties whose type is boolean. In such case the getter/accessor
method makes use of is instead of get.
public boolean isAcceptable()
{
return acceptable;
}
Indexed Properties
An indexed property is one which accepts an array of values. Suppose the bean contains an integer
array to hold the marks scored named marks, the getter and setter methods for this property will be
598 Programming in Java
Beans must also provide methods to get and set specific elements of the array. For example,
public int getMarks(int index) // gets specific element at index
{
return marks[index];
}
Bound Properties
A bound property is one which is bound to the listener and this listener is notified whenever
the value of this field changes. PropertyChangeListener and PropertyChangeEvent of
the java.beans package are used for this purpose. The bean must add the methods
addPropertyChangeListener() and removePropertyChangeListener() for managing the bean’s
listeners. As soon as the bound property is changed, the bean sends a PropertyChangeEvent to
its registered listeners. java.beans package includes a utility class PropertyChangeSupport to
keeps track of property listeners. It also includes a method that fires PropertyChangeEvent to all
registered listeners. An instance of this class is declared as a member field of the bean and all
such task are delegated to it. Let us see how this is done.
{
int oldLength = length;
/* And fire a property change event to the registered listener. If the old and new
value is same, no event is fired.
public void firePropertyChange(String propertyName,boolean oldValue,
boolean newValue) */
pcs.firePropertyChange("length",oldLength,l);
}
Constrained Properties
A constrained property is a special kind of bound property. In this case, the listeners are consulted
prior to changing the constrained property and if there is no objection from any of the listeners,
changes are made. But if any one of the associated listeners veto’s the change, the property remains
unchanged. VetoableChangeListener and VetoableChangeSupport of the java.beans package
are used for this purpose. Let us take the previous example and add VetoableChangeSupport and
VetoableChangeListener to it.
import java.beans.*;
public class DemoBean {
private int length = 10;
private Pr opertyChangeSupport pcs = new PropertyChangeSupport(this);
return length;
}
This method apprises the listeners about the change in the property’s value.
Any of the registered listeners can throw a PropertyVetoException to veto the
update. In such a case the method passes an "undo" PropertyChangeEvent. This
will revert back the old value to all listeners that confirmed this update and
re-throws the PropertyVetoException. If the old and new values are same and
non-null, No event is fired */
vcs.fireVetoableChange("length", oldLength, l);
length = l;
pcs.firePropertyChange("length",oldLength, l);
}
public void addPropertyChangeListener(PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
This action instantiates an object of the class specified in the class attribute and bind it with
the name specified in the id attribute. So, for example, if we want to use a bean created by the
name CalculateBean.java residing in the beans directory, the following JSP action can be used:
<jsp:useBean id="calc" class="beans.CalculateBean" >
The name calc specified in the id attribute is bound with this bean. It will be used further to
access the bean class. It can be considered as equivalent to the following scriptlet code:
<% beans.CalculateBean calc = new beans.CalculateBean; %>
Note All classes should be part of a package in order to be accessible in other classes. Classes
within the default package are invisible to classes of the same package. So whenever you
create bean classes, make sure it is part of some package.
package beans;
public class CalculateBean {
// ...
}
After placing the bean class (rather all classes) in a package, recompile it and place it in
/WEB-INF/classes/beans/CalculateBean.class
or its equivalent
<%= calc.getName() %>
or
<% calc.setName("Peter"); %> // scriptlet code
The property “name”, is of type String whereas there may be other attributes in a bean that
may be numeric in nature. But, the value that is passed will always be a String, (value = "") so
conversion from string to other types will be required. This will prove to be a tedious approach
while converting from one type to other. JSP provides a simple solution of letting the container
automatically handle all conversions. You just need to specify
<jsp:useBean id = "calc" class = "beans.CalculateBean" />
<jsp:setProperty name = "calc" property = "*"/>
Note Moreover, the above setting is also used to synchronize html form elements (input fields) with
Java Bean. In other words, it is used for form synchronization. Suppose we have an HTML
form which accepts some data from the user (e.g., user id and password) and we want to pass
this data to JSP. Apart from JSP, we also have a Java Bean that performs the reading and
writing to and from the database based on the data which user has entered. Our JSP code
will first read the HTML form data from the request object and then set all the parameters in
the Java bean using the jsp:setProperty tag. This is perfectly right but certainly repetitive.
Form synchronization lets JSP synchronize HTML forms element data directly with a Java
bean thus alleviating much of this repetitive coding. Each Html form element will synchronize
with a property of a Java Bean that has the exactly the same name (case-sensitive) as that
of form element. Their values will be directly passed to the bean without worrying about the
type conversions.
Hello <br>
<jsp:useBean id="calc" class="beans.CalculateBean" >
After Instantiating Bean <br>
<jsp:setProperty name="calc" property="*" />
<jsp:setProperty name="calc" property="name" value="sachin" />
After Setting property: name <br>
<jsp:setProperty name="calc" property="var1" value="10" />
After Setting property: variable 1 <br>
<jsp:setProperty name="calc" property="var2" value="10" />
After Setting property: variable 2 <br>
Name: <jsp:getProperty name="calc" property="name" /><br>
Variable 1: <jsp:getProperty name="calc" property="var1" /><br>
Variable 2: <jsp:getProperty name="calc" property="var2" /><br>
<%= "Result: "+ calc.sum() %>
</jsp:useBean>
</body>
</Html>
/*getter methods*/
public int getVar1()
{
return var1;
}
public int getVar2()
{
return var2;
}
public String getName()
{
return name;
}
/*setter methods*/
604 Programming in Java
Output
webapps
login
WEB-INF
classes
beans
CalculateBean.class
CalculateBean.java
lib
JavaBeans.jsp
JspElements.jsp
includedirective.html
v stands for verbose output on standard output. All files included in Jar will be shown
on the console.
f option stands for file to indicate that the output will go into a file rather than to the
standard output.
m stands for specifying manifest file to be added to the Jar. If the option is not specified,
.jar extension.
File names to be a part of Jar file can be specified separated by single white spaces.
If a directory is specified the contents of that directories are added to the Jar archive
recursively.
606 Programming in Java
This command will create a compressed Jar file and place it in the current directory. For example,
Fig. 16.26 shows the creation of Calculator.jar.
As you can see above, the name of the directory, i.e., beans is mentioned after the Jar file
name. This directory contains CalculateBean.class which we want to include in the Jar. The
verbose mode is “on” so all operations are shown on the console.
Note If you want to make use of this JAR instead of the beans/CalculateBean.class (placed in
/WEB-INF/classes/beans/CalculateBean.class) in the JavaBeans.jsp page example, place
the Calculator.jar in the following folder: webapps/login/WEB-INF/lib/Calculator.jar and
remove the beans folder from the /WEB-INF/classes directory. Now you can use the same
JavaBeans.jsp page as it is.
t option indicates that you want to view the contents of the Jar file.
f option signifies that the Jar file whose contents are to be viewed is specified.
Figure 16.27 shows both creation and viewing of the Jar files together.
The manifest’s entries are in “header : value” pairs. The first line indicates that manifest file
conforms to version 1.0 of the manifest specification and is created by the 1.7.0_09 version of
the JDK.
Modifying a Manifest File
The m command-line option is used to add custom information to the manifest during creation
of a Jar file. In order to modify the manifest, you will have to create a text file first containing
the information that you wish to add to the manifest. The general syntax for the command is
as follows:
jar cfm jar-file manifest-file input-file(s)
Note Make sure you add a carriage return or new line at the end of manifest file otherwise the last
statement will not be passed. As well as, the order of m and f options and their arguments
must match exactly. If options are -fm then the JAR-file-name must appear before the mani-
fest file and if –mf options are specified, the situations will be reverse. For example,
For example, Fig. 16.28 shows how to add manifest file to the jar. Also note the order of options
and the arguments. Figure. 16.29 shows a sample manifest.txt file.
608 Programming in Java
classname is the name of the class which contains the main method (public static void
main(Stringargs[])) as the execution of any Java applications begin from main method. Once
this manifest is added to the JAR, the application bundled in JAR can be executed as
java -jar JAR-name
Note The ‘e’ option (e stands for entry point) can also be used to create or override the
manifest’s Main-Class header. It is used to specify the applications starting point without
editing or creating the manifest file. For example, this command creates x.jar where the Main-
Class attribute value in the manifest is set to MyMain:
If the starting point or main class is in a package, the following command may be invoked. For
example, App is the package which contains MyMain.class.
jar cfe x.jar App.MyMain App/MyMain.class
anywhere by any one. RMI helps in accomplishing this by allowing objects running on one
machine to be accessed by the clients running in different machines.
Remote method invocation (RMI) is Java’s implementation of remote procedure call (RPC)
for distributed computing. It is based on client/server concept. RPC is, as the name suggests,
a client invoking a procedure on the remote server by passing arguments and expecting some
return. RMI is a Java client (running in one JVM) invoking a procedure on a remote Java server
(running in same/different JVM). RMI is not language-independent, whereas CORBA (common
object request broker architecture) is language-independent. Language independency means a
Java program can communicate with a program written in any language like C or C++. The low
level details of communication are hidden from the programmer. Actually, a protocol named JRMP
(Java Remote Method Protocol) that works over TCP/IP takes care of the communication between
client and server. Sockets are also used for communication, as they are used for transferring and
receiving data, whereas RMI transfers control by invoking procedure on the server.
16.8.1 RMI Networking Model
RMI client/server applications are used over TCP/IP networking model. In TCP/IP, it is the
application layer’s responsibility to deal with presentation as well as session layer issues. So
the RMI provides the functionality for these layers, as shown in Fig. 16.30. The presentation
layer’s functionality at client and server is handled by stub and skeleton, respectively. Remote
reference layer (RRL) handles the session layer functionality by managing the session among
client and server.
Stub and Skeleton
Stub is a client-side proxy class, whereas skeleton is a server-side proxy class generated by the
special compiler, rmic (rmicompiler). Both these classes are generated from the server (.class)
class after it has been compiled by the rmic. (The newer version of JRMP protocol has made
skeleton class obsolete and now it is not generated by the rmic. The functionality of skeleton is
handled by it automatically. For learning purpose, we should know the functions performed by
both Stub and Skeleton.)
Actually the term proxy has been used because the client talks to stub, assuming it to be the
server, whilst its purpose is to pass the client’s request to the server and the server’s response to
the client (vice versa for skeleton). Apart from this, the other functionalities performed by stubs
are
Marshalling arguments and unmarshalling return values.
Parameter marshalling and unmarshalling deals with how parameters are sent to the server
and responses are returned to the client. Actually networks are heterogeneous in nature.
By heterogeneous, we mean machines of different make, different architecture, and different
protocols are used in a network. For example, a machine ‘A’ which stores integers in one’s
compliment form and character in ASCII code wants to communicate with a machine ‘B’ which
610 Programming in Java
uses 2’s compliment for integers and EBCDIC code for characters. If communication is allowed
to proceed without any conversion in between, then whatever A transmits can have some other
meaning when it is interpreted by B. For the communication to be unambiguous, the stubs at the
client marshal the parameters, i.e., convert the parameters into a network byte order (standard
conversion order used on networks) and at the server, the skeletons unmarshal the parameters,
i.e., convert the network byte order into host-specific order (which is the interpretation used on
the server).
Note For testing the RMI application, we will run client/server and the registry on the local machine.,
We have created separate directories for client and server, namely rmiclient and rmiserver,
respectively.
Introduction to Advanced Java 611
Creating an Interface Example 16.10 shows an interface which contains the definitions of the
methods that can be invoked from client remotely. The clients are provided with these interfaces
to let them know about the names of the methods, their return types, and their parameters.
The mandatory requirement for such interfaces is that the interface should be a sub-interface
of Remote interface. Remote interface is a part of java.rmi package, so it has to be imported.
This interface is empty and is used to denote that the methods of this interface can be invoked
remotely. Also note that all the methods in the interface should specify an exception to be thrown,
i.e., RemoteException as shown above. The interface has to be public.
Server Class
The Server class should implement the Calculation interface defined above. The Server class
is shown in Example 16.11.
L14 Naming.rebind("rmi://localhost/Calculator",s);
L15 System.out.println("Object Registered");
}
catch(Exception e)
{
System.out.println(e);
}
}}
Explanation
L2 For creating server, the package java.rmi. L6–7 Method has been overridden; remainder
server has to be imported. (double a, double b). This methods turns the
L3 The Server class should inherit the Unicas- remainder of a/b.
tRemoteObject class to create itself an RMI server. L8–9 Method has been overridden; cube(double
This Server class also inherits the Calculation a).This methods returns a * a * a.
interface and provides the implementation of the L10 main() method defined.
methods (remotely available) in the interface. L11 try block defined within main().
L4–5 Constructor for the class has been defined L12 Object of Server class is created.
and the superclass constructor has been called. The L14 A static method rebind of the Naming class is
superclass constructor throws RemoteException, used to bind the server object to the registry services
so the constructor of S e r v e r class throws a with a name. The first argument is the URL and the
RemoteException. second argument is the server object to be bound.
The URL has the following syntax:
This method may throw a RemoteException as well as a MalformedURLException. Apart from this,
the Naming class provides two other methods: bind and unbind.
The static void bind(String name, Remote obj) method binds the server object with a name
into the registry. If the name is already bound, then it throws an AlreadyBoundException. This is
different from rebind method which overwrites the association of name into the registry.
The static voidunbind(String name) removes the association of name in the registry service.
RMI Registry RMI registry helps to locate a remote object whose methods it wishes to invoke.
RMI registry is a name service which keeps an association of simple names to their corresponding
remote objects. It runs on the same machine as that of RMI server.
Every object that wishes to publicize its methods must register itself by a name on the registry
service. Clients look up the registered name in the registry service and get a reference to the
remote object in return. Then use that reference to invoke the remote methods of the server.
Introduction to Advanced Java 613
Stub The stub class is generated by a special rmicompiler (rmic). The Server class is first
compiled and then, the rmic is used on the compiled Server class. Do not mention server. class
while using rmic for generating stub class. The stub class generated has the following name:
Server_Stub.class. In general, its name is <name of the Server Class>_Stub.class. This class
has to be provided to the client. As we have kept the client in a directory ‘rmiclient’, this stub
has to be copied into the client’s directory.
Client The client is created in a directory ‘rmiclient’. The interface as well as the stub generated
from the Server class must be included in this directory.
The method Naming.lookup (String name) is used to lookup the named service. This
method returns a Remote object. If the named service could not be found, then it throws
NotBoundException. If Registry could not be contacted, a RemoteException occurs. If the URL
argument is not properly formatted, a MalformedURLException results.
Executing RMI Server and Client
Registry, server, and client are run in three separate DOS shells. The outputs at the client and
server DOS shells are shown below:
C:\javabook\programs\CHAP15~1\rmiserver>java Server
Object created
Object Registered
related logic should be independent of the business logic that relies on the data. Figure 16.31
would give a clear understanding of where EJB fits in the entire scenario and how servlets and
JSP would interact with EJB resources. The servlets and JSP use Java naming and directory
interface to look up EJB.
16.9.1 Types of EJB
There are three types of EJB: entity beans, session beans, and message driven beans as shown
in Fig. 16.32.
Entity Bean
An entity bean models real world objects/entities. These entities represent business concepts
that include a customer or a product. Entity bean is used to manage a collection of data (also
known as persistent data) which is retrieved from a database. An entity bean may insert, update
or delete data from the database. This persistent data may be managed in two ways resulting
in two types of entity beans: BMP (Bean Managed Persistence) and CMP (Container Managed
Persistence). An entity bean must implement the javax.ejb.EntityBean interface. Entity beans,
like session beans, are also transactional in nature and they can be shared among different clients.
In container-managed persistence entity beans, persistence is automatically managed by the EJB
container. The bean developer instead of coding the persistence logic relies on the deployment
descriptor to specify attributes whose persistence needs to be managed by the container. The
container synchronizes the state of the bean with the database. In other words, it maps the
attributes of the bean to the database thus performing the insert, update, and delete operations
automatically.
In the bean-managed persistence entity beans, the developer codes the logic to manipulate the
database. All interactions with the database take place according to the directions given by the
EJB container. The EJB container informs the entity bean when to perform an operation: when
to insert, update, or delete its data from the database.
Introduction to Advanced Java 615
Session Beans
Session beans contain business logic and are used for managing processes or tasks. A session
bean provides service to the client and it exists for the entire client server session. Unlike entity
beans which represent an entity into the database, a session bean does not represent anything into
the database. However, it can access the database. An entity bean has persistent state whereas
a session bean does not have a persistent state as it is used for modeling interactions between
clients and server. Session beans are aware about transactions. Instances of session beans are
not shared among clients. Unlike entity beans, session beans have a client-dependent identity.
A session beans has to implement the javax.ejb.SessionBean interface.
Session beans, however, can be either stateful or stateless. A stateful session bean maintains
or retains state across interactions between client and server. A stateful bean is able to retain
state between successive calls from a client to a session bean. Therefore, a call can access data
from the previous method call. This state is not written to a database, so they are not persistent
but the session beans can communicate with the databases.
Stateless session beans are those that do not maintain any state between client and the session
bean. A bean can be specified as stateful or stateless in the bean’s deployment descriptor.
Message-driven Beans
Message-driven beans can be considered as a special kind of stateless session bean which can
receive messages from Java messaging service (JMS) and perform actions. They implement
business logic in response to JMS messages. MDB was introduced in EJB 2.0 specifications
and can be called only implicitly by sending messages to it. Every message-driven bean will
have to inherit the javax.ejb.MessageDrivenBean interface. Unlike the session and entity beans,
message-driven beans are asynchronous in nature. The clients in session and entity beans are
blocked (i.e., synchronous nature) until the container completes the execution of the bean
methods. During this execution, the (session/entity) bean is unable to accept any messages from
any messaging service. And hence EJB introduced the message-driven bean. A client needs to use
a messaging service like JMS in order to send messages to the MDB. The MDB are registered
against JMS destinations. When the messaging service receives the message for a destination,
the EJB container invokes MDB associated with that destination. Hence, it is a local object and
does not require home or remote interfaces.
16.9.2 EJB Architecture
Every human behaves differently at different places. For example, the way you behave/interact/
roam/sit in your home will be different from the way you behave or interact in your office.
So simply you have two interfaces one for your home and other for outsider (Remote). EJB
architecture also specifies two kinds of interfaces for session and entity beans: Home interface
(javax.ejb.EJBHome) and Remote interface (javax.ejb.EJBObject). The Home interface contains
methods for creating, finding, and destroying remote objects. The Remote interface contains
business methods that are exposed to the clients. The EJB container manages interaction between
the EJB and other components using the Home and the Remote interface. The local clients residing
on the same JVM as that of EJB use the Home interface for interacting with the EJB. Remote
616 Programming in Java
clients use the Remote interface to interact with the EJB through an application which is RMI and
IIOP complaint. EJB 2.0 specifications added local (javax.ejb.EJBLocalObject) and Localhome
(javax.ejb.EJBLocalHome)interfaces in addition to Remote and Home interface. So according to
EJB 2.0, Local and LocalHome interface is used by local client, i.e., clients on the same JVM
and Remote interface for clients outside the JVM. What Home interface does for a remote client,
LocalHome does the same for a local client and likewise for local and remote interfaces.
As you can see in Fig. 16.33(b), different versions of JBoss are displayed. You can choose a
version and proceed further. If the Demo EJB bean is created then it may also ask you to deploy
that bean after this step or else it can be done later as well.
First of all, create an EJB Project in the project explorer window like DemoHello shown in
Fig. 16.34. (Do not forget to specify the EJB module version while creating EJB Project. We
are using version 2.0). Before writing our interfaces and bean classes we have to add libraries to
our EJB project. Right click on the DemoHello EJB project and click on BuildPath Configure
Build Path. In the Libraries Tab, click on Add Library, choose server runtime and add the server
(i.e., JBoss in our case) you had earlier added to Eclipse.
Fig. 16.34(a)
618 Programming in Java
Fig. 16.34(b)
Fig. 16.34(c)
Introduction to Advanced Java 619
Fig. 16.34(d)
Now we will create the Remote interface for our first EJB to it. Right click on ejbModule
package that was created in the DemoHello folder in Project Explorer window, Go to New and
click on Interface. This interface will define the business methods that clients can access. As you
can see, we are creating a Hello Enterprise bean. The method that client can call is defined here,
i.e., sayHello(). This interface should inherit the javax.ejb.EJBObject, which in turn inherits
the java.rmi.Remote. Figure 16.35 shows the snapshot of DemoRemote.java interface.
Let us create the Home interface. This interface is responsible for defining the create method. This
interface should inherit the javax.ejb.EJBHome, which in turn inherits the java.rmi.Remote. Figure
16.36 shows a snapshot of the DemoHelloHome.java. The EJB container provides implementation
of the Home interface and creates Home objects for the bean. The references to these Home objects
can be obtained by the clients through JNDI. The client can send request to the home object to
create an EJB object (which inherits the Remote interface) and invoke the business methods. In
order to invoke the business methods, EJB object delegates the request to the enterprise bean
and the response is sent back to the client.
As we will be accessing the bean remotely only, we do not require the local and localhome
interface but for your reference we have provided the code for these interfaces.
Local interface for the EJB is defined (similar to the DemoRemote interface). It inherits the
EJBLocalObject interface.
package com.ejb;
import javax.ejb.EJBLocalObject;
public interface DemoHelloLocal extends EJBLocalObject
{
public String sayHello();
}
LocalHome interface for the EJB (similar to the DemoHelloHome interface). The only thing that
changes is the return type of the sayHello method and it inherits the EJBLocalHome interface.
package com.ejb;
import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;
public interface DemoHelloLocalHome extends EJBLocalHome
{
public DemoHelloLocal create() throws CreateException;
}
The Bean Class is defined to implement the bean’s business methods specified in the remote
interface apart from some other methods according to the bean that we are creating, i.e., either
session or entity bean. As we are creating a session bean, this class should inherit the javax.
ejb.SessionBean interface. The following snapshot shows the DemoBean.java. The methods
Introduction to Advanced Java 621
that have been overridden are: ejbCreate(), ejbActivate(), ejbPassivate(), ejbRemove(), and
setSessionContext().Apart from these, the sayHello() method defined in the DemoRemote
interface is also overridden and implemented here. When the client calls the sayHello(), it is
this method that is executed and the contents are returned to the client. The following snapshot
in Fig. 16.37 shows the DemoBean.java class. A short description of the session bean method is
shown in Table 16.12.
In order to invoke EJB, we need a Remote client. This Remote client uses the JNDI, locate
the beans on the net. It provides a uniform API for performing naming and directory services.
The following snapshot in Fig. 16.38 shows the TestClient.java. Note that it has been created
in a separate directory. This client makes use of javax.naming.InitialContext class (inherits
the context interface) and it serves as a starting point for resolving names. This class is used by
the client for looking up the enterprise bean. The constructor of this class accepts Hashtable of
environmental properties. So a Hashtable object is instantiated and properties are put in it using
the put method. javax.naming.Context is an interface which represent naming context. Three
properties are set as shown in Table 16.13.
Table 16.12 Session Bean Method
ejbCreate
Used for initializing your session.
ejbPassivate
Called when the bean is swapped to disk.
ejbActivate
Called when the bean is swapped back from disk.
ejbRemove
Called before a bean is removed from memory.
setSessionContext
A session context is associated with a bean which it can
use to query about its state.
622 Programming in Java
Figure 16.40 shows another descriptor file, i.e., Jboss.xml which is specific to the container.
Please note that the ejb-name in the ejb-jar.xml and jboss.xml must match.
Go to TestClient.java and right click on it and select Run As Java application. Go to Console
tab besides the Server tab, to see the output (see Figs 16.43 and 16.44).
624 Programming in Java
SUMMARY
Core Java deals with basic programming constructs manipulating data within them. Java RMI is the solution
and the classes needed for creating a standalone for RPC, where a Java program on a remote machine
application. Advanced Java deals with classes that can be called from a Java client program. Basically,
are used for creating Internet-based server-side RMI helps in distributed computing. A Java server page
applications. In this chapter, we have learnt about some is an easy solution to generate dynamic contents for
of the concepts of advanced Java such as servlets, the client. Java beans helps in creation of reusable
JSP, JDBC, RMI, Java beans, and enterprise Java software components which can be used by server
beans. Servlets are used for generating responses side technologies. EJB is a server side distributed
for clients, based on the requests received. JDBC component architecture which is used for creating
API deals with a variety of databases for storing and enterprise wide server side applications.
EXERCISES
Objective Questions
1. Which packages contain the JDBC API? (c) CallableStatement
(a) java.jdbc (b) java.sql (d) Connection
(c) javax.jdbc (d) javax.sql 4. Which of the following is used for calling stored
2. Which class is used to establish a database procedures?
connection? (a) Statement
(a) Class (b) DriverManager (b) PreparedStatement
(c) Statement (d) ResultSet (c) CallableStatement
(d) Connection
3. Which of the following is a precompiled state-
ment? 5. Which of the following methods return a connec-
(a) Statement tion object?
(b) PreparedStatement (a) getConnection()
(b) getConnection(String databaseURL)
626 Programming in Java
Review Questions
1. What is the difference between Statement , 7. Explain all the steps used for establishing a
PreparedStatement, and CallableStatement? connection to a database.
2. Explain the different types of JDBC drivers. 8. Explain how JSP is similar or different from
3. Explain the lifecycle of a servlet. servlets.
4. Differentiate get and post requests. 9. What is Jar file? How are they created?
5. Explain the role of registry services in RMI. 10. What is a Java Bean? Explain the various
properties of a bean.
6. Explain the following:
(a) Http redirects 11. Explain the role of EJB with its different types.
(b) Cookie 12. Explain the role of manifest file in a jar file.
(c) Stubs and skeletons 13. What are the JDBC transaction? Explain what
(d) ResultSet are the different ways of creating transactions
(e) ResultSet metadata in JDBC.
14. What are scrollable ResultSets?
Programming Exercises
1. Write a program to connect to a database and 4. Write a servlet that automatically redirects the
retrieve all the data. The database type (Access client to another page.
or Oracle), driver name, database name, DSN, 5. Write a servlet that ensures authenticated users
etc. have to be fed by the user. have access to important pages. The user name
2. Write a servlet program that fetches all the and password should be stored in a database
data from client and stores it in a database and whenever a user tries to access the servlet,
successfully. first he/she is authenticated.
3. Write a remote calculator program that adds, 6. Write a servlet to store the user’s browsing
subtracts, multiplies, divides, and gives the preferences like color in a cookie and should be
remainder as well. These operations should be displayed in that color.
invoked remotely by a client method. 7. Rewrite the Programming Exercise 5 by using
JSP instead of servlets.
Introduction to Advanced Java 627
8. Create a jar file which will store beans. This bean 9. Create a GreatUser EJB which will greet the uses
should be able to read all form elements of HTML based on time ‘for example’, Good Morning John,
page. (e.g. personal details of a user) and store Good AfterNoon John or Good Evening John,
them into a database, through JSP. etc.
Programming Exercises
1. Write a program to connect to a database and 4. Write a servlet that automatically redirects the
retrieve all the data. The database type (Access client to another page.
or Oracle), driver name, database name, DSN, 5. Write a servlet that ensures authenticated users
etc. have to be fed by the user. have access to important pages. The user name
2. Write a servlet program that fetches all the and password should be stored in a database
data from client and stores it in a database and whenever a user tries to access the servlet,
successfully.
Review Questions ¿UVWKHVKHLVDXWKHQWLFDWHG
1. What is the difference between Statement , 6. Explain the following:
PreparedStatement, and CallableStatement? (a) Http Redirects
2. Explain the different types of JDBC drivers. (b) Cookie
3. Explain the lifecycle of a Servlet. (c) Stubs and skeletons
(d) ResultSet
4. Differentiate get and post requests.
(e) ResultSet metadata
5. Explain the role of registry services in RMI.
7. Explain all the steps used for establishing a
Objective Questions connection to a database.
1. Which packages contain the JDBC API? 4. Which of the following is used for calling stored
A variety of end-chapter (a) java.jdbc (b) java.sql procedures?
(c) javax.jdbc (d) javax.sql (a) Statement
exercises that include 2. Which class is used to establish a database (b) PreparedStatement
(c) CallableStatement
both subjective as well connection?
(d) Connection
(a) Class (b) DriverManager
as objective questions (c) Statement (d) ResultSet 5. Which of the following methods return a Connec-
ti bj t?
APPENDIX A: Lab Manual—Java Lab Exercises
Output
C:\javabook\LabSyllabi> java GreetUser John
Hello, John How are you today?
Output
C:\javabook\programs\LabSyllabi > java Test
Addition of two byte variables is an int, Result= 5
Character at Ascii value: 66 is B
suffix F or f for a float variable 4.28
double variable: 1.0E308
Output
C:\javabook\programs\LabSyllabi > java Distinct
No of distinct value = 2
for(int j=7;j>i;j--)
System.out.print(" ");
/* ASCII value of A is taken and based value of i the loop
is executed to print the alphabets. First time the only A will
be printed as the value of i is 0. Second time AB will
be printed by this loop and soon. */
for(k=65;k<=65+i;k++)
System.out.print((char)(k));
System.out.println();
}
}
}
630 Appendix A: Lab Manual—Java Lab Exercises
Output
If the last for loop is removed then the following output is displayed:
{z = 1;}
else if(b > 17 && b < 30)
{z = 2;}
break;
case 3:
if(b < 20)
{z = 2;}
else if(b > 19 && b < 31)
{z = 3;}
break;
case 4:
if(b < 20)
{z = 3;}
else if(b > 19 && b < 30)
{z = 4;}
break;
case 5:
if(b < 21)
{z = 4;}
else if(b > 20 && b < 31)
{z = 5;}
break;
case 6:
if(b < 21)
{z = 5;}
else if(b > 20 && b < 30)
{z = 6;}
break;
case 7:
if(b < 23)
{z = 6;}
else if(b > 22 && b < 31)
{z = 7;}
break;
case 8:
if(b < 23)
{z = 7;}
else if(b > 22 && b < 31)
{z = 8;}
break;
case 9:
if(b < 23)
{z = 8;}
else if(b > 22 && b < 30)
{z = 9;}
break;
case 10:
if(b < 23)
{z = 9;}
else if(b > 22 && b < 31)
{z = 10;}
break;
632 Appendix A: Lab Manual—Java Lab Exercises
case 11:
if(b < 22)
{z = 10;}
else if(b > 21 && b < 30)
{z = 11;}
break;
case 12:
if(b < 22)
{z = 11;}
else if(b > 21 && b < 31)
{z = 0;}
break;
default :
System.out.println("Month is not valid");
}
if((z >= 0) && (z <= 11))
System.out.println("Zodiac sign is: " + z1[z]);
else
System.out.println("Date is not valid");
}
}
Output
C:\LABSYL~1 > java Zodiac 6 7
Zodiac sign is: Gemini
{
return Length;
}
float getWidth()
{
return Width;
}
float perimeter()
{
float p;
p = 2*(getLength() + getWidth());
return p;
}
float area()
{
float p;
p = getLength() * getWidth();
return p;
}
}
class Cal
{
public static void main(String args[])
{
Rectangle rr = new Rectangle();
rr.setLength(15);
rr.setWidth(15);
System.out.println("Perimeter is:" + rr.perimeter());
System.out.println("Area is:" + rr.area());
}
}
Output
C:\LabSyllabi > java RectangleTest
Perimeter is:60.0
Area is:225.0
/*Copy constructor*/
public CopyConDemo(CopyConDemo c) {
this(c.getM(), c.getN());
}
634 Appendix A: Lab Manual—Java Lab Exercises
int getM() {
return m;
}
String getN() {
return n;
}
Output
C:\javabook\programs\LabSyllabi > java CopyConDemo
Original Object m = 12 n = Original
First Copy m = 12 n = First Copy
Output
C:\javabook\programs\LabSyllabi > java MOverload
addition of two numbers = 11
addition of three numbers = 18.5
9. Implementing Inheritance
(a) Single inheritance
class MotorVehicle
{
String modelName;
int modelNumber;
float modelPrice;
MotorVehicle(String mname, int mnumber, float mprice)
{
modelName = mname;
modelNumber = mnumber;
modelPrice = mprice;
}
void display()
{
System.out.println("Model Name is : " + modelName);
System.out.println("Model Number is : " + modelNumber);
System.out.println("Model Price is : " + modelPrice);
}
}
class Car extends MotorVehicle
{
int discountRate;
Car(String mname, int mnumber, float mprice, int dr)
{
super(mname,mnumber,mprice);
discountRate = dr;
}
//implementing Polymorphism: Method Overriding
void display()
{
super.display();
System.out.println("The discount rate is :" + discountRate);
}
void discount()
{
float discount = modelPrice * discountRate/100;
float priceAfterDiscount = modelPrice - discount;
System.out.println("The discount is : " + discount);
System.out.println("The Price after discount rate is : " + priceAfterDiscount);
}
public static void main(String args[])
{
Car c = new Car("Mercedes E series",2000, 3200000f, 10);
c.display();
c.discount();
}
}
636 Appendix A: Lab Manual—Java Lab Exercises
Output
C:\javabook\programs\LabSyllabi > java Car
Model Name is : Mercedes E series
Model Number is : 2000
Model Price is : 32000 00.0
The discount rate is : 10
The discount is : 320000.0
The Price after discount rate is : 2880000.0
class B extends A
{
B(int n)
{
super(n);
}
void show()
{
super.show();
System.out.println("class B is a subclass of A");
}
}
class C extends B
{
C(int n)
{
super(n);
}
void show()
{
super.show();
System.out.println("class C is a subclass of B");
}
super(n);
}
void show()
{
super.show();
System.out.println("final class D is a subclass of C");
}
}
class MultiLevelInheritanceTest
{
public static void main(String args[])
{
D d1 = new D(12);
d1.show();
}
}
Output
C:\javabook\programs\LabSyllabi > java MultiLevelInheritanceTest
class A variable n = 12
class B is a subclass of A
class C is a subclass of B
final class D is a subclass of C
Output
C:\javabook\programs\LabSyllabi > java ShapeDemo
The number of sides in a Trapezoid is four
The number of sides in a Traingle is three
The number of sides in a Hexagon is six
Output
C:\javabook\programs\LabSyllabi > java CalculatorDemo
ADD of two no is: 20
SUB of two no is: -9
MULTIPLICATION of two no is: 15
Divide of two no is: 5
REMAINDER of two no is: 1
class Test
{
public static void main(String args[])
{
ComparableTest t1 = new ComparableTest(12);
ComparableTest t2 = new ComparableTest(10);
System.out.println("First object: " + t1);
System.out.println("Second object: " + t2);
if((t1.compareTo(t2)) > 0)
System.out.println("First object is greater than second object");
else if((t1.compareTo(t2)) < 0)
System.out.println("second object is greater than first object");
else
System.out.println("both are equal");
}
}
Output
C:\javabook\programs\LabSyllabi > java Test
First object: Object: 12
Second object: Object: 10
First object is greater than second object
640 Appendix A: Lab Manual—Java Lab Exercises
Output
C:\javabook\programs\LabSyllabi > java StringDemo
The String is : java programming
The String is : JAVA PROGRAMMING
The length of String is : 16
The String starts with j: false
The String ends with G: false
The SubString starting from index 3 is: a Programming
The SubString starting from index 3 till index 6 is: a P
The converted String is : true
The converted String is : a
The converted String is : 2.4
The converted String is : 24
{
double s;
s = (Math.sin(Math.toRadians(degrees)));
return (float)s;
}
Output
C:\LabSyllabi > java mypack.Trignometry
Sin value of given angle in degree is:0.5
Cos value of given angle in degree is:0.8660254
Tan value of given angle in degree is:0.57735026
Cosec value of given angle in degree is:2.0000000000000004
Sec value of given angle in degree is:1.1547005383792515
Cot value of given angle in degree is:1.7320508075688774
Output
C:\javabook\programs\LabSyllabi > java WrapperDemo 20 10
Addition: 30
Concatenation: 2010
Addition of String: 2010
Integer Object: 20
Int value in Integer object i is : 20
long value in Integer object i is : 20.0
Appendix A: Lab Manual—Java Lab Exercises 643
Output
C:\LabSyllabi > java PredefinedExceptionDemo
java.lang.NullPointerException
{
return ("Rupees = " + rupees + " Paisa = " + paisa);
}
void addition(Money a2) throws MoneyOverflowException
{
int r = 0;
int p = paisa + a2.paisa;
if(p >= 100)
{
p = p –100;
r + = 1;
}
r + = rupees + a2.rupees;
if(r > 100000)
{
throw new MoneyOverflowException("From Addition Method");
}
System.out.println("After Addition ::");
System.out.println("Rupees = " + r + " \t" + "Paisa = " + p);
}
float getRupees()
{
return rupees;
}
float getPaisa()
{
return paisa;
}
Appendix A: Lab Manual—Java Lab Exercises 645
Output
D:\>java finance.Money 24 23 20 45
Rupees = 24 Paisa = 23
Rupees = 24.0
Paisa = 23.0
Rupees = 20 Paisa = 45
Rupees = 20.0
Paisa = 45.0
After Addition ::
Rupees = 44 Paisa = 68
After Subtraction ::
Rupees = 3 Paisa = 78
D:\>java finance.Money 28 23 24 23
Rupees = 28 Paisa = 23
Rupees = 28.0
Paisa = 23.0
Rupees = 24 Paisa = 23
646 Appendix A: Lab Manual—Java Lab Exercises
Rupees = 24.0
Paisa = 23.0
After Addition ::
Rupees = 52 Paisa = 46
After Subtraction ::
Rupees = 4 Paisa = 0
Output
Parent Thread: mainPriority:5
Parent Thread: mainPriority:5
Parent Thread: mainPriority:5
Parent Thread: mainPriority:5
Parent Thread: mainPriority:5
Child Thread : DemoThreadPriority: 3
Child Thread : DemoThreadPriority: 3
Child Thread : DemoThreadPriority: 3
Child Thread : DemoThreadPriority: 3
Child Thread : DemoThreadPriority: 3
Appendix A: Lab Manual—Java Lab Exercises 647
(b) Multithreading
/* A simple withdraw and deposit threaded program*/
class Deposit
{
int money = 0;
synchronized void submit()
{
try{
Thread.sleep(1000);
}catch(Exception e) {}
money = money+100000;
System.out.println(“Amount Has been deposited. . .”+money);
flag=0;
notifyAll();
}
synchronized int withdraw(int a)
{
try{
System.out.println(“wait for amount to be withdrawn”);
wait(1000);
money = money-a;
}
catch(Exception e) {}
notifyAll();
return money;
}
}
class Thread1 extends Thread
{
Deposit s;
Thread1(Deposit s,String str)
{
super(str);
this.s = s;
start();
}
public void run()
{
int amount = s.withdraw(3000);
System.out.println(“Amount has been submitted and can be withdrawn: “ + amount);
}
}
class Thread2 extends Thread
{
Deposit s;
Thread2(Deposit s,String str)
{
super(str);
this.s = s;
start();
}
public void run()
{
s.submit();
}
}
648 Appendix A: Lab Manual—Java Lab Exercises
class TestDeposit
{
public static void main(String s[])
{
Deposit st = new Deposit();
Thread1 withdrawThread1 = new Thread1(st,”One”);
Thread2 submitThread1 = new Thread2(st,”Two”);
Thread1 withdrawThread2 = new Thread1(st,”Three”);
Thread2 submitThread2 = new Thread2(st,”Four”);
}
}
Output
D:\javabook\appendixa>java TestDeposit
wait for amount to be withdrawn
Amount Has been deposited. . .100000
wait for amount to be withdrawn
Amount has been submitted and can be withdrawn: 97000
Amount Has been deposited. . .197000
Amount has been submitted and can be withdrawn: 194000
Output
C:\javabook\programs\LABSYL~1 > java Copy
Enter the file name to be copied:
Appendix A: Lab Manual—Java Lab Exercises 649
TestDeposit.java
Enter the new file name:
Test2.java
Output
C:\javabook\programs\LABSYL~1 > java DemoGeneric
Class A Object
Class A Object
Class B object
Class B object
APPENDIX B: Interview Questions
1. What is the difference between an interface and 8. What is the difference between a constructor
an abstract class? and a method?
An abstract class can have concrete methods (that A constructor is a special member function of a
depict default behaviour) as well as abstract (no class that is used to initialize the objects. It has the
implementation) instance methods. An interface same name as that of the class, without any return
can only declare constants and methods, but cannot type, and is invoked using the new operator. For
provide implementation of the methods. In other example,
words, all the methods in the interface are implicitly class Demo
abstract. In an interface, all members are public {
with no implementation. Refer Table 6.1 for all Demo(){} // constructor
differences. }
2. What is the purpose of garbage collection in A method is an ordinary member function of a class.
Java? It has a name (although not recommended but can
Garbage collection is used to identify and discard be same as that of the class), a return type (which
objects that are no longer needed by a program. The may be void) and are invoked using the dot operator.
resources (e.g., memory) allocated to an object can For example,
be reclaimed when all references to it are null. public void add(int a, int b)
3. What are pass by reference and pass by value? It is invoked as shown below:
In pass by reference, the addresses of the variables
objectName.add(4,5) // for instance method
are passed rather than their value. Pass by value
Classname.add(4,5) // for static methods
means a copy of the value is passed whereas in pass
9. Explain the keyword ‘static’ in Java.
by reference no copy is created. The actual variable
is referenced. Static members can accessed without creating an
instance of a class. Static cannot be overridden
4. Describe thread synchronization. because they are attached to a class, not an object.
Thread synchronization is used to maintain However, a static method can be shadowed by
consistency of data by preventing concurrent another static method in a subclass.
access of shared resources by multiple threads. 10. Explain the keyword ‘final’ in Java.
A thread can modify a shared resource (variable The keyword ‘final’ can be used at three levels:
or data structure) while another thread is using or class, method, and variable. A final class cannot
modifying the same shared structure. be inherited, i.e., they cannot be sub classed. Final
5. What are the different ways of creating threads method cannot be overridden and you cannot
in Java? change the value of a final variable (it is a constant).
Inherit the runnable interface or thread class. 11. What are the different types of cloning objects?
The different types of cloning objects are deep and
6. What is cloning?
shallow copying.
Cloning is basically making a copy of an existing
12. What will happen if the static modifier is
object.
removed from the main method?
7. What is the difference between a vector and an
This method becomes a normal method of the
ArrayList?
class and not the main method which is desired by
Vector class is synchronized, whereas ArrayList the JVM to execute the method. So the program
class is not synchronized. compiles, but shows a runtime error.
Appendix B: Interview Questions 651
that IP address used for identifying the applications (e) Reference: name of named reference within
running on that particular machine. IP address exists the page (i.e., cs), for example, www.yahoo.
on network layer and port numbers on the transport com/index.html#cs.
layer of the TCP/IP protocol suite. TCP clients are 32. What are anonymous classes?
created with the help of java.net.Socket class and An anonymous inner class is a local class that has no
server with the help of java.net.ServerSocket name. They are extensively used in event handling.
class. UDP socket are created using java.net. 33. What is shadowing?
DatagramSocket class.
Shadowing of fields occurs when variable names
27. What are wrapper classes? are same. It may occur when local variables and
Java provides special classes in the java.lang instance variable names collide within a class or
package which encapsulate the primitive data variable names in a superclass and subclass are
types. These are called wrapper classes. They are as same. In case of methods, instance methods are
follows: Byte, Short, Integer, Long, Double, overridden whereas static methods are shadowed.
Float, Character, and Boolean. The difference between the two is important
28. What is the difference between an error and an because shadowed methods are bound early
exception? whereas instance methods are dynamically (late)
An error is an irrecoverable condition which binded.
occurs at runtime, for example, OutOfMemory 34. What is dynamic binding?
error. While exceptions are conditions that occur Objects exist at runtime, and hence late binding is
because of programming mistakes or bad input, done by the JVM at runtime for resolving which
for example, FileNotFoundException will be method will be executed. It is also known as
thrown if the specified file does not exist or a dynamic binding or runtime binding.
NullPointerException will take place if you try
35. What are nested classes?
to use a null reference. In most of the cases it is
possible to recover from an exception. Nested class is a class with a class. Nested classes
are of the following types:
29. Is it necessary that each try block must be
Non-static inner classes
followed by a catch block?
No, it is not necessary. try block can be followed Static nested classes
When a method with the same name and signature 49. Which abstract class is the superclass of all
exists in superclass as well as sub class (i.e., a classes used for reading bytes?
case of method overriding) which method will be InputStream is the superclass of all classes used
executed (superclass version or subclass version) for reading bytes.
will be determined by the type of object from which 50. What is the name of the collection interface that
it has been called and so it cannot be done by the is used to maintain unique elements?
compiler. Hence, it is done at runtime and that is Set.
why these methods are late bound by the runtime 51. What is scrollable result set?
environment.
The ResultSet, before JDBC 2.1, could be scrolled
40. What is a static nested class? in forward direction only. JDBC 2.1 introduced
A static nested class is a static member of a class just the concept of moving the cursor in backward
like normal static members of any class. They have direction also. You can even position the cursor of
access to all static methods of the enclosing parent a ResultSet object on a specific row.
class. The static nested classes cannot directly refer 52. What is a transaction?
to instance variables and method of the outer class, A transaction is a set of statements that if
similar to static parts of any class. They can only executed should complete in entirety. If any of the
do it through an object of the outer class. Unlike statement fails to execute in a transaction, the entire
the inner classes, the static nested classes can have transaction should be rolled back.
static members.
53. What is auto commit?
41. Which method is used to get and set the label
Auto commit feature commits the changes made by
displayed on a button object?
SQL statements to the database and is by default set
setLabel(String txt) –for setting label to true. It can be set using the following method of
and the connection object.
getLabel() — for getting the label con.setAutoCommit(false);
42. What is the difference between Scrollbar and 54. What is a servlet?
ScrollPane? Servlets are Java server-side programs that accept
ScrollPane is a container whereas Scrollbar is a client’s request (usually http request), process them
component. and generate (usually http response) responses. The
requests originate from the client’s web browser and
43. What is the difference between String and
are routed to a servlet located inside an appropriate
StringBuffer?
web server. Servlets execute within a servlet
String is immutable whereas StringBuffer is container which resides in a web server like Apache
mutable. Tomcat.
44. Which operators are known as short-circuit 55. What is lifecycle of a servlet?
operators?
The init() method is called only once during the
&& and || are known as short-circuit operators. lifetime of an applet. One time initializations are
45. Which abstract class is the superclass of all done in this method.
classes used for writing characters? The service method is used for processing the
Writer class is the superclass of all classes used client’s request and generating responses. The
for writing characters. request may be forwarded by service method
46. What is the name of the exception thrown by the to doGet() or doPost() depending upon the http
read method defined in InputStream class? request. If it is a get request, doGet() will be called
IOException. and if it is a post request, doPost() will be called.
The service method is capable of handling both
47. What is the name of the class that allows reading
types of requests (get and post).
of Java primitives from an input byte stream?
The destroy method is called by the servlet
DataInputStream.
container before the servlet is unloaded. So clean-
48. Name the parent of all the classes in Java. up activities like closing the database connections
Object class. can be done in this method.
654 Appendix B: Interview Questions
56. What common http methods are used to send 61. What is the difference between a JSP and a
data from http client to a web server? servlet?
The client’s data is sent to the server from the JSP offers a significant advantage over servlet. JSP
client’s browser via two methods of http protocols: is embedded in html with some special delimiters
get and post. which look like tags. So it is easy to learn. To
57. What are the drawbacks of using get method for work with a servlet you need to learn Java and its
sending data to the server? programming styles which is not the case in JSP.
The get method appends data to the URL (of the Moreover, JSP pages are automatically recompiled
servlet handling the request) and passes it to the when required, which is not the case with servlets.
server. The drawbacks of this approach are: Servlet have to be recompiled in case they are
The URLs are of fixed size and it puts a changed. So as soon as you refresh your JSP page,
restriction on the amount of data that can be changes made to it are reflected.
transmitted to the server. 62. What is JavaBeans?
Moreover, whatever data is sent to the server JavaBeans provides a standard format for writing
is visible in clear text. Java classes. Java bean is reusable software
58. What is a cookie? component. Once it is designed and created, it
Cookies are basically small pieces of information can be used over and over again in many different
stored on the client’s machine by the browser. A applications as per their requirements. Java beans
cookie contains information like user browsing can be used by IDE and other Java API’s to create
preferences, user id and password combinations, new applications.
session id, and number of times a user has visited a 63. What is a Jar file?
page. This information is stored in pairs, i.e., name- JAR stands for Java archive. It is similar to a ZIP
value pairs. This information wrapped in a cookie file. A JAR tool is provided with Java development
object is sent to the client browser by a servlet, kit (JDK) to perform basic tasks with JAR files.
which stores it somewhere in its temporary Internet 64. What is a manifest file?
files. Whenever a request is sent to that particular Manifest file (.mf) is a special file that can contain
server (from where cookie was downloaded), all information about the files contained in a JAR file.
the cookies (stored in the client’s machine from that A manifest file could be used to tell which classes
very server) are attached to the http request and sent in the JAR are bean classes, or which is the main
to the server. The server can then fetch the cookies class (starting point) in the JAR, etc.
from the request and then act accordingly. 65. What is EJB?
59. What is a session? EJB is a server side distributed component of the
A session is used to track the user between J2EE architecture that primarily provides business
successive requests from the same client to same logic besides interacting with other server side
server. A session is a kind of conversation between components. EJB developers need to focus only
the server and a client. A conversation is a series of on coding business logic leaving the system level
continuous requests and responses. services to be handled by EJB server which include
multiple threading, object pool, security, instance
60. What is JSP? management, connection pooling, transactions, etc.
JSP stands for Java server pages. JSP, in contrast EJB is based on the concept that in a distributed
to servlets, is basically a page that contains Java computing environment, database-related logic
code embedded within html tags. Servlet is a Java should be independent of the business logic that
program where html tags are embedded in Java relies on the data.
code or html responses are generated through Java. 66. What are the different types of EJB?
JSP files have an extension .jsp and they execute As per EJB 2.0 specification: session, entity, and
within a JSP container present in the web server. message-driven bean.
This container actually translates the .jsp into an 67. What is autoboxing and unboxing?
equivalent servlet. In other words, JSP is a servlet
Java 5.0 introduced a new feature for converting back
in the background.
and forth between a wrapper and its corresponding
Appendix B: Interview Questions 655
then ultimately the exception passes to the default Method overloading, method overriding, and
exception handler. constructor overloading are the various ways of
80. What is platform independence? achieving polymorphism in Java.
Platform independence means that a Java compiled 90. What are checked and unchecked exceptions?
code can run on any platform provided the Java Checked exceptions are monitored by the compiler
runtime environment exits on that platform. whether you have handled them in your program or
81. What is an applet? not. Unchecked exceptions (or runtime exceptions)
are not checked by the compiler.
Applet is the Java program meant to be embedded
in a webpage. 91. What is a thread?
82. What is the purpose of repaint method? Threads are parts of a process running concurrently.
Threads are used for achieving multitasking.
repaint() method is used to paint the applet again.
In other word, it invokes a call to the paint method 92. What are generics used for?
of the applet on an event. This feature was added in Java 5 with an aim
to provide strict type checking at compile time.
83. What is a class?
Generic feature also allows same class to be used
Class is a collection of object with similar attributes by many different collections of objects such as
and behavior. It is also defined as a new or user string, and integer. It would be much better to check
defined data type. at compile-time what goes into a collection so that
84. What is an object? no exception occurs at run time. If we could ensure
Objects are instances of a class. only objects of a particular type should go into the
85. What is abstraction? collection then most runtime problem can be solved
and that is where generics help.
In programming, we manage complexity by
concentrating only on the essential characteristics 93. What is an iterator interface used for?
and suppressing implementation details. Abstraction Iterator interface is used for iterating through the
focuses on the essential characteristics rather than elements of a collection.
the details. 94. Can constructors specify the throws clause?
86. What is encapsulation? Yes.
The process of binding the data procedures into 95. Can switch…case statement accept string?
objects to hide them from the outside world is Yes, Java 7 onwards.
called as encapsulation. It provides us the power 96. What is aggregation?
to restrict anyone from directly altering our data.
It is a part-of relationship among objects. When
Encapsulation is also known as data hiding.
a particular object is a part of another object then
87. What is the basic purpose of finalize method? we say that it is aggregation. For example, car is
Before an object gets garbage collected, the garbage an aggregation of many objects: engine, door, etc.
collector gives the object an opportunity to clean 97. Can an interface inherit another interface?
up itself through a call to the object’s finalize() Yes
method. This process is known as finalization. All
98. What to declare a class if it does not override all
occupied resources (sockets, files, etc.) can be freed
methods of an interface?
in this method. The finalize() method is a member
function of the predefined java.lang.Object class. abstract
A class must override this method to perform any 99. Which class is the superclass of all errors and
clean up if required by the object. exceptions in Java?
88. What is polymorphism? Throwable class is the superclass of all errors and
Poly means many and morph means forms. So exceptions in Java.
basically it means more than one implementations. 100. What is RMI?
One name many implementations is the key idea RMI stands for remote method invocation. RMI is
behind polymorphism. one of the ways by which distributed computing
89. What are the various ways of achieving poly- can be achieved. The concept of RMI is to invoke
morphism in Java? an object that resides in one JVM by another object
residing in another JVM.
INDEX
ByteBuffer 277
Bytecode 16 17
Verifier 19
Byte stream 261
Canvas 430
CardLayout 430 465 467 468
Casting 57 59 60
Character stream 269
Char literals 47
Checkbox 430 438 439 440
441
CheckboxGroup 430
CheckboxMenu Item 430
Child threads 227
Choice 430
Choice boxes 448
Class declaration in Java 77
Classes 74 76
Class loader 19
Class method 76 100
Classpath 35 163
Class/static variables 97
Class variables 76
Cloneable interface 285
Cloning 285
CMP (container managed persistence) 614
Collection 296 297
Interface 297
Collections API 25
Collections class 318
Color 430
Color class 380 381
Command-line arguments 118
Compaction 96
Compilation 17
Component 9 430
ComponentListener interface 406
Composition 9
Conditional statements 62 185
Constrained properties 599
Constructor 90-93
Chaining 104
Overloading 94
Parameterized 93
Containers 430 432
Class 455
ContainerListener Interface 406
Continue statement 70
Conversion 60
Cookies 576
CopyOption 279
Cursor 540
Data encapsulation 76
Data hiding 4
Dynamic binding 5
Late binding 5
Method invocation 5
Runtime polymorphism 5
Data types 42 43
Boolean 43
Byte 43
Char 43
Double 43
Float 43
Int 43
Long 43
Short 43
tdouble 43
Deep copy 285 290 292
DefaultMutableTreeNode 518
DefaultTreeModel 517
Deployment descriptors 622
Dialog 431
Dialog box 525 527
Diamond operator 27
Dimension 431
Directory structure 34
doFilter method 585
Draw String() 361
Dynamic binding 139
Echo 118
Echo client 348
Eclipse 39
Enumerated type 183 184
Enumeration 186 320
Enum type 183
Escape sequences 47
Event classes 395
Field 21
FileChannel 277
FileDialog 431
Files 269 278
Fill 475 476
Filter 585
FilterChain 586
Final 146
Finalization 97
Finally block 209
FlowLayout 431 459 461
FocusEvent class 402
FocusListener interface 405
Font 431
Font class 382 383
Garbage collection 20
Garbage collector 96
Gel 39
Generic classes 307 308
Generics 25 301 304 305
getCodeBase() 369
getContentPane() 498
getDocumentBase() 369
getState() 238
Global variables 21
Graphics 431
Class 377 379
GridBag constraints 431
GridBagLayout 431 471 474 475
476 477
Anchor 472
Fill 472
gridheight 472
gridwidth 472
gridx 472
gridy 472
insets 472
ipadx 472
ipady 472
weightx 473
GridBagLayout (Cont.)
weighty 473
GridLayout 431 469
gridx 475 476
gridy 475 476
Identifier 44 45
Constant 45
Interface 45
Method 45
Package 45
if…else 62
Image 431
Implements 158
Indexed properties 597
Inheritance 132 133 134 151
Hierarchical 134
Hybrid 134
Multilevel 133
Multiple 134
Single 133
javah 39
java.io.File 258
java.lang 169
Java messaging service (JMS) 615
java.nio.file 278
javap 39
java.util 296
Java Virtual Machine 15
javax.ejb.EntityBean 614
javax.ejb.MessageDrivenBean 615
javax.ejb.SessionBean 615
JCheckBox 502 505
JColorChooser 530 531
JCreator 40
jdb 39
JDesktopPane 539
JDK 37 38
JEditorPane j 546
JFileChooser 529 530
JFrame 497
JGlass 497
JInternalFrame 539
JLayeredPane 497
JList 510 511 512
JMenuBar 497
join() 243
JOptionPane 527
JPanel 501
JPopupMenu pum 546
JRadioButton 502 506
JRootPane 497
JScrollPane 510 512
jspDestroy() 589
jspInit(),_jspService() 589
JSP elements 590
Actions 590
Directives 590
Expression, scriptlets, and declarations 590
JSP Life Cycle 589
JSplitPane 513
JTabbedPane 514 515 516
JTable 521 523 525
JTextField 508
JToggleButton 502 506
JTree 516 519
Metadata 24
Method 21 82 83
Declaration 83
Type 82
Method overloading 87 88
Method overriding 137 141
Methods 91
Modifiers 83
MouseEvent class 400
MouseInfo 431
MouseListener interface 404
MouseMotionAdapter 411
MouseMotionListener 407
MouseMotionListener interface 405
MouseWheelListener interface 405
Multi catch 212
Multiple catch 204
Multiple inheritance 156
Multithreaded server 347 348
Multithreaded sockets 346
Multithreading 20 224 225 243
Naming convention 44
Narrowing conversion 59
Nested classes 119 124
NetBeans 40
Network interface 349
NimbusLookAndFeel 532
nio 276 278
Non-static inner classes 119
Null literals 47
Null pointers 28
Numeric literals 26 45
Object 21 75 76 79
80
Declaring 79
Initializing 80
Instantiating 79
Object oriented 16
Object-oriented analysis and design (OOAD) 6
Aggregation 8
Inheritance, aggregation, composition 8
Object-oriented modeling 2
inheritance 4
base class 4
subclass 4
Object-oriented programming 2
Abstraction 3
Classes 3
Encapsulation 4 11
Objects 3
OOAD using UML 6
Polymorphism 5
Observable 323
Class 322
Observer 323
Observer and observable 322
Observer interface 322
Octal literals 46
OOP 9
Applications 9
Operators 48 49 50 51
52 53 54
Arithmetic 48 49
Assignment 48
Binary 48
Bitwise 52
Boolean 51
Logical 51
Overloading 28
Relational 50
Shift 53
Ternary 54
Unary 54
OutputStream 257
Overloaded constructors 95
Overriding 149
PropertyChangeListener 600
PropertyChangeSupport 599
PropertyVetoException 541
Sandbox 19
Scrollable ResultSet 559
Scrollbar 431 483 484 485
ScrollPane 431
SeekableByteChannel 278
Serialization 283
Servers 340
Concurrent 340
Iterative 340
Session API 577
Session management 574
SET 311
setBackground() 362
setForeground() 362
Set interface 300
Shadowing 142 149
Shallow copy 285
showStatus() 362
Socket class 338
Sockets 337
SortArray.text 109
Split pane 513
StandardCopyOption 279
Static import 166 167
Static initialization block 101
Static members 100
Static methods 99
Static nested class 119 122
Static variable 21 98
Stealth project 13
Java bytecode 14
Java virtual machine (JVM) 14
JDK 15
JRE 15
Stream 256
String 176 177 178
Class 177 178
Manipulation 176
String (Cont.)
Methods 176
StringBuffer 179
String class 174
Subclass 132
Subpackages 164
Superclass 132 141 143
Swing 429 495 496 502
Features 496
switch-case 63 64
Synchronization 245
Synchronizing 246
SynthLookAndFeel 532
Thread (Cont.)
Blocked 236
Not runnable 236
Terminated 237
Timed_Waiting 236
Waiting 236
Throw 206 207
Tracing 96
Transactions 560
TreeExpansionEvent 518
TreeExpansionListener 518
TreeMap class 317
TreeSet class 314
try…catch 203
try-with-resources 210 211
Type conversion 57
Variable 42
Variable arguments 117
Vector 319
VetoableChangeListener 599
VetoableChangeSupport 599
weightx 476
weighty 476
White spaces 44
Window 431 456
WindowListener interface 405
Wrapper class 170 171
XML 537