You are on page 1of 193

BS 515 CA-E

B.A/B.Com/B.Sc
THIRD YEAR SEMESTER-V
DESCIPLINE SPECIFIC CORE COURSE-DSC-5

COMPUTER APPLICATIONS

PROGRAMMING WITH JAVA

“We may forgo material benefits of civilization, but we cannot forgo our right
and opportunity to reap the benefits of the highest education to the fullest
extent as the education is the greatest material benefit”

-Dr. B.R. Ambedkar

Dr. B.R. AMBEDKAR OPEN UNIVERSITY


HYDERABAD
2020
COURSE TEAM

Course Design Team (CBCS) Course Development Team (CBCS)


Editor & Writer
1. Prof. A. Vinaya Babu
Prof. S.V.L.Narasimham
2. Prof. S.V.L.Narasimham
3. Prof. V. Vijay Kumar.
Associate Editor
4. Prof. B. Vishnu Vardan. Vorsu Mallaiah
5. Prof. S. Vishwanatha Raju

6. Mr. Vorsu Mallaiah .


Cover Design
7. Mr. D. Venkateswarlu G. V. Swamy
8. Prof. P. Madhusudhan Reddy.

First Edition : 2020

© 2020, Dr. B. R. Ambedkar Open University, Hyderabad, A.P.

All rights reserved. No part of this book may be reproduced in any form without the permission
in writing from the University.

The text forms part of Dr. B. R. Ambedkar Open University Programme.

Further information on Dr. B. R. Ambedkar Open University courses may be obtained


from the Director (Academic), Dr. B. R. Ambedkar Open University, Road No. 46,
Prof. G. Ram Reddy Marg, Jubliee Hills, Hyderabad- 500033.

Web: www.braou.ac.in

E-mail: info@braou.ac.in

Printed on behalf of Dr. B. R. Ambedkar Open University, Hyderabad by the Registrar.

Lr. No.-
Printed at: .................................................................................................................................

ii
PREFACE

This book on “Programming wth Java” is prepared for the Under Graduate Students
of B.A./B.Com/B.Sc studying in Dr. B. R. Ambedkar Open University. This course is offered
as a Discipline Specific Core Course (DSC) under CBCS being offered in V Semester as four
credit course. For the convenience of the students, the entire syllabus is organized in to four
blocks. Each block consists of three units. Each block covers a specific area of the subject.
The Units are prepared by the expert in accordance with a format so designed as to enable the
student to read and understand them without much difficulty. Each unit begins with a statement
of the Objectives followed by an introduction, self-check exercises in between and at the end
model examination questions intended to test the student’s comprehension of its subject matter.
“Programming with Java” course aims at gaining the knowledge of evolution of Java Language,
application of Java, comparisons with other languages like C and C++, advantages ofJava,
input and output, data types, operators, type casting, type conversion,classes,objects, garbage
collection, inheritance, encapsulation. And also enable the students to gain the knowledge of
using package; setting class path, access protection, importing packages, defining, implementing,
nested interfaces, applying interfaces, default interface methods, using static method in an
interface It enables all the students to learn basics to advanced features of Java language.
Today, we carry more computing power on our smart phones and tabs than was available in the
early models. The past decade has seen the revolutionary development in the hardware and
computer infrastructure. The software such as High level languages, Middleware, mobile
operating systems, GPS and deep learning software enhanced the skills of the people in solving
the challenging problems and living with emerging technologies. There is no doubt that the
intelligent computing technologies has helped to change the world. Most websites are hosted
on servers running free software. Even the mighty IBM, Google and Amazon also have their
walls placed in the rock-solid foundations of AI &ML, data mining, Big Data Analysis.

This course consists of four blocks and 12 units. Block-1 describesthe basic features
of Java which are History of java, downloading java, installing java, comparing java with C
and C++, Java vocabulary, variables, data types, type conversions, operators, literals, reading
input from keyboard, writing output to console. Block-II introduces the classes, objects new
operator, object references, methods, box class, types of constructors, this key word,. instance
variable hiding, garbage collection, finalize method, stack class, overloading methods and
constructors, access controls, final method, static method, static variables nested and inner
classes, string class, command line arguments with vararg. super class, second use for super,
multi-level hierarchy, method overriding, dynamic method dispatching, abstract classes, and
using final with inheritance. . Block-III explains Defining package, setting class path, access
protection, importing packages. Interfaces – defining, implementing, nested interfaces, applying
interfaces, default interface methods, use static method in an interface, Frame work, types of
exceptions, uncaught exceptions, try and catch, nested catch, multiple try, throw, throws, finally,
java built-in exceptions, user-defined exceptions, chained exceptions, recently added 3
exceptions. Collection Frame Work, Collection Classes- Array List, HaspMap, user defined
data in collections, using for each loop to iterate collections. . Block – IV describes the JDBC
definition, JDBC structure, registering and calling JDBC drivers, JDBC URL and the
connection, using JDBC drivers, Using meta-data, Transaction management with JDBC, event
handling mechanism, event classes, key event class, source of events, event listener interfaces,
using delegation event model, adaptor classes, inner classes-Examples of event handling with
AWT container and component classes and Java Swing.

The University hopes that this material will help the student to get clear concepts of
the Java, the power of java OOPs, Exception handling, Event handling,GUI API which enables
the world progress to modern era with the emerging computing technologies. iii
iv
CONTENTS

Block/Unit Title Page

BLOCK – I: BASIC FEATURE OF JAVA 1

Unit-1: Introduction to Java Language 3-14

Unit-2: Data Types 15 - 22

Unit-3: Java Operators and Control Structures 23 - 40

BLOCK – II: JAVA AND OOPs 41

Unit-4: Introduction to Classes and Objects 43 - 55

Unit-5: Additional Features of Java OOPs 56 - 69

Unit-6: Inheritance and Abstract Classes 70 - 81

BLOCK – III: ADDITIONAL FEATURES OF JAVA 83

Unit-7: Packages and Interfaces 85 - 94

Unit-8: Java Exception Handling 95 - 109

Unit-9: Java Collections 110 - 127

BLOCK – IV: BACK-END AND FRONT-END TOOLS OF JAVA 129

Unit-10: Java Data Base Connectivity 131 - 144

Unit-11: Java AWT and Event Handling 145 - 158

Unit-12: Java Visual Programming with Swing 159 - 184

Model Question Paper 185 - 187

v
vi
BLOCK - I

BASIC FEATURES OF JAVA


This block gives an overall study on the definition, evolution, applications of Java Language,
Comparing Java with C and C++, Downloading Java SE 8, Installing Java, setting class
path, and finally running first java program. It also enables the students to understand how
to read the input from keyboard, writing output to console, various types of operators like
arithmetic, bitwise, relational, Boolean and type conversions, type promotion in Java data
types. This block explainsif statement, if else, ire else if statement, switch multi-branching
statement, go to unconditional branching, iterations of java such as for loop, while loop,
do-while loop, for each loop, continue, and break statement in the loop..
The units included in the block are:
Unit-1:Introduction to Java Language
Unit-2: Data Types
Unit-3: Java Operators and Control Structures

1
2
UNIT-1: INTRODUCTION TO JAVA LANGUAGE
Contents
1.0 Objectives
1.1 Introduction
1.2 History, Evolution, Features of Java
1.3 Comparing with C++, Java SE 8, Phases of Execution
1.4 Sample Java programs
1.5 Summary
1.6 Check your progress – model answers
1.7 Model Examination Questions
1.8 Glossary

1.0. OBJECTIVES
After studying this unit, you should be able to understand
• the history, evolution and features of Java Programming Language
• the similarities and differences between Java and C/C++
• Features of Java SE8
• the structure of Java program along with how to read and print data

1.1. INTRODUCTION
Java language project, which was originally called Oak, was initiated by James Gosling, Mike
Sheridan, and Patrick Naughton in June 1991. Later the project went by the name Green and
was finally renamed Java. At that time Coke was the most favoured drink in software circles,
followed by Java coffee, the coffee from Indonesia. Since Coke is a brand already owned by a
company, Java was preferred. C/C++ style syntax are adopted in Java so that programmers
would be comfortable. Most of the features of Java language were also taken from C++ language
with suitable modifications, additions and omissions. Sun Microsystems (which is now acquired
by Oracle Corporation) released the first public implementation as Java 1.0 in 1996 as Free
and Open Source Software (FOSS). Java is generally available as Java Development Kit (JDK)
from its download site.Java is supported by a lot of open source libraries which can be used for
free to build applications. There are many tools and IDEs (Integrated Development Environment)
that makes your Java development easier. There are many frameworks that help you build
highly reliable applications quickly and easily since these frameworks already implements
common code pertaining to the applications.The Java community is huge and mature which
makes support easy in tight situations. Help on any topic is almost always available on Internet
how hard the problem may be.

1.2. HISTORY, EVOLUTION, FEATURES OF JAVA


java language history
Java language project, which was originally called Oak, was initiated by James Gosling, Mike
Sheridan, and Patrick Naughton in June 1991. Later the project went by the name Green and 3
was finally renamed Java. At that time Coke was the most favoured drink in software circles,
followed by Java coffee, the coffee from Indonesia. Since Coke is a brand already owned by a
company, Java was preferred. C/C++ style syntax are adopted in Java so that programmers
would be comfortable. Most of the features of Java language were also taken from C++ language
with suitable modifications, additions and omissions. Sun Microsystems (which is now acquired
by Oracle Corporation) released the first public implementation as Java 1.0 in 1996 as Free
and Open Source Software (FOSS). Java is generally available as Java Development Kit (JDK)
from its download site.
Java is supported by a lot of open source libraries which can be used for free to build applications.
There are many tools and IDEs (Integrated Development Environment) that makes your Java
development easier.
There are many frameworks that help you build highly reliable applications quickly and easily
since these frameworks already implements common code pertaining to the applications.
The Java community is huge and mature which makes support easy in tight situations. Help on
any topic is almost always available on Internet how hard the problem may be.
These strengths make the Java as number one programming language in the world by popularity
with the rating 15% followed by C with 13.3% and Python 8.5% (according to Tiobe analysts).
Evolution of java language
Java instantly became successful with its portability feature and libraries provided for various
mundane tasks in software development. Further, it supported the Graphical User Interface
(GUI) programming with its Applets and Abstract Windows Toolkit (AWT) out of the box
which was very cumbersome at that time with other languages.
With the success of its initial version, java quickly released its version 1.1 and then a major
features added version 1.2 in December 1998, which was also known as Java 2 Platform. In
this new version, there were many additions like GUI using Applet/AWT/Swing API,
Compilation on the fly compiler, support for audio formats, adding Array and reflections etc.
This version of Java is no longer supported since 2006 by which time Java 1.5 (Java 5) became
very popular.
Java was made available in three versions viz., Standard Edition (SE), Enterprise Edition (EE)
and Micro Edition (ME) since Java 2 to make it convenient for developers to download, install
and use. The standard edition is sufficient for most of the applications including web
applications. The enterprise edition aims at more advanced features required for the web like
Java Messaging Service (JMS), Enterprise Java Beans (EJB), Java Mail Service (JMS) etc.
The micro edition is targeted for the micro devices like Mobiles, TV, Set Top Box, Gaming
Consoles etc., where memory and capability of the device is very low.
Later there was another major advancement in the form of Java 1.5 or Java 5 in September
2004 which became a benchmark version for Java. This version introduced features such as
Generics, Annotations, Autoboxing/unboxing, Enumerations, Varargs, New concurrency utilities
in java.util.concurrent and Scanner class for parsing data from various input streams and buffers.
The next breakthrough version was Java 1.8 or Java 8 which was released in March 2014, and
the current version (Java 14) is an enhancement of Java 8. However the de facto version
accepted by industry is still the Java 8. All the examples, in this text are based on Java 8. This
version added new features like Lambda expressions, new Stream API, Functional interface
and default methods, Annotation on Java Types, Unsigned Integer Arithmetic, New Date and
Time API, Launch JavaFX applications from jar files, Strings in switch case structure etc.
Java 9 was released in September 2017 and Java 10 was released in early 2018, with minor
4 enhancements to the language like HTTP 2 client, JShell, Collection API upgrades etc.
Java 11 was released in September 2018 with enhancement to HTTP Client API, String API,
Collection, Files API etc.
Java 12 was released in March 2019 with further enhancements to String API, Files API, and
experimental support for expressions in switch case statement etc.
Java 13 was released in September 2019 with minor enhancements to Java 12
Java 14 was released in March 2020 with full support for switch case expressions, Helpful
NullPointerExceptions, Records, Text Blocks etc.
Features of java
Platform Independent:Java’s most important feature was the “Write Once, Run Anywhere”
(WORA) functionality which is necessary for software development companies to reduce the
porting cost from one operating system to another. Java software runs on everything from
laptops to data centres, game consoles to scientific supercomputers.
Secured:Java is fairly secure language with configurable security to allow over network and
file access restrictions. Static type-checking at compile time and runtime checking with built-
in security manager, the applications cannot be invaded from outside.
Industry Accepted:Java is accepted by industry as language of choice for the web due to its
support for server side components. It is maintained by the industry giant Oracle and supported
by almost all the big players in software industry including IBM, Redhat etc.
Simple and Safe: Java is similar to C/C++ but it removes the drawbacks and complexities of
C/C++ like pointers and multiple inheritances.
ObjectOriented:Java is a fully Object-Oriented Programming (OOP) language unlike C++
which is semi object-oriented. Java supports all OOP features such as abstraction, encapsulation,
inheritance and polymorphism.
Flexible:Since Java 8, Java is updated with functional programming feature like functional
interfaces and Lambda Expressions. This increases the flexibility of Java.
Robust: Java has automatic garbage collection which recovers memory allocated for variables
if the any variable is no more used. Java guides programmer toward reliable programming
habits for creating robust applications.
Fast:Java code is compiled into bytecode which is highly optimized by the Java compiler, so
that the Java virtual machine (JVM) can execute Java applications at full speed.
Multithreaded:The Java platform supports multithreading capabilities built into the language
right from its version 1.0 which means that applications can run on multiple concurrent threads,
resulting in better responsive applications.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. How do you say java is simple and safe?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

5
1.3 COMPARING WITH C++, JAVA SE 8, PHASES OF EXECUTION
Comparison with c and c++
Java language borrowed the syntax from C and features from C++ language with minor changes.
This helped programmers to quickly learn Java and migrate to this modern language since
they need not relearn syntax. Almost all the language features are supported in Java which are
the strength of C and C++ like static variables, recursive functions, variable argument functions
etc. Object oriented paradigm is supported totally just like C++. However there are some
distinct differences among these languages.
First and foremost of them is the removal of the pointers which is the source of many errors in
software particularly with memory leakages.
Further Java also removed support for multiple inheritance, which creates confusion. Instead
of this it introduced the concept of Interfaces to mimic the multiple inheritance.
Operator overloading is also removed from Java since it is unsafe because the implementation
may be misleading in some cases. For example, a library may implement a + symbol for doing
something else like say formatting the disk!
In C and C++ the “main” method is outside all the classes and structures, but in Java, it should
be within a class, which is the pure object oriented since no definition should be outside the
classes.
While C and C++ use “include” statement, java uses “import” statement which is more natural.
Some of the important feature comparisons are given in the following table:
C C++ Java
Structured code with its Compatible with C source Mostly follows C++/C
original syntax rules code, except for a few special syntax
cases

Doesn’t support Object Extends C with object- Fully supports Object


Oriented Programming oriented programming and Oriented Programming
generic programming. C code
can most properly be used
Write Once, Compile Same as C Write once, run anywhere/
anywhere (WOCA) everywhere (WORA/
WORE)

Allows procedural Allows procedural Allows procedural progra


programming. programming, functional mming, functional progra
programming, object- mming (since Java 8),
oriented programming, object-oriented progra
generic programming, and mming and generic progra
template meta-programming. mming (since Java 5)

Runs as native executable Same as C Runs on a virtual machine.


machine code for the target
machine instruction set

6
Has multiple binary Same as C Has one binary
compatibility standards compatibility standard,
cross-platform for OS and
compiler.

No boundary checking Optional automated bounds All operations are required


checking for some classes like to be bound-checked by all
vector and string. compliant distributions of
Java.

Unsigned Arithmetic Support Same as C. Same as C

Standardized minimum limits Same as C Standardized limits and


for all numerical types but sizes of all primitive types
actual sizes are implementation on all platforms.
dependent.
All primitive values are passed Passed by value and passed by All primitive and reference
by Value references are supported types are always passed by
value.
Memory management is Same as C Automatic garbage
manual. collection.

Supports struct and union only Supports class, struct and Supports class only
union

Overriding of methods not Supports overriding of Supports overriding of


supported methods methods

Has standard libraries Has standard libraries Has standard libraries


Operator overloading not Operator overloading Operators overloading not
permitted supported supported
Inheritance not supported Single and multiple Only supports single
inheritance of classes, inheritance of classes.
including virtual inheritance.
Templates not supported Parameterized types Parameterized types
supported with Templates supported with Generics
No Lambda functions lambdas supported Lambdas supported
No inline documentation Same as C Extensive Javadoc
mechanism documentation standard on
all system classes and
methods.
const keyword defines Same as C final keyword provides an
immutable variables and equivalent
member functions
Supports goto statement Supports the goto statement The goto is a reserved
. keyword but is unused
Compiled into target platform Same as C Compiled into platform
machine code independent Java byte code
7
JAVA SE8
Java Platform, Standard Edition 8 is a major feature release and is used throughoutthis notes.
Java SE8 enhanced the algorithms wherever it is possible and is the most favored version in
software development. Following is a list of some important features or enhancements
introduced in Java SE 8.
• Lambda Expressions - They enable function code or functionality to be passed as an
argument to another function which simplifies the code.
• Default methods are introduced in interfaces which will be used if no method is declared
in the class implementing it.
• The new Stream API to support bulk operations on collections.
• Better support for Internationalization and Unicode.
• New Date, Calendar and Locale APIs introduced that provide a comprehensive date-
time model.
• NashornJavaScript Engine is introduced to support JavaScript code.
• Performance improvement for the String class.
• Parallel Array Sorting implemented for performance improvement.
• Standard Encoding and Decoding Base64.
• Unsigned Arithmetic Support.
• The JDBC-ODBC Bridge has been removed and need to be explicitly downloaded if
it is required.
• JDBC 4.2 introduces new features.
• Java DB 10.10 Relational Database Management System (RDBMS) is included.
• Better network support and security features are added.
• Concurrency improvement.
Phases and block diagram of execution of java program
A java program is a pure text file with an extension of “.java”. This text file can be created
with any standard text editor like “notepad”, “wordpad” or some other editor which is more
capable of. Once the java code is saved in a java file, it must be compiled to create a bytecode
file which is uniform across all platforms. Java compiler creates a “.class” file for every class
that is defined in Java code. This bytecode can be understood by a Java Virtual Machine
(JVM) which will load and run it. This process essentially takes two phases where the first
phase is to convert Java code to bytecode and the second phase is to load and run this bytecode
inside a JVM. Once the bytecode is generated, it can be run with the “java” command that
initiates a JVM which loads the bytecode from the class file and performs various checks
before it is run. Following are the steps followed in running bytecode by the JVM. The class
loader loads the bytecode file. The bytecode is verified for correctness and integrity. The JVM
takes the loaded code and interprets the code instruction by instruction.
Following diagram shows the process of compiling and running a Java program.

8
Java Code
Java Code Compiler
Compiler Byte
Byte Code
Code
Test java
Test.java java
java Test.class
Test Class

Java
Java Byte Code
Byte Code Class loader
Class loader
Internreter
Interpreter Verifier
Verifier

Machine
Machine Specific
Specific Output
Output
Runtime
Runtime

Figure 1.1
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is Java SE8?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

1.4 SAMPLE JAVA PROGRAMS


In this section, a simple Java class is given and step by step process is given to create, compile
and run the program. The program just prints a standard “Hello World” message on the screen.
Before anything else, the Java must be installed on the machine. Follow the instructions from
any website that gives the process. Search for “How to Download & Install Java JDK 8 in
Windows” where Windows may be replaced with appropriate operating system. (https://
www.guru99.com/install-java.html is one of the search results which shows how to install
Java and set PATH and CLASSPATH variable. However it is the reader’s choice to choose any
result). After downloading and installing JDK 8, the CLASSPATH environment variable must
be set accordingly. There are at least three files required to be added to the CLASSPATH
which are “rt.jar” from jre/lib folder, “tools.jar” and “dt.jar” from java/lib folder.
For example on Windows system, one can right click on “this PC” icon or search for
“environment variables” in menu or control panel and select edit environment variables. This
pops up the following window where the “Environment Variables” button is clicked.

9
It opens up the window of system properties as shown below:

Here click on the CLASSPATH variable if exists or click on new button if it doesn’t exist. This
opens up the System variable edit window with variable name and variable value. The class
path value is a series of directories separated by semicolons in windows (by colons in Linux).
Add all the paths to the jar files separated by semicolons and click OK button. This adds the
various jar files to the CLASSPATH environment variable, which are automatically scanned
for any missing classes by Java compiler during compilation and running.

10
Open any text editor (notepad.exe on Windows or vi or some other editor in Unix) and type the
following code without the preceding numbers and space.
1 import java.lang.*; // Import statement(s) here
2 public class HelloWorld// class declaration
3 {
// class block begin
4 public static void main(String args[]) // main method
5 { // main block begin
6 System.out.println(“Hello World”); // output
7 } // main block end
8 } // class block end
Save this file at a convenient location as “HelloWorld.java”. For convenience create a folder
for all the java files say at “D:\javacode” on Windows or “./javacode” in Unix platform.Note
that the class name should be same as file name (with a .java extension) always.
Though the program takes only a few lines of code, it provides an insight into the Java program.
The 1stline is an import statement that instructs the compiler to add code from all library files
from the package java.lang. This java.lang package is automatically imported and need not be
explicitly imported. This is only for illustration purpose and in real programs it is never used.
More details on packages will be given later.
The 2nd line declares a new class called “HelloWorld” with public scope.
The 3rd and 8th lines declare a block of code within which the main method is written.
The 4th line declares the standard main method. This should be declared as public static void
method with an array of strings as parameters. Here the parameter name is taken as “args”
arbitrarily.
Lines 5 and 7 declare the block for the method “main”.
Line 6 uses the println method of the “out” object declared inside the built-in System class.
This outputs the string given as parameter, which is “Hello World” in this case. The System.out
object generally refers the standard output device (screen).
Additionally comments can be added anywhere in the document using either // (line comments),
“/* comment here */” (multiline block comment) or “/** comments here */ (multiline document
comment). These comments are ignored during compile time. All the text after the // to the end
of that line are ignored in case of line comments or all the content between /* and */ is ignored
in case of block or document comments.

11
Observe that the code is indented to make each block clearly identified. Java removes all
unnecessary spaces and tabs before compiling the code. This indentation is important for
readability of the code which in turn improves maintainability of the code.
The name of the file should be the name of the class including the case with an extension of
“.java” in lower case. Note that file names are case insensitive in Windows where as they may
be case sensitive in other operating systems.
Now open a command window (by running cmd in Windows or by firing a console session in
Unix systems). Move to the folder where the file is stored with cd command. For example, on
windows issue the following two command if the folder of the java file is “D:\javacode”.
D:
cdjavacode
Now the command prompt changes to (D:\javacode>) from where the program is run.
Run the compiler on HelloWorld.java with the following command:
javac HelloWorld.java
If there are no errors, the HelloWorld.class file will be generated in the same folder. If there
are errors (most likely some kind of typo error), it shows the error along with line number and
so correct it in the Java file with text editor and rerun the javac command.
Once the class file (ByteCode) is generated, it is ready to be run with the interpreter under
JVM. This is done with the java command.
javaHelloWorld.class
If everything goes well, the output is printed on the screen. If any change is made to the source
code, the javac and java commands should be repeated.
Separators: There are certain characters which are used as separators in Java.
( ) Parenthesis: Used to contain list of parameters and to change the precedence in expressions.
[ ] Brackets: Used to declare array type and to access an element in an array.
{ } Braces: Used to define a block of code.
; Semicolon: Used to separate statements or statement terminator.
, Comma: Separates consecutive identifiers and chains statements.
White spaces: The tab, space, newline and carriage return characters are treated as white space
characters.
Java program that reads input and prints output
In the previous example, there is no input required and only there is an output statement
(System.out.println). However, in many cases a program requires some input from the user.
The input can be from various devices like keyboard, file, network etc.. In the next example
We consider reading input from keyboard and shows an output to the screen. The standard
input device (keyboard in this case) is accessed by the built-in System.in object. As was
mentioned earlier, the import of java.lang.* is omitted since it is automatically imported.
Consider the following example that reads a name from the keyboard and prints a hello message.
The keyboard is generally attached to an input stream and the methods from the stream are
used to get input from keyboard. The easiest way is to use a scanner object which is defined in
java.util package. Hence, the java.util.Scanner is imported first and then it is instantiated with
the System.in as its input. The Scanner class has methods for reading various data types which
12 are given below:
intnextInt() Returns the next token as an int.
float nextFloat() Returns the next token as a float.
double nextDouble() Returns the next token as a long.
String next() Returns the next token as a string terminated by a blank.
String nextLine() Returns the rest of the current line, excluding any line separator at the
end.
The next program reads a name and salary from the keyboard and shows the read values on the
screen.
importjava.util.Scanner;
publicclass Test{
publicstaticvoid main(String[] args)
{
Scanner scn = newScanner(System.in);
System.out.print(“Enter Name: “);
String name = scn.nextLine();
System.out.print(“Enter Salary: “);
intsalary = scn.nextInt();
scn.close(); // Close Scanner
System.out.println(
“Hello “ + name +
“ Your salary is: “+ salary);
}
}
In the above program, the Scanner class is imported first. Then the class Test is declared as
public. Then the main method is declared within the class. In the main, an object of type
Scanner is declared and instantiated with System.in as its input. Now there are a couple of
prompt messages followed by two scanner input methods (nextLine() and nextInt()) to read
required input from keyboard. The last print statement prints the information by adding the
string literals and the read values. The plus sign with strings will concatenate them.
Check Your Progress

Note: a) Space is given below for writing your answers

b) Compare your answers with the one given at the end of the unit

3. What is Scanner?

............................................................................................................................................................

............................................................................................................................................................
............................................................................................................................................................
13
1.5 SUMMARY
This unit aims at introducing the Java language and explains how a program can be entered
into computer, compiled and run. It gives a brief history of Java language, its features which
made them the most popular language and a small introduction to the structure of a Java
program. The input can be from various devices like keyboard, file, network etc.. In the next
example We consider reading input from keyboard and shows an output to the screen. The
standard input device (keyboard in this case) is accessed by the built-in System.in object. As
was mentioned earlier, the import of java.lang.* is omitted since it is automatically imported.
Consider the following example that reads a name from the keyboard and prints a hello message.
The keyboard is generally attached to an input stream and the methods from the stream are
used to get input from keyboard. The easiest way is to use a scanner object which is defined in
java.util package. Hence, the java.util.Scanner is imported first and then it is instantiated with
the System.in as its input. The Scanner class has methods for reading various data types.

1.6. CHECK YOUR PROGRESS MODEL ANSWERS


1. Java does not deal pointers and multiple inheritance.
2. Java platform Standard Edition 8.
3. Scanner is a class in java.util which reads input from any input source.

1.7. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
1. Describe the features of Java.
2. Explain how to download and install Java on Windows.
3. Explain the difference between C&C++ and Java
II. Answer the following questions in about 15 lines each
1. Describe how to set the path and class path to compile and execute java code
2. Write a simple java program to read and print a string.
3. Describe additional features in Java SE8.

1.8.GLOSSARY
Class Method : A method that is invoked without reference to a particular
object. Class methods affect the class as a whole, not a
particular instance of the class.
Class Variable : A data item associated with a particular class as a whole—not
with particular instances of.
Classpath : An environmental variable which tells the Java virtual
machine Where to find the class libraries, including user-
defined class libraries
Declaration : A statement that establishes an identifier and associates
attributes with it, without reserving its storage (for data) or
providing the implementation (for methods).
Default : A Java keyword optionally used after all case conditions in
a switch statement. If all case conditions are not matched by
14
the value of the switch vari
UNIT-2: DATA TYPES
Contents
2.0 Objectives
2.1 Introduction
2.2 Java Data Types
2.3 Keywords and Type Conversions
2.4 Summary
2.5 Check your progress – Model Answers
2.6 Model Examination Questions
2.7 Glossary

2.0 OBJECTIVES
After studying this unit, you should be able to understand
• various data types available in Java
• how to declare variables and literals,
• casting of one data type to another and automatic conversion of data types
• some special characters defined in Java

2.1 INTRODUCTION
In Java, all the variables are objects except the primitive types. If any object is to be created, it
should be created with the “new” keyword and should be assigned to a variable (known as
handle). The syntax for the creation of objects is given in the example below, which defines an
object of type String and assigns it to a variable of type String named s along with an initial
value for the string.Stack and heap are two different areas in memory to store variables. The
heap space variables are available throughout the application while the stack space variables
are available only during that block. The heap space contains all objects that are created, while
stack space contains any reference to those objects and primitive values. A variable is a name
given to a storage area which a program can manipulate. Each variable in Java is associated
with a data type, which is required to determine the size required in memory. A variable name
should start with an alphabet (a-z, A-Z), a $ or an underscore (_) followed by any number of
alphabets or digits or underscores

2.2 JAVA DATA TYPES


In Java, all the variables are objects except the primitive types. If any object is to be created, it
should be created with the “new” keyword and should be assigned to a variable (known as
handle). The syntax for the creation of objects is given in the example below, which defines an
object of type String and assigns it to a variable of type String named s along with an initial
value for the string.
String s = new String(“this is initial value”);
Here, Stringclass is a built-in non primitive data type in Java. It is important to note that
custom data types can be created by way of classes, which is the fundamental activity in Java 15
programming.
Primitive Types
There are certain data types in Java, which are built into the language for efficiency reasons;
which are known as primitive data types. Creating a simple object like integer with new is
inefficient. Hence Java uses the approach taken by C and C++ where an “automatic” variable
is created which holds the value directly instead of its address and it is placed on the stack so
it’s much more efficient. Java determines the size of each primitive type. These sizes don’t
change from one machine architecture to another as they do in most languages. This size
invariance is one of the reasons for the Java’s portability. Following table gives the details of
the Java’s built-in data types.
Primitive type Size Minimum Maximum Wrapper
Type
boolean 1-bit – – Boolean
char 16-bit Unicode 0 Unicode 2 16- 1 Character
byte 8-bit -128 +127 Byte
short 16-bit -215 (-32768) +215 – 1 (+32767) Short1
int 32-bit -231 (-2147483648) +231–1 (+2147483647) Integer
long 64-bit -263 (-9223372036854775808) +263–1 (-9223372036854775807) Long
float 32-bit 3.4e-038 3.4e+038 Float
double 64-bit 1.7e-308 1.7e+308 Double
void – – – Void
All numeric types are signed (unsigned types which are available in C/C++ are not supported).
The primitive data types also have equivalent “wrapper” classes if one is particular to use the
Objects instead of the built-in data types. Java provides ways to convert a primitive value to an
equivalent object and vice versa. For example:
char c = ‘x’; creates a variable c on stack where as
floatfloatValue = 12.3f;
The suffix ‘f’ denotes that it is a float value. Without this it is treated as double value and gives
an error since it cannot convert double to float implicitly
Character obj = new Character(c); // creates a variable
or
Character obj = new Character(‘x’); // creates a variable
In the above two examples, ‘obj’ is created with the same value ‘x’. In the first case, a variable
is passed as parameter, and in the second case a literal is passed.
For now consider stack and heap are two different areas in memory to store variables. The
heap space variables are available throughout the application while the stack space variables
are available only during that block. The heap space contains all objects that are created, while
stack space contains any reference to those objects and primitive values.
Variables or identifiers
A variable is a name given to a storage area which a program can manipulate. Each variable in
Java is associated with a data type, which is required to determine the size required in memory.
A variable name should start with an alphabet (a-z, A-Z), a $ or an underscore (_) followed by
16 any number of alphabets or digits or underscores. Though the $ symbol is valid, it is not
generally used favoring C/C++ syntax. Java is case sensitive language which means lower
case letters are not same as upper case letters. Hence, there may be two variables ‘a’ and ‘A’
exist simultaneously within a block. Variables in Java can be direct variables, which can be
used for storing values of primitive data types, or handles, which store the addresses of objects.
For example,
intval; stores an integer value in val directly where as
String str; stores the address of the object (known as handle).
Following are some of the valid variable names
valueOfVariable, _01, StrVal_02, __01_value, $val
Following are invalid variable names
2x (cannot start with a digit), value of variable (spaces not allowed), val’s (quote not allowed).
Camel Case Notation
Java generally uses a special notation for naming variables, methods and classes. All class
names start with a Capital letter while variable and method names start with lower case letter.
If a variable or method or class name has more than one word, each first letter from the second
word onwards will be made capital. All constant variables are represented with all capital
letters. Consider the following examples:
intthisIsMyVariable; // starts with lower case since it is a variable
classMyClass; // starts with an upper case since it is class definition
MyClassmyClass; // starts with lower case since it is an object
voiddoItNow(); // starts with lower case since it is a method
public static final int MY_CONST = 10; // All upper case since it is a constant
This notation is followed throughout this text as far as possible.
Static methods and variable
Static storage contains data that is available for the entire time a program is running. Any static
data can be accessed just by using its containing class or package name plus a dot followed by
a variable name. There is no necessity of using an object to access static variables or methods.
However, static methods can access only the static data of that class. For example, the static
max() method of Math package can be accessed without creating a Math object like int x =
Math.max(10,20);
Constant storage: Constant values act as a definitions used in C/C++ which cannot be changed.
For example it is similar (but not exactly equals) to #define MY_CONST 10 in C which given
as final in the above example.
Final Variables
If some variables are to be kept constant, we use the keyword ‘final’ before it. By declaring a
variable final, the variable cannot be modified. Normally constants are declared as final. For
example:
Finalint MAX_VALUE = 20;
final float RATE_OF_INTEREST = 4.5f;
Here it is customary that constants are normally in upper case, but is not a rule. Once declared,
the variables cannot be modified. Hence, these variables must be initialized, while they are
declared. 17
Arrays
Virtually all languages support arrays. Using arrays in C and C++ is risky because those arrays
are only blocks of memory and there is no range checking or initialization. Hence, if an array
is used without initialization or if the index is out of bounds, the results are unpredictable. This
is one of the sources of errors in C programs.
A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The
range is checked for every access of any element of the array. When an array of primitive data
types are created, each element is initialized either to 0 or to empty value based on the data
type. When an array of objects is created, internally the program creates an array of handles,
and each of those handles is automatically initialized to a special value null. When Java sees
null, it recognizes that the handle is not pointing to any object.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What are the escape sequence characters?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

2.3 KEYWORDS,TYPE CONVERSIONS


Like every language .Java also has a set of reserved Words (Keywords): Java uses the following
words for specific purpose. These should not be used as identifiers (variable names) or for
other purposes.
Abstract boolean break byte case catch char class
Const continue default do double else extends final
Finally float for goto 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
The goto is implemented in C and C++ which transfer the control to the line that has a label
which is given in goto statement without respecting the structure of the program. This is the
reason why the use of goto is best avoided and in professional programs, it is not seen at all.
Though Java reserved this as keyword to be compatible with C, it is marked as unused and
hence it cannot be used in programs neither as a variable nor as a control statement.
LITERALS
Any constant value of any data type that can be assigned to an appropriate variable is called a
literal.
100(integer literal), 19.3 (double literal), ‘A’ (char literal), “Test String” (String literal) etc.
intintVal = 10; // Integer literal 10 is assigned to intVal variable
String str = “Test String”; // String literal is assigned to str variable
18
ESCAPE SEQUENCE CHARACTERS
There are certain characters that have special meaning in Java language like tab, newline etc.
If any of these special character is a part of a string literal or value of a character variable, they
must be escaped by a reverse slash (‘\’) to instruct the compiler that the next character should
be treated as normal value without any special meaning. Following table gives the characters
that should be escaped in literals.

Name Character ASCII

Backspace \b 8

TAB \t 9

NUL character \0 0

newline \n 10

carriage control \r 13

double quote \” 34

single quote \’ 39

backslash \\ 92

Examples:
Stingstr = “Double quote (\”) is escaped”; // double quote is escaped
charch = ‘\’’; // single quote is escaped
String str=”10\t20\30\n”; // Tab separated data terminated by newline
TYPE CASTING
There are cases where one data type is to be converted into another data type (for example, an
integer into a float). There are two cases while converting from one data type to another viz.,
implicit automatic conversion (known as type conversion) and explicit conversion (know as
casting). The explicitly conversion is possible using the casting, which is done using the
following syntax.
(new data type) <data or variable of old type>
Consider the following code piece:
int x=10;
long y;
float z=12.34f;
y = x;// Legal since int is promoted as long (conversion)
y = (long)x;// Legal since int is promoted as long (casting)
x=y;// Illegal since long is demoted as int
x= (int) y;// Legal since explicit casting is used (casting)
x = (int) z; // Legal since explicit casting is used with data loss
It is important to note that there may be data loss during casting, since the data is narrowed
sometimes. Further, the two data types must be compatible for type conversion. For example, 19
the following is not possible and gives an error:
int t = (int)”10"; // String cannot be directly converted to int
TYPE CONVERSION
Automatic conversion of data type is taken care when a variable of one data type is assigned a
value of other data type following the rules that the two data types are compatible and the new
data type is large enough to hold all the old data without any loss of bits and bytes. The
promotion rules are given in the “Type Promotion” section.
Examples:
NtintVal = 10;
LonglongVal = intVal; // Automatic conversion from int to long (data widening)
FloatfloatVal = longVal; // Automatic conversion from long to float (promotion)
TYPE PROMOTION
Java tries to convert the data automatically into the other data type if it is a promotion where
the two data types are compatible and the new data type is larger than the original data type.
Following are automatically converted (promoted) by compiler
· From a byte to a short, an int, a long, a float, or a double
· From a short to an int, a long, a float, or a double
· From a char to an int, a long, a float, or a double
· From an int to a long, a float, or a double
· From a long to a float or a double
· From a float to a double
The promotion from byte ->short->int->long is also known as widening since the basic data
type is still integer. Similarly float->double is also widening since the basic data type is still a
float value. However, conversion like int->float is promotion since the basic data type itself is
changed where the nature of int and float are different. Following is a simple program that
shows different conversions:
public class TestCasting{
public static void main(String[] args){
bytebval = 10;
charcval = ‘A’;
floatfval = 1.23f;
intival = bval; // Ok, promotion
System.out.println(“ival: “ + ival);
ival = 300;
bval = (byte) ival; // Value = 300%256 = 44 (data lost)
System.out.println(“bval: “ + bval);
ival = (int) fval; // Value = 1 (data lost)
System.out.println(“ival: “ + ival);

20
ival = cval; // Value = 65 (ASCII Value of ‘A’)
System.out.println(“ival: “ + ival);
}
}
Conversion from String to Numeric value
Java provides methods for converting a string into its equivalent number with wrapper classes.
For example the Integer class provides a method called parseInt to convert a string to integer.
Similar methods are available for converting to appropriate data type in other wrapper classes
like Float, Double, Long etc.
Examples:
String x = “123”; // sequence of characters ‘1’,’2' and ‘3’
String y = “234.567”; // sequence of characters ‘2’,’3',’4',’.’,’5',’6' and ‘7’
int i = Integer.parseInt(x); // Converts String x to integer
long l = Long.parseLong(x); // Converts String x to long number
float f = Float.parseFloat(y); // Converts string y to float
double d = Double.parseDouble(y); // Converts y to double
Converting Numeric Value to String
Any numeric value can be converted to String in different ways:
Method 1: The value may be added to an empty string (“”) to promote it as string.
String p = “”+i;
String q = “”+d;
Method 2: The String.valueOf() method may be used.
String p = String.valueOf(i);
String q = String.valueOf(d);
Method 3: The Wrapper class’s toString() method may be used.
String p = Integer.toString(i);
String q = Integer.toString(d);
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is type casting?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

2.4 SUMMARY
Data type defines the values that a variable can take, for example if a variable has int data
type, it can only take integer values. In java we have two categories of data type: 1) Primitive
data types 2) Non-primitive data types – Arrays and Strings are non-primitive data types, we 21
will discuss them later in the coming tutorials. Here we will discuss primitive data types and
literals in Java.
Java is a statically typed language. A language is statically typed, if the data type of a variable
is known at compile time. This means that you must specify the type of the variable (Declare
the variable) before you can use it.n Java, we have eight primitive data types: boolean, char,
byte, short, int, long, float and double. Java developers included these data types to maintain
the portability of java as the size of these primitive data types do not change from one operating
system to another.The promotion from byte ->short->int->long is also known as widening
since the basic data type is still integer. Similarly float->double is also widening since the
basic data type is still a float value. However, conversion like int->float is promotion since the
basic data type itself is changed where the nature of int and float are different

2.5. CHECK YOUR PROGRESS MODEL ANSWERS


1. Characters escaped by a reverse slash (‘\’) to instruct the compiler that the next character
should be treated as normal value without any special meaning.
2. Explicit type conversion know as type casting

2.6. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
1. Describe the primitive data types and their sizes in java.
2. Explain type conversion, type casting, type promotion with examples
3. List out the various keywords in java.
II. Answer the following questions in about 15 lines each
1. Describe variables and handlers with examples
2. Write a simple java program to read and print all primitive data types.
3. Describe Escape sequence characters in Java.

2.7.GLOSSARY
Class Method : A method that is invoked without reference to a
particular object. Class methods affect the class as a
whole, not a particular instance of the class.
Class Variable : A data item associated with a particular class as a
whole—not with particular instances of.
Classpath : An environmental variable which tells the Java virtual
machine Where tofindthe class libraries, including user-
defined class libraries
Declaration : A statement that establishes an identifier and associates
attributes with it, without reserving its storage (for data)
or providing the implementation (for methods).
Default : A Java keyword optionally used after all case conditions
in a switch statement. If all case conditions are not
matched by the value of the switch vari
22
UNIT-3: JAVA OPERATORS AND CONTROL
STATEMENTS
Contents
3.0 Objectives
3.1 Introduction
3.2 Operators
3.3 Cotrol Statements
3.4 Summary
3.5 Check your progress Model Answers
3.6 Model Examination Questions
3.7 Glossary

3.0. OBJECTIVES
After studying this unit, you should be able to
• understand Java language program constructs and expressions
• explain howto write and execute Java programs with simple to medium complexity,
• describe various operators in Java
• understand various control statements in Java

3.1. INTRODUCTION
Java provides various operators for various purposes. These operators can be classified broadly
into 4 categories according to their usage. These four groups are explained below. These
operators are useful when more than one condition is to be tested simultaneously. For example,
if there are two subjects, and a student is declared passed only when he clears both subjects.
That is, the student has to pass in first subject AND has to pass in second subject. This condition
is called AND condition. Similarly there are cases where we will be satisfied with either of the
given two choices (for example, coffee or tea). This is called OR condition. Following is the
full list of the logical operators available in Java. Java provides a rich set of bitwise operators,
which can be used to manipulate individual bits of a byte. This is necessary in case we are
representing data with only one bit (for example, the status of a file can be indicated with just
one bit(for example, 1 means file already in use and 0 means it is not in use). Similarly, in
embedded systems which have very small memory generally in the order of hundreds of bytes
to a few kilobites (compared to the order of GBs in PCs), each bit is valuable and hence bit
operations are a must if the target program is for embedded systems. Java is originally targeted
to be an embedded platform and hence fully supports the bit operations. Following is the list of
bitwise operators:

3.2. OPERATORS
Java provides various operators for various purposes. These operators can be classified broadly
into 4 categories according to their usage. These four groups are explained below:

23
Mathematical operators:
Mathematical operators are required for representing or computing mathematical formulae.
The various mathematical operators that are available in Java are:
+ (addition) - (subtraction / unary minus) * (multiplication)
/(division) % (modulus) ++ (increment)
—(decrement) += , -=, *=, /=, %= (arithmetic assignment operators)
The unary operators are attached to a variable as +x, -y, +10, -20 etc.
The assignment operators are shortcuts. For example, x +=10 is equivalent to x =x+10.
Increment and decrement operators have double syntax. They can be used on either side of a
variable, which, then decides whether it is used as post-operator or pre-operator.
Consider, x=10 and y = x++
In this case y is assigned the value of x first, and then x is incremented (y=10 and x=11). Here
++ is used as post-increment operator. It is equivalent to two statements as y=x; x++;
Now consider x=10 and y= ++x, which means first increment x and then assign the value to y
(x=11 and y=11). Here ++ is used as pre-increment operator. It is equivalent to x++; y=x;
Other operators are used for normal arithmetic operations. The set of arithmetic assignment
operators is a short form of the actual operation. For example, x +=2 is equivalent to x = x+2.
Following is a full example for pre and post increment operators
// Demonstrates the ++ and — operators
public class AutoInc {
public static void main(String args[]) {
int i = 1;
System.out.println(“i : “ + i);
System.out.println(“++i : “ + ++i); // Preincrement
System.out.println(“i++ : “ + i++); // Postincrement
System.out.println(“i : “ + i);
System.out.println(“—i : “ + —i); // Predecrement
System.out.println(“i— : “ + i—); // Postdecrement
System.out.println(“i : “ + i);
}
}
The output for this program is:
i:1
++i : 2
i++ : 2
i:3
—i : 2
24
i— : 2
i:1
Relational Operators
There is a set of operators in Java, which are used to compare two operands and return a
boolean true or false. These are
== (Equal), != (not equal), < (less than), > (greater than) <= (less than or equal), >= (greater
than or equal).
x (operator) y returns either TRUE or FALSE depending on the comparison that is used. For
example, if x=10 and y=20, then x>y returns FALSE while, y >x returns TRUE.
Logical Operators
These operators are useful when more than one condition is to be tested simultaneously. For
example, if there are two subjects, and a student is declared passed only when he clears both
subjects. That is, the student has to pass in first subject AND has to pass in second subject.
This condition is called AND condition. Similarly there are cases where we will be satisfied
with either of the given two choices (for example, coffee or tea). This is called OR condition.
Following is the full list of the logical operators available in Java.
! logical NOT
|| Logical OR
&& Logical AND
Following program gives examples for various logical operators:
importjava.util.*;
public class Bool {
public static void main(String args[]) {
int i = 10;
int j = 20;
System.out.println(“i = “ + i);
System.out.println(“j = “ + j);
System.out.println(“i > j is “ + (i > j));
System.out.println(“i < j is “ + (i < j));
System.out.println(“i >= j is “ + (i >= j));
System.out.println(“i <= j is “ + (i <= j));
System.out.println(“i == j is “ + (i == j));
System.out.println(“i != j is “ + (i != j));
System.out.println(“(i < 10) && (j < 10) is “
+ ((i < 10) && (j < 10)) );
System.out.println(“(i < 10) || (j < 30) is “
+ ((i < 10) || (j < 30)));
}
} 25
Output listing looks like this:
i = 10
j = 20
i > j is false
i < j is true
i >= j is false
i <= j is true
i == j is false
i != j is true
(i< 10) && (j < 10) is false
(i< 10) || (j < 30) is true
Note that a boolean value is automatically converted to “true” or “false”if it is printed as
string. Variable i can be replaced with any other primitive data type except boolean. Be aware,
that the comparison of floating-point numbers for equality is not guaranteed due to the nature
of storing a floating point number. Even a tiniest fraction difference is still “not equal”.
Bitwise operators
Java provides a rich set of bitwise operators, which can be used to manipulate individual bits
of a byte. This is necessary in case we are representing data with only one bit (for example, the
status of a file can be indicated with just one bit(for example, 1 means file already in use and
0 means it is not in use). Similarly, in embedded systems which have very small memory
generally in the order of hundreds of bytes to a few kilobites (compared to the order of GBs in
PCs), each bit is valuable and hence bit operations are a must if the target program is for
embedded systems. Java is originally targeted to be an embedded platform and hence fully
supports the bit operations. Following is the list of bitwise operators.
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ exclusive OR (XOR)
>> Shift right
<< Shift left
>>> Shift right zero fill
&=, |=, ^=, >>=, <<=, >>>= Operate and then assign
The bitwise AND operator (&) results in 1 if both input bits are 1, otherwise results in 0. The
bitwise OR operator (|) results in 1 if either input bit is 1 andresults in 0 only if both input bits
are 0s. The bitwise XOR (^) results in 1 if only one of the input bits is 1, but not both. The
bitwise NOT (~) is a unary operator and invert the bit (1 is made 0 and 0 is made 1).
Bitwise operators can be clubbed with the = sign to operate and then assign: &=, |= and ^= are
all legitimate. (Since ~ is a unary operator itcannot be combined with the = sign.)
The boolean type is treated as a single bit value and hence it is treated differently. Bitwise
AND, OR and XOR can be performed but a bitwise NOT can’t be performed to prevent
duplication with the logical NOT. Using shift expressions is not allowed on boolean values
26
since there only one bit.
Shift operators
The shift operators can be used only on primitive integer types. These operators shift the bits
of the number to left(<<) or right (>>) by a number of bits given after the operator. When the
bits are shifted some bits are overflowed and some empty bits will be added. The overflowed
bits are ignored and empty bits are replaced with zeros. There is an unsigned right shift
operator (>>>) which shifts the sign bit also to the right which not available in C/C++.
Shifts can be combined with the equal sign (<<=,>>=,>>>= etc.). The left value is replaced by
the left value shifted by the right value. Here’s an example that demonstrates the use of all the
operators involving bits:
// Using the bitwise operators
public class BitManipulation {
public static void main(String args[]) {
int i = 59081716;
int j = 198850956;
intmaxpos = 2147483647;
intmaxneg = -2147483648;
printBinary(“-1”, -1);
printBinary(“+1”, +1);
printBinary(“maxpos”, maxpos);
printBinary(“maxneg”, maxneg);
printBinary(“i”, i);
printBinary(“~i”, ~i);
printBinary(“-i”, -i);
printBinary(“j”, j);
printBinary(“i & j”, i & j);
printBinary(“i | j”, i | j);
printBinary(“i ^ j”, i ^ j);
printBinary(“i << 5”, i << 5);
printBinary(“i >> 5”, i >> 5);
printBinary(“(~i) >> 5”, (~i) >> 5);
printBinary(“i >>> 5”, i >>> 5);
printBinary(“(~i) >>> 5”, (~i) >>> 5);
}
static void printBinary(String message, intval)
{System.out.print( message + “: “ + val + “ Binary: “);
String str = Integer.toBinaryString(val);
String x = “”;
for(int i=0; i<32-str.length(); i++) x += “0”;
27
x += str;
System.out.println(x);
}
}
Note the use of System.out.print() instead of System.out.println(). The print() method continues
on the same line until a println() or a newline (“\n”) is printed. The leftmost bit represents the
sign, 0 means positive and 1 means negative. To print the bits, the built-in function from
Integer class is used along with logic to fill zeros before the actual value. The output looks like
this:
-1: -1 Binary: 11111111111111111111111111111111
+1: 1 Binary: 00000000000000000000000000000001
maxpos: 2147483647 Binary: 01111111111111111111111111111111
maxneg: -2147483648 Binary: 10000000000000000000000000000000
i: 59081716 Binary: 00000011100001011000001111110100
~i: -59081717 Binary: 11111100011110100111110000001011
-i: -59081716 Binary: 11111100011110100111110000001100
j: 198850956 Binary: 00001011110110100011100110001100
i& j: 58720644 Binary: 00000011100000000000000110000100
i | j: 199212028 Binary: 00001011110111111011101111111100
i ^ j: 140491384 Binary: 00001000010111111011101001111000
i<< 5: 1890614912 Binary: 01110000101100000111111010000000
i>> 5: 1846303 Binary: 00000000000111000010110000011111
(~i) >> 5: -1846304 Binary: 11111111111000111101001111100000
i>>> 5: 1846303 Binary: 00000000000111000010110000011111
(~i) >>> 5: 132371424 Binary: 00000111111000111101001111100000
Ternary if-else operator (?:)
This operator is unusual because it has three operands. It is truly an operator because it produces
a value, unlike the ordinary if-else statement that you’ll see later in this chapter. The expression
is of the form
boolean-exp ?value0 : value1
If boolean-exp evaluates to true, value0 becomes the value produced by the operator. If boolean-
exp is false, value1 is produced by the operator.
Here’s an example:
Staticintmax(int x, int y)
{
return x > y ? x: y;
}
Another example that limits a value to a maximum of 10
28
int x = (y<10)?y:10; // either y or maximum 10
The code is more compact than using if else structure:
Staticintmax(intx, int y)
{
if (x > y)
returnx;
else
returny;
}
Though the ternary operator is used for efficiency reasons and for compact code, it is advised
to use the second method if clarity of the program is important.
The comma operator
The comma is used in C and C++ and Java as an operator for sequential evaluation. The sole
place that the comma operator is used in Java is in for loops. Comma operator can be used as
follows:
for(i=0,j=1; i<20; i++, j—) {….}
Here for loop expects only one initialization, where as two initializations are given here with
a comma operator. Similarly it expects one increment or decrement, but two operations are
given here (i++ and j—) with a comma operator.
String operator +
There’s one special usage of an operator in Java: the + operator can be used to concatenate
strings, as was seen in previous examples. The + operator seems normal for strings, though it
doesn’t fit with the traditional way that + is used. If an expression begins with a String, then all
operands that follow will be converted to strings automatically using their internal “toString()”
method.
int x = 0, y = 1, z = 2;
String sString = “x, y, z “;
System.out.println(sString + x + y + z);
Here, the Java compiler will convert x, y, and z into their String representations instead of
adding them together first.
Operator Precedence
Operator precedence determines how the given expression should be evaluated. For example,
10/2+3 may give 8 if the equation is evaluated as 10/2 and then add 3 to it. On the other hand,
if the equation is considered as 10 divided by (2+3), the answer is 2. In such cases, the compiler
first evaluates the operator that has higher precedence. The list of operators with precedence
from highest to lowest is as follows:

29
() []
++ — ~ !
* / %
+ -
>>>>><<
>>= <<=
== !=
&
^
|
&&
||
?:
= operator= (+=, *= , ...)

It is advised to use the parenthesis for safety in case of complex expressions to avoid wrong
interpretation by the compiler.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. List the relational operators in Java?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

3.3. CONTROL STATEMENTS


In Java, the keywords for controlling the flow of the program include if-else, while, do-while,
for, and a selection statement called switch. Java does not support the gotobut a workaround is
suggested which is much more constrained than a typical goto. Without any control statement,
the program is executed from first line to the last line in the same sequence.
true and false
All conditional statements are evaluated to true or false. An example of a conditional expression
is A == B. This uses the conditional operator == to see if the value of A is equivalent to the
value of B. The expression returns true or false depending on the values of A and B. Note that
Java doesn’t allow a number as a boolean unlike C and C++ (where a nonzero number is true
and zero is false).
if-else
The if-else statement is probably the most basic way to control program flow. The else is
optional, so you can use if in two forms:
30
if(Boolean-expression)
statement
or
if(Boolean-expression)
statement
else
statement
The condition must produce a Boolean result. The statement means either a simple statement
terminated by a semicolon or a compound statement (a group of simple statements enclosed in
curly braces). As an example of if-else, here is a test() method that will tell you whether a
guess is above, below, or equivalent to a target number:.
staticint test(inttestval) {
int result = 0;
if(testval> target)
result = -1;
else if(testval< target)
result = +1;
else
result = 0; // match
return result;
}
Note the use of multiple conditions with (if, else if and else). It is conventional to indent the
body of a control flow statement so the reader might easily determine where it begins and
ends. It is also a good practice to use curly braces around the statement even if it is a simple
statement.
return
The return keyword causes a value to be returned to the calling statement if it is supposed to
return a data type. With void type methods, the return statement simply terminates the method.
The test() method above can be rewritten to take advantage of this:
staticint test2(inttestval) {
if(testval> target)
return -1;
if(testval< target)
return +1;
return 0; // match
}
There’s no need for else because the method will not continue after executing a return.
Iteration
while, do-while and for control looping and are sometimes classified as iteration statements . 31
A statement repeats until the controlling Boolean-expression evaluates to false. The form for a
while loop is
While loop
while(Boolean-expression)
statement
The Boolean-expression is evaluated at the beginning of the loop every time. If the expression
results in a true, the loop statement(s) are executed. Here’s a simple example that generates
sequential numbers until a particular condition is met:

// Demonstrates the while loop


public class WhileTest {
public static void main(String[] args) {
int i = 0;
while(i <100) {
i++;
System.out.println(i);
}
}
}
The conditional expression for the while says “keep doing this loop as long as the number is
less than 100”.
do-while loop
The form for do-while is
do
statement
while(Boolean-expression);
The sole difference between while and do-while is that the statement of the do-while always
executes at least once, even if the expression evaluates to false the first time. In a while, if the
conditional is false the first time the statement is never executed. In practice, do-while is less
common than while. Normally the do-while is used where the loop has to be executed at least
once, as in menu programs, where the user is supposed to select at least the exit from the
menu.
Care must be taken while using a ‘while’ or ‘do-while’ loop so that it will not go into an
endless loop. Within the body of the structure, there should be a way to make the condition
false somehow.
For loop
For loop is the most used iteration structure in any programming language. It is useful whenever
the statement is executed for a definitive number of times. It also simplifies the initialization
and increment/decrement operations as they are inserted in the for loop itself. A for loop
performs initialization before the first iteration. Then it evaluates the condition or boolean
32 expression and if the result is true, it executes the statement. After the statement is executed, it
performs an increment or decrement operation and then tests the condition again. The syntax
of for loop is:
for(initialization; Boolean-expression; step)
statement
Any of the three expressions viz., initialization, Boolean-expression or step can be empty. The
expression is tested before each iteration, and if the result is false, execution will continue at
the line following the ‘for’ statement. At the end of each loop, the step executes. for loops are
usually used for “counting” tasks:
/*Demonstrates “for” loop by printingall the ASCII characters
except character 26 which is End of File (^Z).
*/
public class ListCharacters {
public static void main(String[] args) {
for(char c = 0; c < 128; c++){
if(c != 26 ){ // ANSI Clear screen
System.out.println(“” + (int)c + “ — “ + c);
}
}
}
}
Note that the variable c is defined at the point where it is used, inside the control expression of
the for loop, rather than at the beginning of the block denoted by the open curly brace. The
scope of c is the expression controlled by the ‘for’ loop.In Java and C++ variables can be
declared anywhere within the block unlike C (where variables should be declared at the begin
of the block). This allows a more natural coding style and makes code easier to understand.
Multiple variables can be defined within a ‘for’ statement, but they must be of the same type:
for(int i = 0, j = 1;i < 10 && j != 11; i++, j++)
/* body of for loop */;
The int definition in the ‘for’ statement covers both i and j. The ability to define variables in
the control expression is limited to the for loop only. This approach cannot be used with any of
the other selection or iteration statements.
for each loop
This is a variation of a ‘for’ loop which is useful when a specific task is to be done on an array
of data. It takes the following form:
for(DataTypevaraiable:dataCollection)
/* body of for loop where variable is used*/;
Here the variable is assigned one item from collection in the same sequence and there is no
need for checking condition like i<collection.length; i++ etc. The collection can be an array of
any data type, an ArrayList, a List or a Vector. Following example prints all the numbers of an
array
33
public class ForEachTest {
public static void main(String[] args) {
intarr[] = {1,3,4,6,7,8,10};
for(int i:arr){
System.out.println(i);
}
}
}
Here the variable iis of the same data type as that of arr and it should be declared within for
loop only. For each iteration, i is assigned the next value from the array and will be printed.
break and continue
Inside the body of any of the iteration statements you can also control the flow of the loop by
using break and continue. break quits the loop without executing the rest of the statements in
the loop. continue stops the execution of the current iteration and goes back to the beginning
of the loop to begin a new iteration.
This program shows examples of break and continue within for and while loops:
// Demonstrates break and continue keywords
// Prints all even numbers within 1 to 9 with a for loop
// and then with a while loop
public class BreakAndContinue {
public static void main(String[] args) {
int i;
for(i = 0; i < 10; i++) {
if(i == 9) break; // Out of for loop
if(i % 2 != 0) continue; // Skip to next iteration
System.out.println(i);
}
i = 0;
// An “infinite loop”:
while(true) {
i++; // Increment i
if(i == 10) break; // Out of loop
if(i % 2 != 0) continue; // Top of loop
System.out.println(i);
}
}
}
34
In the for loop the value of i never gets to 10 because the break statement breaks out of the loop
when i is 9. Normally, a break is used when there is no point in continuing further. For example,
an array contains 100 integers and it should be searched for the first occurrence of a specific
number. The process is to start search with first number and continue till the last number or till
the value is found. Hence, within the for loop, if the value matches, the loop is terminated with
break. The continue statement causes execution to go back to the top of the iteration loop (thus
incrementing i) whenever i is not evenly divisible by 2. When it is even, the value is printed.
The second portion shows an “infinite loop” that would, in theory, continues forever. However,
inside the loop there is a break statement that will break out of the loop. In addition, the
continue moves back to the top of the loop without completing the remainder (thus prints only
when the value of i is divisible by 2).
A second form of the infinite loop is for(;;). The compiler treats both while(true) and for(;;) in
the same way and hence, it is a matter of programmer’schoice.
Named break and continue
The goto keyword has been present in programming languages from the beginning which has
its genesis from assembly language (in the form of jump). “if condition A, then jump here,
otherwise jump there”. Although goto is a reserved word in Java, it is not used in the language;
Java has no gotobut it has a similar but restricted jump around statement in the form of named
break and continue statements. In java a lable can be declared as unique label name followed
by a colon, like this:
myLabel:
The only place a label is useful in Java is just before an iteration statement without anything
between the label and the iterative statement. And the sole reason to put a label before an
iteration is if you’re going to nest another iteration or a switch inside it. That’s because the
break and continue keywords will normally interrupt only the current loop, but when used
with a label they’ll interrupt the loops up to where the label exists:
label_1:
outer-iteration {
inner-iteration {
//...
break; // 1 inner loop break
//...
continue; // 2 inner loop continue
//...
continue label_1; // 3 Outer loop continue
//...
break label_1; // 4 Outer loop break
}
}
In case 1, the break breaks out of the inner iteration and you end up in the outer iteration. In
case 2, the continue moves back to the beginning of the inner iteration. But in case 3, the
continue label1 breaks out of the inner iteration and the outer iteration, all the way back to
label1. Then it does in fact continue the iteration, but starting at the outer iteration. In case 4, 35
the break label1 also breaks all the way out to label1, but it does not re-enter the iteration. It
actually does break out of both iterations. Here is an example using for loops:
// Java’s “labeled for loop”
public class LabeledFor {
public static void main(String args[]) {
int i = 0;
outer: // Can’t have statements here
for(; true ;) { // infinite loop
inner: // Can’t have statements here
for(; i < 10; i++) {
output(“i = “ + i);
if(i == 2) {
output(“continue”);
continue;
}
if(i == 3) {
output(“break”);
i++; // Otherwise i never gets incremented.
break;
}
if(i == 7) {
output(“continue outer”);
i++; // Otherwise i never gets incremented.
continue outer;
}
if(i == 8) {
output(“break outer”);
break outer;
}
for(int k = 0; k < 5; k++) {
if(k == 3) {
output(“continue inner”);
continue inner;
}
}
}
36 }
// Can’t break or continue to labels here
}
static void output(String s) {
System.out.println(s);
}
}
Note that break breaks out of the for loop, and that the increment-expression doesn’t occur
until the end of the pass through the for loop. Since break skips the increment expression, the
increment is performed directly in the case of i == 3. The ‘continue outer’ statement in the
case of i == 7 also goes to the top of the loop and also skips the increment, so it too is incremented
directly.
Here is the output:
i=0
continue inner
i=1
continue inner
i=2
continue
i=3
break
i=4
continue inner
i=5
continue inner
i=6
continue inner
i=7
continue outer
i=8
break outer
If not for the break outer statement, there would be no way to get out of the outer loop from
within an inner loop, since break by itself can break out of only the innermost loop. (The same
is true for continue.). Of course, in the cases where breaking out of a loop will also exit the
method, you can simply use a return.
Switch statement
The switch is sometimes classified as a selection statement. The switch statement selects from
among pieces of code based on the value of an integeror string expression. Its form is:
switch(selector) {
37
case value1 : statement; break;
case value2 : statement; break;
case value3 : statement; break;
case value4 : statement; break;
case value5 : statement; break;
// ...
default: statement;
}
Selector is an expression that produces an integer or string value. C/C++ doesn’t support
string as a selector and Java started supported it from version 5. The switch compares the
result of selector to each value defined in case statements. If it finds a match, the execution
starts at the corresponding statement (simple or compound).If no match occurs, the default
statement is executed.
Notice that the definition of each case ends with a break, which causes execution to jump to
the end of the switch body. This is the conventional way to build a switch statement, but the
break is optional. If it is missing, the code for the following case statements execute until a
break is encountered. Although usually this kind of behavior is not required, it can be useful to
an experienced programmer. Note the last statement, for the default, doesn’t have a break
because the execution just falls through to where the break would have taken it anyway. There
is no effect of a break at the end.
The switch statement is a clean way to implement multi-way selection which otherwise requires
multiple if else if conditions. Here’s an example that creates letters randomly and determines
whether they’re vowels or consonants:
// Demonstrates the switch statement
public class VowelsAndConsonants {
public static void main(String[] args) {
for(int i = 0; i <26; i++) {
char c = i + ‘a’;
System.out.print(c + “: “);
switch(c) {
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
System.out.println(“vowel”);
break;
case ‘y’:
case ‘w’:
38 System.out.println(“Vowel sometimes”);
break;
default:
System.out.println(“consonant”);
}
}
}
}
Although it appears this program is switching on a character here, the switch statement is
actually using the integral value of the character. The single quoted characters in the case
statements also produce integral values that are used for comparison. Notice how the cases can
be “stacked” on top of each other to provide multiple matches for a particular piece of code
(without break statement).
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What os the switch statement?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

3.3. SUMMARY
This chapter introduces the data types and control structures available in Java. Data conversion
from one type to another type is explained along with promotion rules and precautions to be
taken to prevent possible data loss. Various examples are given for each control structure.The
goto keyword has been present in programming languages from the beginning which has its
genesis from assembly language (in the form of jump). “if condition A, then jump here, otherwise
jump there”. Although goto is a reserved word in Java, it is not used in the language; Java has
no gotobut it has a similar but restricted jump around statement in the form of named break
and continue statements. In java a lable can be declared as unique label name followed by a
colon, lSelector is an expression that produces an integer or string value. C/C++ doesn’t support
string as a selector and Java started supported it from version 5. The switch compares the
result of selector to each value defined in case statements. If it finds a match, the execution
starts at the corresponding statement (simple or compound).If no match occurs, the default
statement is executed.

3.4. CHECK YOUR PROGRESS MODEL ANSWERS


1.<,>,<=,>=.==.I=
2. It is a multi-branching statement

39
3.5. MODEL EXAMINATION QUESTIONS
I. Answer the following questions in about 30 lines each
1. Write a java program that reads the percentage of marks and declares the grade following
the rule (Distinction: >=70%, First class: >= 60%, Second class: >= 50% and fail
otherwise)
2. Write a program that prints a triangle with stars from 1 to 5 using (a) for loop and (b)
while loop as shown below (stars must be centered vertically by calculating the space
required before the stars):
*
***
*****
3. Write a program that reads two names from keyboard and prints them alternatively for
10 times (if count is odd, print first name, otherwise print second name).
II. Answer the following questions in about 15 lines each
1. Write a program that reads a value and tells if it is an even or odd number.
2. Read 10 numbers from keyboard and print the maximum, minimum and average of
these numbers
3. Describe Bitwise operators with an example java program.

3.6. GLOSSARY
Class Method : A method that is invoked without reference to a
particular object. Class methods affect the class as a
whole, not a particular instance of the class.
Break : Exit from the loop
Continue : Skip the iteration which meets certain conditon
Operator Precedence : List the operators in the order of priority for evaluating
expressions.
String Operator : Print the values of numeric variables as characters

40
BLOCK - II

JAVA AND OOPs


This block gives an overall study on defining classes, objects, and oops concepts such as
encapsulation, inheritance, polymorphism, dynamic bindingusing new operator, defining
object references, methods, box class, types of constructors, this key word,.instance variable
hiding, garbage collection, finalize method, stack class. It also enables the students to
understand how towrite programs of overloading methods and constructors, using access
controls, final method, static method, static variables nested and inner classes, string class,
operations on strings, command line arguments with vararg. This block explains member
access & inheritance, subclass and super class, second use for super, multi-level hierarchy,
method overriding, dynamic method dispatching, abstract classes, and using final with
inheritance.

The units included in the block are:


Unit-4: Introduction to Classes and Objects
Unit-5: Additional Features of Java OOPs
Unit-6: Inheritance and Abstract Classes

41
42
UNIT-4: INTRODUCTION TO CLASSES AND OBJECTS
Contents
4.0 Objectives
4.1 Introduction
4.2 Java classes and objects
4.3 Box and Unbox, Constructors
4.4 Garbage collection and Finalize Method
4.5 The Stack Class
4.6 Summary
4.7 Check your progress Model Answers
4.8 Model Examination Questions
4.9 Glossary

4.0. OBJECTIVES
After studying this unit, you should be able to
• Explain how classes are declared in Java and how to create objects of this class
• Descr9he some important implementations specific to object oriented programming
• Understand this keyword.
• The garbage collection feature of Java is also explained in this chapter.

4.1. INTRODUCTION
In object oriented programming, classes are the definition of an entity which contains data and
operations that can be performed with the data. This is unlike C which is procedural language
where data and methods to manipulate data are defined independently. When a class is defined,
it is like a blueprint for a design or a plan for a building. A class can hold two types of elements:
data members and method (function) members. Methods in classes have access to the object
data directly. The code of the method is shared among all objects of the same class but data
part is different for each object. A method is same as a function definition in C/C++. A member
has a name, parameters and a return type. For example, the Box class may contain methods to
access data or process and return data. In programming, when a variable is created, memory is
allocated and these must be destroyed to release the memory. Programmers know about the
importance of initialization, but often forget the importance of cleanup. In C or C++ this is
done by the use of free or delete. Java has the garbage collector to reclaim the memory of
objects that are no longer used. The garbagecollector is automatically initiated by the runtime
environment whenever it feels apt. Since the finalize method is called just before garbage
collector is run, it may not be called if garbage collector is not run because there is plenty of
memory available making garbage collection unnecessary.

4.2. CLASSES AND OBJECTS


In object oriented programming, classes are the definition of an entity which contains data and
operations that can be performed with the data. This is unlike C which is procedural language 43
where data and methods to manipulate data are defined independently. When a class is defined,
it is like a blueprint for a design or a plan for a building. To use a class, it must be realized first
like manufacturing the product or constructing a building using the blueprint or plan respectively.
Any number of same product or buildings can be built using the same blueprint and all of them
look exactly alike. In programming a class is a template for objects and an object is an instance
of a class. When many objects are created using a class, they inherit all the variables and
methods from the class definition.
The new Operator
Like many object-oriented languages, Java also uses the keyword class to create new data
types. The class keyword is followed by the name of the new type. For example:
class NewTypeName { /* data and code here */ }
This introduces a new type, so you can now create an object of this type using the new operator
as follows:
NewTypeName a = new NewTypeName();
Here the variable ‘a’ is a handle (reference) to the object that is created by new. This handle or
reference is used to refer to the particular object of the type NewTypeName. Data elements
defined in the class definitions are created for each object separately. This is known as data
isolation which is a fundamental feature of any OOP.
Object References
As mentioned earlier when an object is created with new necessary space will be allocated in
the memory and a reference to this memory is returned by new, which should be stored in a
reference variable of this type. If this reference is not stored or inaccessible, the object is lost
which still will be in the memory which causes memory leak. Each object created must be held
with a separate reference handler (variable). Member data or methods of an object can be
accessed with reference.variable or method name. Consider the following example:
public class Box {
int height, width, depth;
}
Now objects of type Box can be created with:
Box b1 = new Box ();
Box b2 = new Box ();
Here b1 and b2 both contain height, depth and width data specific to them. Hence, b1.height is
different from b2.height and so on. Java guarantees to initialize primitive values. So height,
depth and width of each object are initialized to 0.
Methods
A class can hold two types of elements: data members and method (function) members. Methods
in classes have access to the object data directly. The code of the method is shared among all
objects of the same class but data part is different for each object.
A method is same as a function definition in C/C++. A member function has a name, parameters
and a return type. For example, the Box class may contain methods to access data or process
and return data. Following modification to the Box class makes it practical.
/**
44 * This class demonstrates the use of data and methods
*/
public class Box {
int width, height, depth; // Variables to hold length and width
/**
* Method that initializes the data
*@param h height of the box
*@param w Width of the box
*@param d Depth of the box
*/
public void setSize(int h, int w, int d)
{
height= h;
width = w;
depth = d;
}
// Returns the volume of the rectangle
public int getVolume() {
return length*width*height;
}
// Main method that tests the class
public static void main(String args[])
{
Box b1 = new Box (); // Create Box object and assign it to b1
Box b2 = new Box ();
b1.setSize(5, 10, 4); // H, W and D of box 1
b2.setSize(10,20, 5);
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
The above class definition introduces some important features of Java. The first one is the
comment style (/** … */). This is specific to Java where the content of each such comment is
extracted and a help document is automatically created using ‘javadoc’ command which creates
an HTML file for each class. Javadoc comments can contain annotations like @param and
@return which are formatted properly by javadoc tool.
Here the data can be initialized directly as b1.height = 5, … However, java can hide this data
by declaring a variable’s scope as “private” to make the class more secure. In such case, only
public members can be accessed and the only way to set data will be to use setSize() method.
45
Similarly, the class also defines a method to process the data called getVolume() which computes
the volume and returns it to the calling program. Note that b1.getVolume() and b2.getVolume
() return appropriate volumes.
The main method may be given in the same class as a static member or a separate class can be
created to create objects of type Box as shown below:
class BoxTest {
// Main method that tests the class
public static void main(String args[])
{
Box b1 = new Box (); // Create Box object and assign it to b1
Box b2 = new Box ();
b1.setSize(5, 10, 4); // H, W and D of box 1
b2.setSize(10,20, 5);
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
Now BoxTest may be run because it has its own main method which is the entry point for the
application.
The ‘this’ Key Word
It was mentioned earlier that methods are shared among objects and data is different. When
the method is same, how can getVolume() method distinguishes the data of b1 and b2? This is
done though an internal reference known as ‘this’ which references the current object. In fact
when a variable is accessed within the program, all class variables are automatically accessed
with ‘this.variable’ internally. Similarly when the user calls a method of the class over an
object the ‘this’ reference is automatically passed to it internally thus eliminating any confusion.
In the above example, when b1.getVolume() is called, the statement ‘return height*width*depth’
takes the form ‘this.height*this.width*this.depth’, where this refers to b1 (current object).
Similarly consider a small change in the setSize() method as follows:
public void setSize(int height, int width, int depth)
{
height = height;
width = width;
depth = depth;
}
The use of height, width and depth on the left side is ambiguous since there are data members
called height, width and depth as well as local variables called height, width and depth. To
avoid confusion, the data members are prefixed explicitly as:
public void setSize(int height, int width, int depth)
46
{
this.height = height;
this.width = width;
this.depth = depth;
}
Now the compiler can treat the variables properly.
Instance Variable Hiding
If a local variable exists in a method with same name as that of an instance variable, then the
local variable hides or shadows the instance variable. If instance variable is to be accessed,
where a local variable with the same name also exists, the instance variable should be prefixed
with “this.’ as shown in the above example.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What do you mean by instance variable hiding?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

4.3.BOX AND UNBOX, CONSTRUCTORS


BOX AND UNBOX
Java provides wrapper classes for various primitive data types (Byte, Character, Short, Integer,
Long, Float, Double corresponding to byte, char, short, int, long, float and double respectively).
Wrapper class objects wrap a primitive data type within them. Converting primitive data type
to object is called auto boxing and converting an object into corresponding primitive data type
is known as auto unboxing.
Example
public class BoxTest {
public static void main (String args[]){
Integer obj = new Integer(12345);
int i = obj; // Unboxing
System.out.println(i);
obj = 54321; // Boxing
System.out.println(obj);
}
}
Output of the program is as shown below:
12345
54321 47
Note the automatic conversion from object to primitive data type (obj->i) and vice versa (i-
>obj).
CONSTRUCTORS
Normally it is expected that any variable or object is initialized to a proper value before it is
used. To guaranty that a variable is initialized, an automatic function, which will be run
immediately when an object is created, should be written. In Java, the class designer can
guarantee initialization of every object by providing a special method called a constructor. If
a class has a constructor, Java automatically calls that constructor when an object is created,
before users can even get their hands on it. So initialization is guaranteed. The name of the
constructor is the same as the name of the class. It makes sense that such a method will be
called automatically on initialization. A constructor should have no return type defined (not
even void). Use of any return statement gives an error during compilation itself. Note that the
coding style of making the first letter of all methods lower case does not apply to constructors,
since the name of the constructor must match the name of the class exactly.
Java provides three types of constructors viz., default constructor, no arguments constructor
and constructors with arguments.
Default Constructor
The original example of Box shown above has no constructor. In such a case a default constructor
is automatically created with code of initializing the data elements of the object. In the above
example, the values are automatically set to zeros. If the user creates at least one constructor
inside the class, the default constructor is not created automatically.
Constructor with no arguments
Here’s the Box class with a no arguments constructor:
/**
* This class demonstrates the use of no arguments constructor
*/
public class Box {
int width, height, depth; // Variables to hold length and width
/**
* No arguments Constructor
*/
public Box() {
width = 5;
height= 5;
depth = 5;
}

/**
* Method that initializes the data
*@param h height of the box
48 *@param w Width of the box
*@param d Depth of the box
*/
public void setSize(int h, int w, int d){
height= h;
width = w;
depth = d;
}
// Returns the volume of the rectangle
public int getVolume() {
return length*width*height;
}
// Main method that tests the class
public static void main(String args[]){
Box b1=new Box();// Create Box object and assign it to b1
Box b2 = new Box();
b2.setSize(10,20,5);
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
Now, when an object is created by the syntax “new Box(); “, storage is allocated and the
constructor is called. It is guaranteed that the object will be properly initialized (height, width
and depth to 5 each) before anything is done with the object.
Like any method, the constructor can have arguments to specify how an object is created.
These arguments provide a way to initialize an object. For example, if the Box has a constructor
that takes height, width and height as arguments/parameters, a Box object can be created as
shown in the example.
Constructor with parameters (arguments)
Here’s the Box class that implements constructor with arguments:
/**
* This class shows the use of constructor with arguments
*/
public class Box {
int width, height, depth; // Variables to hold data
/**
* Constructor with parameters
*@param h Height of the box
49
*@param w Width of the box
*@param d Depth of the box
*/
public Box(int h, int w, int d) {
width = w;
height= h;
depth = d;
}
// Returns the volume of the rectangle
public int getVolume() {
return length*width*height;
}
// Main method that tests the class
public static void main(String args[])
{
Box b1 = new Box (5,10,15); // Create Box object b1
Box b2 = new Box (2,3,4); // Create Box b2
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is constructor?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

4.4.GARBAGE COLLECTION AND FINALIZE METHOD


In programming, when a variable is created, memory is allocated and these must be destroyed
to release the memory. Programmers know about the importance of initialization, but often
forget the importance of cleanup. In C or C++ this is done by the use of free or delete. Java has
the garbage collector to reclaim the memory of objects that are no longer used. The garbage
collector is automatically initiated by the runtime environment whenever it feels apt. Since the
finalize method is called just before garbage collector is run, it may not be called if garbage
collector is not run because there is plenty of memory available making garbage collection
unnecessary. Java provides a static method in System to request the system to initiate garbage
50
collection which in general will be obliged by the system. However, in some cases, it may not
respect the request, since garbage collection is an independent process by itself.
THE FINALIZE METHOD
In some cases the user may wish to do something just before garbage collection removes an
unused object, like disconnecting from database, closing a network connection etc. The garbage
collector knows only how to release memory allocated with new, so it won’t know how to
release the object’s “special” memory which may be allocated by database or network
connection. To handle this case, Java provides a special method called finalize() that can be
defined within a class. When the garbage collector is ready to release the storage used for your
object, it will first call finalize(), and only on the next garbage-collection pass will it reclaim
the object’s memory. So the finalize() gives the ability to perform some important cleanup at
the time of garbage collection. If there is some activity that must be performed before the
object is no longer needed it must be performed explicitly by calling the finalize method since
Java has no destructor or similar concept. The finalize method has the following format:
protected void finalize() throws Throwable
Observe that the method may throws an exception which will be explained later. For now, the
method should be declared as it is defined.
Example
public class FinalizeTest {
protected void finalize(){
System.out.println(“finalize method called”);
}
public static void main(String[] args) {
FinalizeTest obj = new FinalizeTest();
System.out.println(obj.hashCode());
obj = null;
System.gc();// calling garbage collector
System.out.println(“end of garbage collection”);
}
}

4.5.THE STACK CLASS


In object oriented programming, classes are the core component, where data and its manipulation
methods are defined. A good class should be self contained as far as possible. Though the Box
class described above gives an overall idea of what a class is, it will not cover the manipulation
part. To illustrate this concept, a Stack class is presented here. The Stack is a “Last In First
Out” mechanism, just like a stack of plates arranged for a buffet. The last plate (top plate) is
the first to be lifted. This is very useful in system programming, compiler design and may also
be used to reverse any order. A stack has basically two operations, push and pop, where a push
inserts a data element at the top while the pop extracts the top element. In this example, a stack
of integers is created using an internal integer array which is not exposed to the programmer.
The programmer simply uses the object of Stack type to use it. The size of stack is limited to
the predefined constant (5 in the program).
51
public class Stack {
public static final int MAX = 5;
public static final int ERROR = -999;
int array[];
int top;
// No argument constructor
public Stack()
{
array = new int[MAX];
top = 0;
}
// Push operation
public void push(int number) {
if(top < MAX) {
array[top] = number;
System.out.println(“Pushing value: “ + number);
top++;
}
else {
System.out.println(“Stack full. Cannot add value”);
}
}
// Pop operation
public int pop() {
top—;
if(top < 0) {
System.out.println(“Stack empty, returning error value”);
return ERROR; // Some error value
}
else {
return array[top];
}
}
public static void main(String[] args)
{
Stack s1 = new Stack();
52
Stack s2 = new Stack();
s1.push(1); // 0th element
s1.push(3); // 1st element
s1.push(5); // 2nd element
s1.push(7); // 3rd element
s1.push(9); // 4th element (stack full here)
s1.push(11); // Stack overflow here
for(int i=0;i<Stack.MAX;i++){
s2.push(i*2+100);
}
// Now pop values from stack s1
for(int i=0;i<MAX;i++){
System.out.println(“Popped from S1: “ + s1.pop());
}
// Now pop values from stack s2
for(int i=0;i<MAX;i++){
System.out.println(“Popped from S2: “ + s2.pop());
}
// By now both stacks are empty.
//Now try to pop one more element
System.out.println(“Popped from S1: “ + s1.pop());
System.out.println(“Popped from S2: “ + s2.pop());
}
}
The output of the program is given below
Pushing value: 1
Pushing value: 3
Pushing value: 5
Pushing value: 7
Pushing value: 9
Stack full. Cannot add value
Pushing value: 100
Pushing value: 102
Pushing value: 104
Pushing value: 106
Pushing value: 108
53
Popped from S1: 9
Popped from S1: 7
Popped from S1: 5
Popped from S1: 3
Popped from S1: 1
Popped from S2: 108
Popped from S2: 106
Popped from S2: 104
Popped from S2: 102
Popped from S2: 100
Stack empty, returning error value
Popped from S1: -999
Stack empty, returning error value
Popped from S2: -999
Observe that the array and top are not directly used anywhere. Instead, the operations provided
are performed on stack objects.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What do you mean by instance variable hiding?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

4.6.SUMMARY
This chapter introduces the concept of classes, objects, data and member elements, constructor
etc. The method and constructor overloading is illustrated with simple examples. Java’s unique
garbage collection feature and its associated finalize method are also explained.To guaranty
that a variable is initialized, an automatic function, which will be run immediately when an
object is created, should be written. In Java, the class designer can guarantee initialization of
every object by providing a special method called a constructor. If a class has a constructor,
Java automatically calls that constructor when an object is created, before users can even get
their hands on it. So initialization is guaranteed. The name of the constructor is the same as the
name of the class. It makes sense that such a method will be called automatically on
initialization.Programmers know about the importance of initialization, but often forget the
importance of cleanup. In C or C++ this is done by the use of free or delete. Java has the
garbage collector to reclaim the memory of objects that are no longer used. The garbage collector
is automatically initiated by the runtime environment whenever it feels apt. Since the finalize
method is called just before garbage collector is run, it may not be called if garbage collector
is not run because there is plenty of memory available making garbage collection unnecessary.
Java provides a static method
54
4.7. CHECK YOUR PROGRESS MODEL ANSWERS
1. If a local variable exists in a method with same name as that of an instance variable,
then the local variable hides or shadows the instance variable
2. Method whose name is the class name without return type that guarantees data members.
3. . The Stack is a “Last In First Out” mechanism, just like a stack of plates arranged for a
buffet.

4.8. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
1. Describe the term class, object, encapsulation, box,Unbox in java with exaples
2. Write a java program to create class student with htno,name, dob,panme,address,course
and methods to set student data and to print student data. The data should be given from
keyboard
3. Write a java program to create class student with htno,name, dob,panme,address,course
and constructors with no arguments, with argument to initialize the data of the class.
And method to print the data.
II. Answer the following questions in about 15 lines each
1. Write a java program to demonstrate box and Unbox int data type.
2. Expalin how java handles the garbage collection
3. Write a java program to demonstrate finalize method.

4.9. GLOSSARY
Constructor : Method whose name is the class name without return type
that guarantees data members.
Box and Unbox : Primitive to wrpper and vice versa
Hiding a variable : If a local variable exists in a method with same name as that
of an instance variable, then the local variable hides or
shadows the instance variable
Garbage : All the memory allocated for unused objects and variables.
Instance Variable : Variable which is instantiated for each object of a class.

55
UNIT-5: ADDITIONAL FEATURES OF JAVA OOPs
Contents
5.0 Objectives
5.1 Introduction
5.2 Overloading methods and constructors, Access controls
5.3 The final method, Static Variables and Methods
5.4 Nested and inner classes, String class
5.5 Command line arguments with vararg
5.6 Summary
5.7 Check your progress Model Answers
5.8 Model Examination Questions
5.9 Glossary

5.0. OBJECTIVES
After studying this unit, you should be able to
• Explain object oriented programming concepts like overloading, access controls.
• Describe static classes, static members and methods
• Understandinner and anonymous classes.
• Gain knowledge on command line arguments

5.1 INTRODUCTION
In many cases it is required to use the same function name for different purposes to maintain
intuitive naming convention. For example, the method name ‘add’ is apt for adding integers,
real numbers or other data types.Access control to variables and members of a class is one of
the key features of any OOP as it results in more robust and safe code. For example in the stack
class the array defined to store values is supposed to be accessed or modified only by its two
methods push and pop where the top is properly modified. If a user directly accesses the ‘top’
variable and sets its value say to 5 when there is only one value on stack, the program behaves
oddly by showing “stack full” message. To avoid this danger, the user should not be permitted
to access the variables array and top. Object oriented programming encourages the extension
of an existing class by the user to provide additional or different functionality. In some cases
the designer of a class may feel that a specific method should not be modified any further. In
such a case, the method may be declared as ‘final’ in Java. Once a method is made final, its
derived classes cannot modify or override this method

5.2. OVERLOADING METHODS AND CONSTRUCTORS,


ACCESS CONTROLS
In many cases it is required to use the same function name for different purposes to maintain
intuitive naming convention. For example, the method name ‘add’ is apt for adding integers,
real numbers or other data types. This is possible in object oriented programming by way of
56
overloading. Overloading a method is possible, provided the arguments list is different in each
case. For example, the method “add” for adding two integers and two floats should have
different argument types but can have the same name “add”.
int add(int a, int b);
double add(double a, double b);
The compiler can select appropriate function depending on the parameters that are passed.
The call add(1.2, 2.3)will select the function add with double values automatically. Constructor
can also be overloaded in Java which means, one can pass different initialization values to the
constructor during the creation of the object.
Following is an example that shows both overloaded constructors and overloaded ordinary
methods:
/**
* This class shows the use of constructor with arguments
*/
public class Box {
int width, height, depth; // Variables to hold data

/**
* No parameter Constructor
*/
public Box() {
width = 5;
height= 5;
depth = 5;
}

/**
* Constructor with parameters (overloaded)
*@param h Height of the box
*@param w Width of the box
*@param d Depth of the box
*/
public Box(int h, int w, int d) {
width = w;
height= h;
depth = d;
}

57
/**
* Returns the volume of the rectangle
*/
public int getVolume() {
return length*width*height;
}

/**
* This method sets the values and returns volume
*/
public int getVolume(int h, int w, int d) {
height = h;
width = w;
depth = d;
return h*w*d;
}

// Main method that tests the class


public static void main(String args[]){
Box b1 = new Box (); // Create object b1 with defaults
Box b2 = new Box (2,3,4); // Create Box b2 with parameters
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
System.out.println(“Volume of 2x3x4: “ + b1.getVolume(2,3,4));
}
}
A method or a constructor can be overloaded any number of times, as long as the parameters
are different.
ACCESS CONTROLS
Access control to variables and members of a class is one of the key features of any OOP as it
results in more robust and safe code. For example in the stack class the array defined to store
values is supposed to be accessed or modified only by its two methods push and pop where the
top is properly modified. If a user directly accesses the ‘top’ variable and sets its value say to
5 when there is only one value on stack, the program behaves oddly by showing “stack full”
message. To avoid this danger, the user should not be permitted to access the variables array
and top.
Java provides four levels of access levels for protecting data and members
Default: If nothing is mentioned about access level, default access level is assumed which
58
means that the variable is accessible from anywhere within the same package (more about
packages later).
public: If a variable or method is given public access, that the variable or method is accessible
from anywhere, even from other packages.
private: Private access means that the variable is accessible only from the current class.
protected: Protected access says that the variable is accessible from the class and its derivatives
(inherited classes).
Any variable can be given one of the access levels. If a variable is accessed without proper
rights, the compiler signals an error message. Consider the following example:
class One {
int a; // default access
public int b; // public access
private int c; // private access
protected int d; // protected access
}
class Two
{
void f()
{
One one = new One();
one.a=20; // valid since they are in same package
one.b=30; // valid since public
one.c=30; // error since c is private
one.d=40; // error: class Two is not derived from One
}
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. Listout various access controls in Java?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

5.3. THE FINAL METHOD, STATIC VARIABLES AND METHODS


THE FINAL METHOD
Object oriented programming encourages the extension of an existing class by the user to
provide additional or different functionality. In some cases the designer of a class may feel that 59
a specific method should not be modified any further. In such a case, the method may be
declared as ‘final’ in Java. Once a method is made final, its derived classes cannot modify or
override this method. For example consider the following example:
class Calculator{
int a, b;
public Calculator(int a, int b)
{
this.a = a;
this.b = b;
}
public final int getSum()
{
return a+b;
}

public static void main(String[] args){


Calculator calc = new Calculator (10,20);
System.out.println(calc.getSum());
}
}
Here the method getSum is declared as final since there is no way it can be improved. Hence,
any subclasses derived from Calculator (by extending Calculator) cannot modify the behavior
of getSum.
STATIC VARIABLES AND METHODS
Generally a class describes how objects of that class should look like and how they will behave.
A class is merely a definition and nothing can be done with it until an object of that class is
created with new, and at that point data storage is created and methods become available. But
there are some situations in which this approach is not sufficient.
There may be a requirement where all objects share a common value (for example, if a printer
is connected to a PC, only one object of type Printer can exist which should be shared by all
the objects of an application).
A variable should exist even if there is no object of that type is created.
The static keyword fulfills these requirements. When something is declared as static, that data
or method is not tied to any particular object instance of that class. Even if an object of that
class is never created, a static method or data can be accessed directly with in class. With
ordinary, non- static data and methods an object must be created and that object must be used
to access the data or method. Since static methods don’t need any object to be created before
they are used, they cannot directly access non- static members or methods by simply calling
those other members without referring to a named object (since non- static members and methods
must be tied to a particular object). The rule is: static methods cannot access non-static members
or data.
60
To make a data member or method static, the keyword ‘static’ is placed before the definition.
For example, this produces a static data member and initializes it:
class StaticTest
{
static int i = 47;
}
Now all the objects of type StaticTest objects will share the same i:
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
At this point, both st1.i and st2.i have the same value of 47 since they refer to the same piece
of memory. There are two ways to refer to a static variable:
Via an object, by saying, for example, st2.i
Directly through its class name as StaticTest.i (this is not possible with a non-static member.
The latter is the preferred way to refer to a static variable since it emphasizes that variable’s
static nature.
For example, the statement ‘StaticTest.i++;’ increments the variable. At this point, both st1.i
and st2.i will have the value 48.
Similar logic applies to static methods. A static method can be referred to either through an
object like any method, or with the classname.method( ). A static method is defined in a similar
way:
class StaticTest {
static int i = 47;
static void incr() { StaticTest.i++; }
}
Observe that the StaticTest’s incr() method increments the static data i. The incr( ) method can
be called in the typical way, through an object:
StaticTest st = new StaticTest();
st.incr();
Or, because incr( ) is a static method, you can call it directly through its class:
StaticTest.incr();
Another use of static method is to wrap utility methods in a class. For example consider a
utility tool max() which finds the maximum of the two numbers passed to it. It is not specific
to any class but in Java it should be within a class since no code will be outside the classes.
Consider the following:
class MyTools {
public static int max(int a, int b) {
return (a>b)?a:b;
}
}
61
One need not create an object just to use max method from MyTools if max is defined as static
method. Now to get maximum of two numbers the call may be made with MyTools.max(10,15)
which simplifies the code since it eliminates the necessity for creating an object of type MyTools
first and then use its member function.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is a static block?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

5.4.NESTED AND INNER CLASSES, STRING CLASS


NESTED AND INNER CLASSES
Java allows defining a class inside another class which is known as ‘nested class’. The scope
of the nested class is bounded by the scope of the enclosing classes. Nested classes can be
declared as static or non-static. If a nested class is declared as static, it can access only the
static members of the enclosing class, and hence its usage is very limited and is rarely used. If
the nested class is declared as an ordinary class (non-static), then it can access any member of
its enclosing class including the private members. The non-static nested class is called ‘inner
class’.
For example, if Cube is a class defined within the Shape class, the object of Cube cannot exist
without the existence of a Shape object and the inner class Cube can access all the members of
the Shape class, including private members. However, the external class (Shape) cannot access
the members of Cube class. Following is an example:
public class Shape
{
private int width;
private int height;
private Cube cube; //Variable of type Cube

public Shape(int width, int height, int depth){


cube = new Cube(width, height, depth);
// Here Shape cannot access cube.depth
}

public int getArea(){


return width*height;
}
public int getVolume(){
62
return cube.getVolume();
}
// ——— Definition of inner class ———//
class Cube{
int depth;
public Cube(int w, int h, int d){
width = w; // Cube can access Shape’s members
height = h;
depth = d;
}
public int getVolume() {
return height*width*depth;
}
}
public static void main(String args[]){
Shape s = new Shape(5,10,15);
System.out.println(“Volume: “ + s.getVolume());
Cube c = new Cube(5,10,15); // Not OK
System.out.println(“Volume: “ + c.getVolume()); // Not OK
}
In the preceding code the Shape class uses an inner class, calledCube, to represent the third
dimension. Following guidelines may be followed while using inner classes.
Inner classes may be used when there is close relationship between two classes and is not
accessed by any other class.
Inner classes are often used in event handling in Java GUI programming where there is a close
relationship between the listener and its generator user interface component.
STRING CLASS
String is a series of characters. It is perhaps the most used data type in any program. In languages
like C and C++ strings are implemented using a character array. In Java, string is a built-in
class, which deserves that priority. The class String has many methods and constructors for
creating and manipulating strings. A string literal is represented with enclosed double quotes
like “this is a test string”
String Constructor
String has many flavors of constructors. The simplest is the default constructor, which creates
a string with no data.
String s = new String();
The second from takes an array of characters like:
char ch[] = {‘a’, ‘b’, ‘c’};
63
String s = new String(ch);
The most used constructor is the constructor with another String as initializer.
String s = new String(“This is a test String”);
String s1 = new String (s);
Another way to initialize a String variable is to assign a string literal to it.
String s = “This is a test String”;
There are other constructors, which are sparingly used depending on the particular situation.
These are given in Java documentation.
String Class Methods
String is the natural data the is used in real life and hence a wide variety of methods are
provided in the String class. The Java documentation may be referred for an exhaustive list of
methods available. However, some of the very useful methods are given here. Note that strings
are immutable (non modifiable) and hence when a method needs to change the value, it creates
a new string and returns it.
int length(): returns the length of the string.
Strings can be concatenated using the + operator. For example,
String s1=”This”;
String s2 = “ is”;
String s3 = “ a Test”;
String s4 = s1+s2+s3+” Message”;
System.out.println(s4);
System.out.println(“Length of the string:” + s4.length());
The value that is printed is “This is a Test Message” followed by “Length of the string: 22.
String class has the ability to concatenate other data types also as seen above. This is done by
using the toString() method of the object that is being added, which returns the String equivalent
of the object.
char charAt(int where) method return the character at the index given.
String s = “This is a test”;
s.charAt(3) gives ‘s’ since this is the 3rd character (0th char is the first char).
Strings cannot be compared with == operator since strings are objects and if == is used it
compares the handles or references to the two strings, which is not correct. The content of two
strings must be compared which is done either using equals() or using equalsIgnoreCase().
equals compares two strings and returns true if they are equal including the case and false
otherwise. equalsIgnoreCase make case insensitive comparison.
1. boolean equals(String s)
2. boolean equalsIgnoreCase(String s);
3. For example,
4. “This”.equals(“this”)returns false
5. “This”.equalsIgnoreCase(“this”)returns true.
64
6. int compareTo(String s) compares two strings and returns an integer.
7. s1.compareTo(s2) returns negative value if s1<s2, zero if s1=s2 and positive value if
s1>s2
8. boolean startsWith(Strings)
9. boolean endsWith(Strings)
The above functions return true if the string starts or ends with the given pattern respectively
and false otherwise. Some other important methods are given below:
int indexOf(int ch) - returns the index where the character ch is first found.
int lastIndexOf(int ch) - returns the index where the character ch is last found
int indexOf(String s) - returns the index where the substring s was found first.
int lastIndexOf(String s) - returns the index where the substring s was found last.
String subString(int start) - returns the substring from the start character onwards.
String subString(int start, int end) - returns the substring from start to end.
String concat(String s) - returns the original string + s
String replace(char org, char rep) - replaces all org characters with rep
String trim() - returns the string after trimming all the leading and trailing white spaces.
String toLowerCase() - returns a string after converting it to lower case
String toUpperCase() - returns a string after converting it to upper case
Following is an example that illustrates the use of various member functions of String class.
public class StringTest{
public static void main(String args[]){
String s1 = new String(“string 1”); // using constructor
String s2 = “string 2”; // Another way of creating a string
System.out.println(“char at 3 : “ + s1.charAt(3));
System.out.println(“Length of string 1 is :” + s1.length());
System.out.println(“Comparison :” + “This”.equals(“this”));
System.out.println(“Comparison:”+”This”.equalsIgnoreCase(“this”));
System.out.println(“Compareto :” + “abc”.compareTo(“def”));
System.out.println(“Compareto :” + “def”.compareTo(“abc”));
System.out.println(“Compareto :” + “abc”.compareTo(“abc”));
System.out.println(“Startswith:”+”abcdef”.startsWith(“abc”));
System.out.println(“StartsWith :”+ “abcdef”.startsWith(“def”));
System.out.println(“endsWith :” + “abcdef”.endsWith(“ef”));
System.out.println(“indexOf :” + “abcdefghijkl”.indexOf(“de”));
System.out.println(“substring :” + “abcdefghijkl”.substring(4));
System.out.println(“concat :” + “abc”.concat(“def”));
System.out.println(“replace :” + “ abcdefabcdef”.replace(‘b’,’x’)); 65
System.out.println(“trim —” + “ abcdef “.trim() + “——”);
System.out.println(“toUpperCase :” + s1.toUpperCase());
}
}
The result of the above program is shown below:
char at 3 : i
Length of string 1 is :8
Comparison :false
Comparison :true
Compareto :-3
Compareto :3
Compareto :0
Startswith :true
StartsWith :false
endsWith :true
indexOf :3
substring :efghijkl
concat :abcdef
replace : axcdefaxcdef
trim —abcdef——
toUpperCase :STRING 1
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What is the function to find length of the string?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

5.5.COMMAND LINE ARGUMENTS WITH VARARG


Command line arguments are useful when some data is to be supplied to the program when the
program is run. This is done by giving the arguments along with the command separated by
spaces. Java takes the arguments that are passed by the user as an array of strings which is
passed to the main(). That is the reason for declaring the main with String array as a parameter.
These arguments can be processed by accessing the parameter to main. Consider the example
below:
public class Test {

66
public static void main(String args[]){
System.out.println(“You have sent “+ args.length +
“ arguments and they are: “);
for (int i=0;i<args.length;i++){
System.out.println(i+”: “ + args[i]);
}
}
}
The result of the same program for two different argument lists is shown below:
java Test one two three
You have sent 3 arguments and they are:
0: one
1: two
2: three
java Test one two three four five six seven
You have sent 7 arguments and they are:
0: one
1: two
2: three
3: four
4: five
5: six
6: seven
Methods with Variable Arguments (Varargs) in Java
Since JDK 5, Java has included support for methods with variable arguments just like variable
arguments to main method. A variable-length argument is specified by three periods(…) known
as ellipses. For Example,
public static void sum(int ... a) { // code } takes any number of integers as arguments.
Internally the compiler takes these arguments as an array of int values. Following Java program
demonstrates the use of varargs
class Test{
static void sum(int ...a){
int sum = 0;
System.out.println(“Number of arguments: “ + a.length);
// using for each loop to get sum of contents of a
for (int i : a){
sum +=i;
}
67
System.out.println(“Sum: “ + sum);
}
// Driver code
public static void main(String args[]){
sum(); // no parameter
sum(100, 200); // two parameters
sum(1, 2, 3, 4, 5); // five parameters
}
}
Output:
Number of arguments: 0
Sum: 0
Number of arguments: 2
Sum: 300
Number of arguments: 5
Sum: 15
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
4. What do you mean by method VARARGS?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

5.6. SUMMARY
This chapter introduced the basic concepts of classes and objects and some features of Java
language like variable arguments to main and user defined methods. An introduction to the
String class is given. Command line arguments are useful when some data is to be supplied to
the program when the program is run. This is done by giving the arguments along with the
command separated by spaces. Java takes the arguments that are passed by the user as an array
of strings which is passed to the main(). That is the reason for declaring the main with String
array as a parameter. These arguments can be processed by accessing the parameter to main.
Since JDK 5, Java has included support for methods with variable arguments just like variable
arguments to main method. A variable-length argument is specified by three periods(…) known
as ellipses. For Example,public static void sum(int ... a) { // code } takes any number of
integers as arguments. Internally the compiler takes these arguments as an array of int values.
Following Java program demonstrates the use of varargs

68
5.7. CHECK YOUR PROGRESS MODEL ANSWERS
1. Public, private, default, protected
2. It initializes static variables
3. string.length()
4. Any method can variable arguments using syntax data type ….. arg_name

5.8. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Explain static variables, static methods with examples
2. Write a program that overload a methods and constructors
3. Write a program to implemtn various methods of String class
II. Answer the following questions in about 15 lines each
1. Describe final method with example
2. Describe various access controls in Java with an example.
3. Write a java program that uses command line and variable method arguents.

5.9. GLOSSARY
Access Control : Control the how a member of class is accessible in
side,out side of the class.
Inner Class : A class whihch is defined inside another class
Static Variable : A variable which is shared by all methods with class
scope or object scope
Final Mehtod : A static method which can’t be modified
compareTo(String s) : Compares two strings and returns an integer

69
UNIT-6: INHERITANCE AND ABSTRACT CLASSES
Contents
6.0 Objectives
6.1 Introduction
6.2 Inheritance, Super Class and Subclass
6.3 Abstract Classes and Methods
6.4 Summary
6.5 Check your progress Model Answers
6.6 Model Examination Questions
6.7 Glossary

6.0. OBJECTIVES
After studying this unit, you should be able to
• Understand the concept of inheritance

• Descr9he abstract classes and method overriding

• Explain how the method dispatching works.

• Explain how to prevent derived classes from overriding methods..

6.1. INTRODUCTION
Inheritance is the feature that makes software more reusable. When a class is developed for a
particular application, and there is a need to develop a similar class with minor modifications,
inheritance comes handy. When a class is inherited from another, some or all the methods of
the base class can be retained or overridden or some extra methods can be added. That means,
without editing the source code of the original class, one can enhance the capabilities of the
class by deriving a new class from the existing class. The super is a keyword in java which
references parent class object. It is generally used to access the specific variable of a superclass.
A special function called super() also exists, which calls the constructor of an object’s superclass.
The super() function should be used only in the subclass constructors and it should be the first
line of that constructor. A reference (variable of a class type) to an object of a subclass can be
used just like any reference without inheritance. However, a reference of superclass (base
class) type can also be used to refer a subclass. For example, consider the above example
given in the multi level hierarchy. Class A is the parent of B which is the parent of C. Normally
if objects of type A, B and C are to be created, the same data type variables are declared with
new

6.2. INHERITANCE, SUPER CLASS AND SUBCLASS


Inheritance is the feature that makes software more reusable. When a class is developed for a
particular application, and there is a need to develop a similar class with minor modifications,
inheritance comes handy. When a class is inherited from another, some or all the methods of
the base class can be retained or overridden or some extra methods can be added. That means,
70
without editing the source code of the original class, one can enhance the capabilities of the
class by deriving a new class from the existing class.
The class that is used to define a new class is called a super class (or parent class or base
class.) The class based on the parent class is called a subclass class (or child or derived class.)
In Java, children inherit characteristics from just one parent. This is called single inheritance.
Some languages like C++ allow multiple inheritance, where a child can inherit from more than
one parent. With multiple inheritance, it is sometimes hard to tell which parent contributed
what characteristics to the child. Java avoided these problems by restricting to single inheritance.
Inheritance in Java is achieved by using the keyword “extends”. The Syntax for extending a
class is:
classsubClassextendssuperClass {
// new characteristics of the child class go here
}
Where ‘subClass’ is new class name and ‘superClass’ is the existing class name. For example,
say there is a class called Count that stores an integer and prints the number when asked.
class Count{
int count; // Data member that is shared with child classes
public Count1(){
count = 0;
}

public Count(int i){


count = i;
}
public void printValue( ){
System.out.println(“Count: “ + count);
}
}
Now we wish to extend this class to print the square of count when asked.
class Count2 extends Count{
public Count2(int i){
count = i;
}
public printSquare(){
System.out.println(“Count square: “ + count*count);
}
}
In Class2, an extra function called printSquare() is implemented. This function is available to
71
all variables of type Class2 along with other functions (methods) that are already defined in
class Count.
The Super Keyword and Super() Method
The super is a keyword in java which references parent class object. It is generally used to
access the specific variable of a superclass. A special function called super() also exists, which
calls the constructor of an object’s superclass. The super() function should be used only in the
subclass constructors and it should be the first line of that constructor.
The class definition for Count has a constructor that initializes the member data of Count type
objects. The class Count2 has a constructor that initializes the data of Count2 objects. Instead
of directly using initialization of its super class, the Count2 can call the constructor of Count
with a call to the ‘super()’ method. The super can be default or parameters can be sent to match
its super class’s constructor. The constructor for class Count2 with super looks like this:
// constructor with call to its super
public Count2( int i){
super(i); // use the super class’s constructor
// Other Statements if any (in this case there is nothing)
}
The statement super( i ) invokes a constructor of the parent to initialize some of the data. There
are two constructors in the parent. The compiler selects the correct one to invoke based on the
argument list in super(i).
The super keyword can be used to specifically access superclass’s variables or methods if
there exists a variable or method in subclass as well. In such case super.count can be used in
Count2 class.
Example:
Here is another program that uses a class VideoCD to represent CDs available at a video CD
rental store.
class VideoCD{
String title; // name of the item
int length; // number of minutes
boolean avail; // is the CD available in the store?
// constructor
public VideoCD(String ttl){
title = ttl;
length = 90; // Default length
avail = true; // Default to true
}
// constructor
public VideoCD(String ttl, int lngth){
title = ttl;
length = lngth;
72
avail = true;
}
public void show(){
System.out.println(title + “ (“ +
(avail? “Available”: “Not available”) + “)”);
}
}
The VideoCD class has basic information in it, and would be sufficient for documentaries and
instructional tapes. But movies need more information hence this will be extended to Movie
which has the name of the director and a rating.
class Movie extends VideoCD{
String director; // name of the director
String rating; // A or B or C
// constructor
public Movie(String ttl, int lngth, String dir, String rtng ){
super( ttl, lngth ); // use the super class’s constructor
director = dir; // Director
rating = rtng; // Rating
}
}
The class Movie is a subclass of VideoCD which is depicted as follows:

VideoCD

Movie

An object of type Movie has the following members in it:


title inherited from VideoCD
length inherited from VideoCD
avail inherited from VideoCD
show() inherited from VideoCD
director defined in Movie
rating defined in Movie
Both classes are defined: the VideoCD class can be used to construct objects of that type, and
now the Movie class can be used to construct objects of the Movie type.
class CDStore {
public static void main ( String args[] ){
VideoCD item1 = new Video CD(“Jaws”, 120 );
73
Movie item2 = new Movie (“Star Wars”, 120, “Spielberg”, “A”);
item1.show();
item2.show();
}
}
In this example, item2.show() will use the superclass’s show() method since it has no method
called show() within its definition. Hence the item2.show() prints the values of the base class.
This can be modified in the derived class as explained later in method overriding and dynamic
method dispatch sections.
Member Access in Inheritance
As mentioned earlier, when a subclass extends a superclass, the subclass can access all the
data and method members except the private data and methods. For example, if count variable
in Count class is made private, it cannot be directly accessed by Count2 class. In such a case,
Count must provide a method like getCount() or setCount() to get or modify the count from
child classes. All other access modifiers (default, public and protected) allow the child to
access the parent’s data.
Multi Level Hierarchy
Inheritance in Java can logically go to any level, though practically it is not necessary go
beyond two to three levels in general. There can be any number of child classes derived from
one parent class, but there can be only one parent class for any given subclass. This is contrary
to C++, where one class can be derived from more than one parent class (multiple inheritance).
Consider the following multi level class hierarchy:
class A{
int a;
public A(int val){
a = val;
}
public void show(){
System.out.println(“Value: “ + a);
}
}
class B extends A{
int b;
public B(int val1, int val2){
super(val1);
b = val2;
}
public void show(){
System.out.println(“Values: “ + a + “, “ + b);
74 }
}
class C extends B{
int c;
public C(int val1, int val2, int val3){
super(val1, val2);
c = val3;
}
public void show(){
System.out.println(“Values: “ + a + “, “ + b +”, “ + c);
}
}
In the above class hierarchy, class C can access any method or data of its parent classes. This
is illustrated with the println statement, where the variable ‘a’ from A and ‘b’ from B are
accessed directly.
Method Overriding
Example Movie class has not defined its own show() method and hence, it uses its base class’s
(VideoCD) show() method which cannot print the data of Movie. Hence, the show method
should be rewritten in the subclass. When a method with same signature is defined in subclass,
the subclass method overrides the super class method. The new show() method in the class
Movie can be as follows:
// added to class Movie
public void show(){
System.out.print(“Title: “ + title + “, “);
System.out.print(“Time: “+ length + “, “);
System.out.print(“Available: “ + avail+”, “);
System.out.println(“Director: “ + director + “, “);
System.out.println(“Rating: “ + rating);
}
Now, even though the parent has a show() method the new definition of show() in the child
class will override the parent’s version.
An object of the parent type will include the method given in the parent’s definition. An object
of the child type will include the method given in the child’s definition.
With the change in the class Movie the following program will print out the full information
for both items appropriately.
class CDStore {
public static void main ( String args[] ){
VideoCD item1 = new VideoCD(“Jaws”, 120 );
Movie item2 = new Movie (“Star Wars”, 120, “Spielberg”, “A”);
item1.show(); 75
item2.show();
}
}
The line item1.show() calls the show() method defined in VideoCD, and the line item2.show()
calls the show() method defined in Movie.
Reference to Classes with Inheritance
A reference (variable of a class type) to an object of a subclass can be used just like any
reference without inheritance. However, a reference of superclass (base class) type can also be
used to refer a subclass. For example, consider the above example given in the multi level
hierarchy. Class A is the parent of B which is the parent of C. Normally if objects of type A, B
and C are to be created, the same data type variables are declares as:
A aObj = new A(10);
B bObj = new B(10,20);
C cObj = new C(10,20,30);
However, as was mentioned, the base class type reference can also be used to refer to the
subclasses. Hence, the above can also be achieved as:
A aObj = new A(10);
A bObj = new B(10,20);
A cObj = new C(10,20,30);
Dynamic Method Dispatching
Dynamic Method Dispatch is a mechanism by which Java can select proper method based on
the object’s data type using a reference of its base (super) class. Consider the following example
where the classes A, B and C defined are used.
class Test{
public static void main(){
A a = new A(); // Reference and object are same types
A b = new B(); // Base class reference to subclass B
A c = new C(); // Base class reference to subclass C
a.show(); // Selects show method of A class
b.show(); // Selects show method of B class dynamically
c.show(); // Selects show method of C class dynamically
}
}
In the above example, Java can select the proper show() function though they are called using
the A type variable. This is a very useful feature in selecting the proper method always even if
a method is extended in future.
Using Final with Inheritance
Sometimes, for security or design reasons, a class should not be sub classed (extended) or a
method within a class should not be overridden. In Java, either of these goals can be achieved
76 by declaring the class or the method as final. Any class or method can be made final by adding
a keyword “final” in front of its definition. A class, or a method or a variable, once it is
declared as a final, it cannot be overridden, or altered. Many of the Java standard methods are
final and hence they cannot be modified. For example,
final class A { .. } -> Inheritance is not possible further
final f() { } -> Overriding is not possible in subclasses
final int x = 10; -> No alteration is possible to variable x.
The Object Class
In Java, every class that is defined in any application is derived from a predefined class called
Object. When a user defines a class like this:
class MyNewClass
{
}
Java is actually defining a child of the Object class. The following is the exact equivalent of
the above:
class MyNewClass extends Object{
……
}
An object class has some generic methods predefined which can be overridden by any subclass.
These methods are as follows:
Object clone() – Clones the current object
boolean equals(Object obj) – Compares current object with another
void finalize() – Generic finalize method that does nothing
final Class getClass() – Returns the data type of the current class
int hashCode() – Computes a hash code for the object (checksum)
String toString() – Converts the object to a String object
If any of these methods is overridden, the new method is used accordingly. This is useful when
a special comparison is required or when the object is converted to a string.
By using this feature, Java achieves generic references, where objects of any type can be
referenced with Object type reference. This is important and is used wherever required,
especially in GUI programming where different components have to be dealt with.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What is dynamic method dispatching?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

77
6.3. ABSTRACT CLASSES AND METHODS
Abstract Method
Consider a simple class called Shape with a, b, c as data members which can store the dimensions
of different shapes. For example, a rectangle stores length and breadth in ‘a’ and ‘b’. A triangle
stores its sides in ‘a’, ‘b’ and ‘c’. A circle just stores the radius in ‘c’. Now if area of the shape
is to be found, there is no generic formula for all these three shapes. The formula will vary
with the shape and hence, while designing the Shape class, there is no way to implement the
method area() meaningfully. The subclasses of Shape must implement their own version of
area() method properly.
Suppose that a program uses a base class and calls the area() method expecting that the subclass
has implemented it, where as the subclass actually doesn’t implement it. This gives an error
during runtime. This situation can be avoided by enforcing or compelling the subclass to
implement the method area(). This is done using the abstract method. An abstract method is
declared by prefixing the keyword abstract before the method signature and removing the
body of the method i.e., just declaring the signature.
access_modifier abstract methodName(parameters …);
The access_modifier can be empty (default), private, protected or public. A non-abstract child
class inherits the abstract method and must define a non-abstract method that matches the
abstract method.
Abstract Class
A class can be declared just by prefixing the keyword abstract before the class definition.
Once, declared as abstract, objects of that type cannot be created. If any method is declared as
abstract in a class, the class must be declared as abstract since there is no code for the abstract
method. The class declaration in such a case must also be preceded by abstract keyword.
Access modifiers such as public can be placed before abstract. Even though it cannot be
instantiated, an abstract class can define methods and variables that children classes inherit.
access_modifier abstract class ClassName{
. . . . . // definitions of methods and variables with at least
// one abstract method
}
Consider the Test class that tests Abstract classes of type Shape:
public class Test{
public static void main(String[] args){
Shape a = new Rect(10,20);
Shape b = new Triangle(10,20,30);
Shape c = new Circle(10);
System.out.println(“Area of Rect: “ + a.area());
System.out.println(“Area of Triangle: “ + b.area());
System.out.println(“Area of Circle: “ + c.area());
}

78 }
abstract class Shape{
double a,b,c;
Shape(){
a = b = c = 0.0; // Chained assignment
}
public Shape(double val1, double val2, double val3)
{
a=val1;
b=val2;
c=val3;
}
abstract double area();
}
class Rect extends Shape{
public Rect(double width, double height){
super(width, height, 0); // 0 will be promoted to double
}
public double area(){
return a*b;
}
}
class Triangle extends Shape{
public Triangle(double side1, double side2, double angle){
super(side1, side2, angle);
}
public double area(){
return (a*b*Math.sin(c*Math.PI/180)/2.0);
}
}
class Circle extends Shape
{
public Circle(double radius) {
super(0f,0f,radius);
}
public double area(){

79
return (double)(Math.PI * c*c);//
}
}
In the above example, a test class is defined with three references to the abstract Shape class,
which is assigned to a Rect, Triangle and Circle respectively. The Shape class is declared
abstract since it defines at least one abstract method (only one in this case). The respective
classes implement the area method appropriately.
Observe that all the subclasses of class Shape should implement all the abstract methods of the
Shape class (in this case there is only one abstract method).
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. How do you define abstract base class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

6.4. SUMMARY
This chapter introduces the important concept of object oriented program called inheritance,
which allows reuse of classes by extending the functionality. Method overriding, importance
of abstract methods and classes is also highlighted. Sometimes, for security or design reasons,
a class should not be sub classed (extended) or a method within a class should not be overridden.
In Java, either of these goals can be achieved by declaring the class or the method as final. Any
class or method can be made final by adding a keyword “final” in front of its definition. A
class, or a method or a variable, once it is declared as a final, it cannot be overridden, or
altered. Many of the Java standard methods are final and hence they cannot be modified.A
class can be declared just by prefixing the keyword abstract before the class definition. Once,
declared as abstract, objects of that type cannot be created. If any method is declared as abstract
in a class, the class must be declared as abstract since there is no code for the abstract method.
The class declaration in such a case must also be preceded by abstract keyword. Access modifiers
such as public can be placed before abstract. Even though it cannot be instantiated, an abstract
class can define methods and variables that children classes inherit.

6.5. CHECK YOUR PROGRESS MODEL ANSWERS


1. is a mechanism by which Java can select proper method based on the object’s data type
using a reference of its base (super) class
2. A class can be declared just by prefixing the keyword abstract before the class definition

6.6. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Create a base class Calculator that has methods for add and subtract. Now extend this
class to perform multiplication and division also.
80
2. Explain multilevel inheritance with an example java program.
3. Write a program to implemtn abstact classes and method using shape class.
II. Answer the following questions in about 15 lines each
1. Describe final key word with inheritance.
2. Write a program in java to demonstrate inheritance..
3. Write a java program that shows the implementation of super ().

6.7. GLOSSARY
Inheritance : Is OOPs concept using which reusability, extensibility
is implemented.
Multilevel Inheritance : Heirarchy of nase class and derived classes
Super() : Is a function which calls base class constructor.
Abstract Method : A method that will be just declared in abstract base class.
Dynamic Method Dispatching: is a mechanism by which Java can select proper method
based on the object’s data type using a reference of its
base (super) class.

81
82
BLOCK - III

ADDITIONAL FEATURES OF JAVA


This block gives an overall study on Defining package, setting class path, access protection,
importing packages. defining, interfaces, implementing, nested interfaces, applying
interfaces, default interface methods, using static method in an interface. It also enables the
students to understand how to define various types of exceptions, implementinguncaught
exceptions, writing try and catch, nested catch, multiple try, throw, and throws blocks,
using finally block to define final option, writing programs using java built-in exceptions,
user-defined exceptions, chained exceptions, and recently added 3 exceptions. This block
explains collection classes which store group of elements of similar data types. Collection
classes included in this unit are arraylist with generic type, hashmap with and without user
defined data types...

The units included in the block are:


Unit-7: Packages and Interfaces
Unit-8: Java Exception Handling
Unit-9: Java Collections

83
84
UNIT-7: PACKAGES AND INTERFACES
Contents
7.0 Objectives
7.1 Introduction
7.2 Packages In Java
7.3 Interfaces In Java
7.4 Summary
7.5 Check your progress Model Answers
7.6 Model Examination Questions
7.7 Glossary

7.0. OBJECTIVES
After studying this unit, you should be able to
• Understand how to build packages that can be used anywhere.
• Describe foundation of interfaces.
• Explain how to use existing packages..
• Understand using interfacesin GUI programming.

7.1. INTRODUCTION
In any programming language, intuitive names should be given for easy identification and
understanding of code without any clash of names. For methods it works with method
overloading. But class names cannot be overloaded. If the name clash in classes is envisaged,
the programmer must somehow limit the scope of the variables (namesapce) where a package
comes handy. Package in Java is a way to organize classes into groups and subgroups. Internally
packages are organized into folders with the same names used in packages. In java, package is
a unit where one can pack various classes together. For example, “io” is a package in java
which contains various input/output related classes. Now, for example, the class name
“DataInputStream” becomes something like “java.io.DataInputStream”. It is a good practice
to use a package for the programs, though java takes the current folder as default package if no
package statement appears at the top. An interface declared within another class or interface is
known as nested interface. The nested interfaces are used to group related interfaces. The
nested interface cannot be accessed directly. Nested interface must be public if it is declared
inside the interface but it can have any access modifier if declared within the class. Since Java
8, interfaces can have a default implementation of an abstract method, which was not possible
with earlier versions. Consider that a class X used an interface Y and therefore has implemented
the methods declared in Y. Now if a new method is to be added in the interface Y for any
enhancement, then X should also implement it which was not done so far.

7.2. PACKAGES IN JAVA


In any programming language, intuitive names should be given for easy identification and
understanding of code without any clash of names. For methods it works with method
overloading. But The class names cannot be overloaded. If the name clash in classes is envisaged, 85
the programmer must somehow limit the scope of the variables (namesapce) where a package
comes handy. Package in Java is a way to organize classes into groups and subgroups. Internally
packages are organized into folders with the same names used in packages. In java, package is
a unit where one can pack various classes together. For example, “io” is a package in java
which contains various input/output related classes. Now, for example, the class name
“DataInputStream” becomes something like “java.io.DataInputStream”.
This is particularly useful for libraries. Users (client programmers) of that library can use
certain routines of the library thus avoiding the need for rewriting code. The library creator
must have the freedom to make modifications and improvements with the certainty that the
client code won’t be affected by those changes. This can be achieved through convention. For
example, the library programmer must agree to not remove existing methods when modifying
a class in the library, since that would break the client programmer’s code.
The packages are generally packed into archived jar (derived from Java archive) files with the
jar tool provided by Java. They are normal zip files which can be handled by any zip/unzip
tool like 7-zip. If a jar file is opened, the folder structure can be observed, which matches the
dot notated package name. For example, the DataInputStream.class file will be in ‘./java/io
directory’.
To use existing package, simply import them to the current program using import statements at
the beginning (top) of the program (before the class definition).
Defining a Package:
It is a good practice to use a package for the programs, though java takes the current folder as
default package if no package statement appears at the top.
To create a new package, the key word “package: must be used as the first non comment line
of the java file (even before import statements).
package mypackage;
This line declares that the classes declared within this java file as components of a library
named “mypackage”. In other words, public class name within this compilation unit is under
the umbrella of the name mypackage, and anyone who wants to use the name must either fully
specify the name or use the import keyword in combination with mypackage (using the choices
given previously). Note that the convention for Java package names is to use all lowercase
letters, even for intermediate words.
If someone package mypackage;
public class MyClass {
// . . .
wants to use MyClass they must either use the import keyword or explicitly use the package
name to make the name or names in mypackage available. The alternative is to give the fully
qualified name:
mypackage.MyClass m = new mypackage.MyClass();
Or
import mypackage.*;
// . . .
MyClass m = new MyClass();
Following Example creates a package called “mypackage”. The file name should be
86 Account.java and should be placed in a directory “./mypackage”
package mypackage;
class Balance {
String name;
Double balance;
Balance (String s, double val){
name = string;
balance = val;
}
void show (){
System.out.println(“Name: “ + name + “Balance: Rs. “ +
balance);
}
}
class Account{
public static void main(String args[]){
Balance b[] = new Balance [2];
b[0] = new Balance(“Sekhar”, 123.45);
b[1] = new Balance(“Chandra”, 432.15);
for (int I =0; I<2; I++){
System.out.println(b[I].show();
}
}
}
compile the file in java/mypackage, which gives two classes in the same directory with the
names Balace.class and Account.class. Run the program by calling the fully qualified file
name as:
java mypackage.Account
If someone tries to execute the program by issuing the command “java Account”, java gives an
error since it is now a part of the package “mypackage”.
Any number of classes can be placed in mypackage and if required, they can be even zipped to
a single file by using either jar or utility like winzip. The path must be included to the
CLASSPATH variable.
Setting Class Path
Consider that a new package is downloaded or created by the user. To use this package, it must
be in the classpath environment variable. Even for Java standard classes like java.lang or
java.io, etc, they must be added to a special environment variable called CLASSPATH. The
first chapter describes how to create/modify this variable.

87
Access Protection
Package controls the access of how the components are bundled together into a cohesive library
unit. Access specifiers are affected by whether a class is in the same package or in a separate
package. Following table gives the possible access levels with respect to packages:
private default protected public
same class yes yes yes yes
same package subclass no yes yes yes
same package non-subclass no yes yes yes
different package subclass no no yes yes
different package non-subclass no no no yes
Importing Packages:
A package is what becomes available when the import keyword is used like:
import java.util.*;
This brings in entire utility library that is a standard part of Java. If a specific class from this
package is required (say a class called Hashtable), it can be imported exclusively with “import
java.util.Hashtable;” statement in which case no other class in java.util is available. The
programmer may directly refer to it in the program with its fully qualified name
java.util.Hashtable without the import statement. However, if it is referred to it with full name,
every time when the class is used, full name must be used which is cumbersome. If the package
is imported, it can be referred simply as Hashtable.
When a package is imported as a whole using * (as in java.util.*), Java compiler is smart
enough to include only the used classes from the package into the compilation unit thus
optimizing the byte code. Hence using “import java.util.*;” and “import java.util.Hashtable;”
have the same output if Hashtable is the only class that is used. The only overhead is the
compilation time, which takes a small extra time in searching for used classes which is negligible
considering the power of the machines today.
Check Your Progress

Note: a) Space is given below for writing your answers


b) Compare your answers with the one given at the end of the unit

1.How do you declare a package?


............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

7.3 INTERFACES IN JAVA


In Java the interface keyword takes the abstract concept one step further. An interface is used
to express an aspect of a class other than what it inherits from its parent. An interface is a
collection of constants, default methods (since Java 8) and method declarations (without method
implementation). Constants must be static and final. The interface imposes a rule that all
classes that implement it should define all the methods that are declared in the interface. This
brings uniformity in method names and implementation.
88
An interface provides only an outline but no implementation just like an abstract class. Interface
also brings uniformity among various programmers and designers. Contrary to the inheritance,
where, classes can have only one parent class, any number of interfaces can be attached to a
single class that implements them. A child class that extends a parent class may also implement
an interface of its own, to gain some additional behavior. The following best describes an
interface in java:
Similarities between class and interface:

• An interface is also written as a java file with .java extension

• An interface can contain any number of methods.

• A variable of interface type can be used to reference the implemented class type object
just like a base class variable can reference a subclass type object
Differences between interface and class
• Interface cannot be instantiated.
• Interface does not have any constructors.
• All of the methods in an interface are abstract.
• All data members must be static final.
• An interface cannot be extended by classes. Only another interface can extend it.
• A class can implement multiple interfaces.
Defining an Interface
The definition of an interface looks somewhat like a class definition. But no objects can be
constructed from it. Objects can be constructed from a class that implements an interface. The
definition of an interface is as below:
interface InterfaceName{
constant definitions
method declarations (without implementations)
}
A method declaration is simply an access modifier, return type, and method signature followed
by a semicolon.
Here is an example interface definition:
interface MyInterface{
public static final int aConstant = 32; // constant
public static final double pi = 3.14159; // Constant
public void methodA( int x ); // Method declaration
double methodB(); // Method declaration
}
A method in an interface cannot be made private. A method in an interface is public by default.
In the example methodB is public even though it does not say so. A constant is automatically
taken as static if ‘static’ keyword is missing in the definition.
Variables in Interfaces 89
An interface is a collection of constants and method declarations only. It cannot contain variables
like normal classes. However, constants can be declared in the interfaces, but must be declared
as static and final. Also by default, the variables and methods that are defined are public. It
cannot contain other access modifiers.
Implementing Interfaces
A class definition that implements an interface must specifically use the keyword “implements”
in its definition as below. Note that a class always extends just one parent but may implement
several interfaces.
class SomeClass extends SomeParent implements interfaceName{
………
}
Following rules are applicable for interfaces:
• A class that implements an interface must implement each method in the interface.
• Each method must be public (this happens by default).
• Constants from the interface can be used as if they had been defined in the class.
• Constants should not be redefined in the class.
• Multiple interfaces can be given with comma separator.
Nested Interfaces
An interface declared within another class or interface is known as nested interface. The nested
interfaces are used to group related interfaces. The nested interface cannot be accessed directly.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
Syntax of nested interface which is declared within the interface
interface ifaceName{
...
interface nestedIfaceName{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nestedIfaceName{
...
}
}
Example of nested interface which is declared within the interface:
interface Display{
90
void show();
// Nested Interface
interface Message{
void msg();
}
}
// Now define the main class that implements both
public class Test implements Display, Display.Message{
public void show(){
System.out.println(“Hello display interface”);
}
public void msg(){
System.out.println(“Hello nested message interface”);
}

// Main method to execute this class


public static void main(String args[]){
// Referencing Test with Display interface
Display d = new Test();
d.show();
//m.msg(); // Error - msg() is not defined in Display
// Referencing Test with Message interface
Display.Message dm = new Test();
dm.msg();
//dm.show(); // Error - Show is not defined in Message
}
}
Extending Interfaces
An interface can be extended just like a class to add new method declarations to an existing
interface. This can also be used to combine several interfaces into a single interface.
Example:
interface A {
void method1();
}
interface B extends A {
int ERROR = 10;
void method2(); 91
}
class Test implements B {
public void method1() {System.out.println(“Method 1”);}
public void method2(){
System.out.println(“Method 2”);
}
public static void main(String args[]){
B c = new Test();
c.method1();
c.method2();
System.out.println(B.ERROR);
}
}
In the above example, interface B extends interface A to add a new constant ERROR and a
new method ‘method2()’. The implementing class must implement both methods declared in
A and B interfaces. The variable of type B is used to access the Test type object. Note that if
variable of type A is used, only methods from interface A can be accessed.
Applying Interfaces
Interfaces are provided to achieve standardization of various names in advance, before somebody
implements it. Consider the following example, which declares an interface and implements
the defined interface. If a class is implementing an interface, it must implement all the functions
that are defined in that interface.
interface Area {
public static final double PI = 3.14159;
public double area();
}
abstract class Shape implements Area{
public double x, y;
public setx(){ x = 0.0;}
public setx(double x){ this.x = x;}
public sety(){ y = 0.0;}
public sety(double y){ this.y = y;}
}
class Rectangle extends Shape{
public double area( ){
return x* y;
}
}
92
class Circle extends Shape{
public double area(){
return Area.PI * x * x;
}
class TestArea{
Rectangle r = new Rectangle();
r.setx(10.0);
r.sety(20.0);
System.out.println(“Area of Rectangle is: “ + r.area());
Circle c = new Circle();
c.setx(5.0);
System.out.println(“Area of Circle is: “ + c.area());
}
}
In the above example, the interface mandates that the area() method to be implemented without
any change to its signature.
Default Interface Methods
Since Java 8, interfaces can have a default implementation of an abstract method, which was
not possible with earlier versions. Consider that a class X used an interface Y and therefore
has implemented the methods declared in Y. Now if a new method is to be added in the interface
Y for any enhancement, then X should also implement it which was not done so far. Hence the
class X gives an error since the new interface is used with old code of X. To overcome this
issue, or to maintain backward compatibility of the interfaces, Java 8 introduced the concept
of default methods which allow the interfaces to have methods with implementation without
affecting the classes that implement the interface.
Default interface methods allow adding new methods to an interface that are automatically
available in the implementations. Thus, there’s no need to modify the implementing classes.
interface MyInterface{
public void square(int a);
// default method
default void show(){
System.out.println(“Default Method called”);
}
}
class Test implements MyInterface{
public void square(int a){
System.out.println(a*a);
}
public static void main(String args[]){ 93
Test t = new Test();
t.square(4);
t.show();
}
}
Output:
16
Default Method called
Here the show() is declared in MyInterface as default method which can be used in the
implementing class without implementing it again.
Static Methods:
The interfaces can have static methods also just like static methods of classes. If a method is
declared as static, then it can be directly accessed using interface_name.method_name().
interface MyInterface{
public void square (int a);
// static method
static void show(){
System.out.println(“Static Method called”);
}
}
class Test implements MyInterface{
public void square (int a){
System.out.println(a*a);
}
public static void main(String args[]){
TestClass t = new Test();
t.square(4);
MyInterface.show();
}
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit

2. What is default methof?


............................................................................................................................................................
............................................................................................................................................................
94
............................................................................................................................................................
7.4. SUMMARY
This chapter introduces the packages, how to create a package and how to use it in other
applications. The concept of interface which is similar to abstract class is given in detail. The
packages are generally packed into archived jar (derived from Java archive) files with the jar
tool provided by Java. They are normal zip files which can be handled by any zip/unzip tool
like 7-zip. If a jar file is opened, the folder structure can be observed, which matches the dot
notated package name. For example, the DataInputStream.class file will be in ‘./java/io directory.
An interface provides only an outline but no implementation just like an abstract class. Interface
also brings uniformity among various programmers and designers. Contrary to the inheritance,
where, classes can have only one parent class, any number of interfaces can be attached to a
single class that implements them. A child class that extends a parent class may also implement
an interface of its own, to gain some additional behavior. The following best describes an
interface in java:Since Java 8, interfaces can have a default implementation of an abstract
method, which was not possible with earlier versions. Consider that a class X used an interface
Y and therefore has implemented the methods declared in Y. Now if a new method is to be
added in the interface Y for any enhancement, then X should also implement it which was not
done so far. Hence the class X gives an error since the new interface is used with old code of
X. To overcome this issue, or to maintain backward compatibility of the interfaces, Java 8
introduced the concept of default methods which allow the interfaces to have methods with
implementation without affecting the classes that implement the interface.

7.5. CHECK YOUR PROGRESS MODEL ANSWERS


1. To create a new package, the key word “package: must be used as the first non comment
line of the java file (even before import statements).
2. Actually interface contains only method declarations. This method will be implemented
in in an interface

7.6. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Explain the packeges using a java program
2. Describe nested interfaces using a java program.
3. Explain hw do extend and implement interfaces using java program
II. Answer the following questions in about 15 lines each
1. Describe the similarities, difference between packages and classes.
2. Write a program in java to demonstrate defult methods in interfaces..
3. Describe Access protection rules in packages

95
7.7. GLOSSARY
Interface : Contains constants, method declaratons, default
methods.
Constant : Final variables such as pi=3.1414.
Package : Container which contains classes and interfaces to
reuse names.
Defualt Method : A method that is implemented in an interface.
Nested Interface : Interface with in another interface.

96
UNIT-8: JAVA EXCEPTION HANDLING
Contents
8.0 Objectives
8.1 Introduction
8.2 Java Exception Handling frame work
8.3 Chained exceptions
8.4. Exceptions added in Java 8
8.5 Summary
8.6 Check your progress Model Answers
8.7 Model Examination Questions
8.8 Glossary

8.0. OBJECTIVES
After studying this unit, you should be able to
• Understand the Java exception handling framework.
• Describegracefully using this framework.
• Explain how to handle different types of exceptions..
• Understand newly addedexceptins in Java 8.

8.1. INTRODUCTION
An exception is an abnormal condition that arises in a code sequence during runtime. A program
often encounters problems as it executes such as trouble reading data, illegal characters in the
data, or an array index might go out of bounds etc. Java Errors and Exceptions enable the
programmer deal with such problems. Java provides a neat way to recovers from errors and
keeps on running the program by handling these error conditions gracefully. This is very
important as far as a program is concerned since the program should be robust and should not
crash when the user makes an error. Java classifies these kinds of errors into two types, viz.
exceptions and errors. The difference between error and exception in Java is that exceptions
can be handled at the run time whereas errors cannot be handled. An Error is a critical condition
that cannot be handled by the user most of the time and the program is terminated eventually

8.2. JAVA EXCEPTION HANDLING FRAME WORK


An exception is an abnormal condition that arises in a code sequence during runtime. A program
often encounters problems as it executes such as trouble reading data, illegal characters in the
data, or an array index might go out of bounds etc. Java Errors and Exceptions enable the
programmer deal with such problems. Java provides a neat way to recovers from errors and
keeps on running the program by handling these error conditions gracefully. This is very
important as far as a program is concerned since the program should be robust and should not
crash when the user makes an error.

97
Java classifies these kinds of errors into two types, viz. exceptions and errors. The difference
between error and exception in Java is that exceptions can be handled at the run time whereas
errors cannot be handled. An Error is a critical condition that cannot be handled by the user
most of the time and the program is terminated eventually. The rest of this chapter discusses
how to handle the Exceptions in Java programs.
Exception Class Hierarchy
Class Exception and class Error both descend from the class Throwable which in turn is descend
from the Object. The Error class is final and nothing can be done with this since these are
catastrophic failures. The Exception class is further extended with RuntimeException. The
following diagram represents the class hierarchy implemented by Java.

Object

Throwable

Error Exception

Runtime
Exception

Figure 8.1
Often the problem is caused by circumstances outside the control of the program, for example,
bad user input or a bad sector in a disk file or a network failure etc. A Java program provides
five statements to manage the exceptions which are ‘try’, ‘catch’, ‘throws’, ‘throwable’ and
‘finally’.
When an exception occurs, the Java virtual machine creates an object of the class Exception,
which holds information about the problem like line number, location within that line, type of
error, statement that caused the error etc. The Exception object is used to recover from the
problem.
Broadly the exception framework can be defined as follows:
The code that may generate any error is enclosed in a try block (try{ …}). If an error arises
anywhere within the block, the execution is stopped there and directly proceeds to the catch
block (catch(Exception e) {…}). The code in the exception block is executed where the
programmer can take corrective measures or gracefully exits from the program. If the user
wishes to generate a custom Exception and wish to throw it, the throw can be used. If the user
wishes to move out of the method on exception, the method can be declared as throwable.
Consider the following example that reads a number and prints it.
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.print(“Enter a Number: “);

98 int num = scn.nextInt();


System.out.print(“The number is: “ + num);
scn.close(); // Close Scanner
}
}
If the program is run and a number is given as input it prints the value. If a non-number is given
as input say ‘abc’, then it cannot be converted to a number and it throws an exception. The
output when error condition occurs is given below:
Enter a Number: abcd
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Test.main(Test.java:6)
It may be observed that it gives the root cause or exact location of the failure as a hierarchy
starting from bottom. Here the source of problem is line 6 of Test.java which points to line
2076 of java.util.Scanner.nextInt from Scanner.java and so on and finally lands at line 864 of
java.util.Scanner.throwFor from Scanner.java and the problem is input mismatch.
Types of Exceptions
There are mainly two types of exceptions: unchecked (uncaught) and checked (caught). Error
is considered as the unchecked exception. All uncaught exceptions are handled by the system
itself. For example,
class Test{
public static void main (String args[]){
int d=10;
System.out.println(20/d);
System.out.prinyln(20/d)
System.out.println(“This line will not be printed”);
}
}
In the above example, it returns with an exception ArithmeticException, saying that it is a / by
zero exception at line 4 of Test.java. Those exceptions that occur during runtime like divided
by zero etc., are known as “Uncaught” or “Unchecked Exceptions”, since the compiler will
not flag any error even if these are not handled by the programmer. A default system exception
handler will handle them and terminate the program. The compiler knows that some statements
or classes may likely generate exceptions and it flags an error when they are not explicitly
handled by the programmer. These are called “Caught” or “Checked Exceptions”. For example,
all file operations may generate IOException and hence, these operations must be handled
separately with a try catch block explicitly.

99
Java’s Built-in Exceptions
Java has a rich set of built-in exceptions. Some of them are given below:
Unchecked Exception Meaning
ArithmeticException Arithmetic Errors such as divided by zero
ArrayIndexOutOfBounds Array index is outside the size of the array
ClassCastException Invalid Cast operation
IlligalArgumentException Wrong arguments in calling a method
IlligalThreadStateException Operation is not compatible with current thread state
IndexOutOfBoundsException Array index is out of bound
NullPointerException Invalid use of null pointer for reference
NumberFormatException Invalid conversion of a string to a number
SecurityException violation of security
StringIndexOutOfBounds Attempt to index outside the bounds of a string
UnsupportedOperationException Unsupported operation was encountered

Checked Exception Meaning


ClassNotFoundException Class Not Found
IllegalAccessException Access to the class is denied
InterruptedException One thread has been interrupted by another
NoSuchFieldException a requested field is not available
NoSuchMethodException requested method not available
IOException Error occurred in I/O operations
The Try and Catch
To catch an exception that may be encountered within a block of code, the following procedure
is followed in Java programs:
• The code that might throw an exception is put inside a try{} block.
• The code that handles the exception is put inside a catch{} block.
• The catch black may be absent if the program is designed so, which is not an error.
However, this is very rare case.
The general syntax for the try-catch is as follows:
try{
// statements, some of which might throw an exception
}
catch(ExceptionType2 e){
// statements to handle this type of exception
}

100 catch(ExceptionType2 e){


// statements to handle this type of exception
}
……………..// any number of catch blocks
// Lines of normal code follows

Note the multiple catch blocks are allowed in Java which is explained shortly. After the catch{}
block is executed, execution continues with the statement that follows the catch{} block
(Execution does not return to the try{} block.).
Nested Try Catch
Nesting of try catch blocks is allowed in Java where the inner ‘try’ block uses its own ‘catch’
block first and if it doesn’t match the exception type, then it goes to the catch block of outer
try. The general syntax of a nested try catch is as follows:
....
try{
outer try block statement(s);
...
try{
inner try block statement(s);
...
}
catch(Exception e){
inner catch block statement(s)
}
outer try block statement(s);
...
}
catch(Exception e){
outer catch block statement(s)
}
....
Multiple Catch Blocks
There can be zero or more catch blocks for a single try block. The compiler will choose the
appropriate block depending on the exception type. If there is no match found in the catch
block(s), the default system exception handler will take control which prints the stack trace
and then terminates the program. Following is the modified code of the above example with
try catch blocks added to handle the errors:
public class Test{
public static void main(String[] args){
101
try{
int a[]=new int[10];
int x = 0;
String s=null;
//System.out.println(a[100]);//1.Generates Exception
//System.out.println(10/x);//2.Generates Exception
System.out.println(s.toUpperCase());//3.Generates Exception
}
catch(ArithmeticException e){
System.out.println(“ArithmeticException occured”);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(“ArrayIndexOutOfBoundsException occured”);
}
catch(Exception e){
e.printStackTrace(System.out);
}
System.out.println(“End of code”);
}
}
In the above example, there are three System.out.println statements, each of which is designed
to generate a different kind of exception which are an ArrayIndexOutOfBounds exception, an
Arithemetic exception and a NullPointer exception respectively. Comment any two lines and
the third line generates that particular exception.
There are some important points to observe here. The first is that the program doesn’t have a
catch block explicitly for the NullPointerException type. However, Exception is the base class
for all the exceptions and matches any kind of exception. Hence, any unmatched exception
will be automatically finds a match here and this block will be executed.
Hence, if the catch(Exception e) block is placed as the first catch block, it matches everything
and no other catch block is executed. Hence the generic catch block must be the last.
The other statement that is used is the “e.printStackTrace(Stream s)” in the last catch block.
This is a built-in method in the Exception class that prints possible elaborated error message
on the given stream (in this case the System.out which defaults to screen).
User Defined Exceptions with Throw and Throws
User defined exceptions can be created by extending the Exception built-in class of Java. The
user just needs to override the toString() method apart from any initialization work. Following
example gives an idea of how a user defined exception can be created.
// User defined Exception class
Class MyException extends Exception{
102
String msg;
MyException (String message){
this.msg = new String (message);
}
public String toString(){
return “Error: “ + msg;
}
}
// Class that uses the user defined exception
class ExceptionDemo{
static square(int a) throws MyException{
if (a < 0) throw new MyException(“Negative Value” +
“cannot be given here”);
System.out.println(“Square of “ + a + “= “ + a*a “);
}
public static void main (String args[]){
try{
square(1);
square(-1); // Generates an error
}
catch (MyException e){
System.out.println(“Exception caught: “ + e); }
}
}
In the above example, when a negative number is passed to method ‘square()’, it returns an
exception which is handled by catch block in the main. The throws keyword after any method
indicates the compiler that this method may generate the exception of given type and must be
caught when this method is called. The throw keyword is used to manually generate and trigger
an exception. For example, to generate an exception even though there is no error, a statement
like “throw new ArithmeticException();” may be added anywhere in the program. When the
execution reaches here, the exception is generated and the program will be terminated, if not
handled properly.
The Finally{} Block
If an exception occurs in a program, it is immediately thrown to the method that called it
which may terminate the program or goes to the catch block. In some cases a resource like a
file may be opened and if an exception occurs, the resource might not be closed properly,
leaving the resource unusable by others or may corrupt it. Similar clean up may be needed in
many cases, where graceful exit is required. In such case, after all the catch blocks, a finally{}
block may be used which ensures that statements within that block will always run, no matter
how the try{} block was exited. Here is the try/catch/finally{} structure.
103
try{
// statements, some of which might throw an exception
}
catch(ExceptionType_1 e){
// statements to handle this type of exception
}
.... // more catch blocks
finally{
// statements which will execute no matter
// how the try block was exited.
}
// Statements following the structure
There can only be one finally{} block, and it must follow the catch{} blocks if any. If the try{}
block exits with or without exceptions, the control goes to the catch block and catch block
takes care that the finally{} block is executed before it takes an action. The finally block will
not be run if a system error occurs which cannot continue the program in any way (like a stack
overflow) or the catch block explicitly terminates the program with “System.exit()” statement.
Following example illustrates the finally block.
public class Test
{
public static void main(String[] args)
{
Try
{
//System.out.println(10/0);// ArithmeticException
}
catch(NullPointerException e) {
// do nothing
}
finally {
System.out.println(“End of code”);
}
System.out.println(“Last Line”);
}
}
In this example, the main throws an ArithmeticException, which is not caught by the program.
Hence, the default system handler will intervene and terminates the program. However, before
it terminates the program, the finally block is executed and the last line will not be executed
104
since it is outside the finally block. The output will be like this:
End of code
Exception in thread “main” java.lang.NullPointerException
at Test.main(Test.java:9)
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What is an exception?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

8.3. CHAINED EXCEPTIONS


Chained Exceptions allows one exception describes cause of another exception. For example,
an integer is read from keyboard and it is used as a divisor in another statement. Suppose that
the read failed and the value is set to zero. Here the exception will be an ArithmeticException
because the denominator is zero but the actual cause of exception was an I/O error which
caused the divisor to be zero. The method will throw only ArithmeticException to the caller.
So the caller is not given the actual cause but only given the surfaced cause. Chained Exception
is used in such situation.
Java provides a constructors in Throwable class which support chained exceptions:
Throwable(Throwable cause)
Throwable(String msg, Throwable cause).
Here, cause is the exception that causes the current exception and msg is a message. The
Throwable class also provides methods to support chained exceptions:
getCause() – This method returns actual cause of an exception.
initCause(Throwable cause) – This method sets the cause for the calling exception.
Following is an example for chained exception:
public class ChainedExceptionTest{
public static void main(String[] args){
try{
// Creating an exception
NumberFormatException ex =
new NumberFormatException(“Exception”);
// Setting a cause of the exception
ex.initCause(new NullPointerException(
“This is the main cause”));
// Throwing an exception with cause.
throw ex; 105
}
catch(NumberFormatException ex){
System.out.println(ex); // print the exception
System.out.println(ex.getCause()); // Print the cause
}
}
}
Output:
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is the main cause
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is changed exception?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

8.4. EXCEPTIONS ADDED IN JAVA 8


There are three features added in Java 8, which are sometimes useful in reducing the code and
making the program robust. These three are:
• Automatic resource release (called try with resource)
• Multiple Exceptions in a single catch block (called multi-catch)
• Rethrow of Exception (called rethrow or final rethrow)
The try with resource
Resource closing is an important activity in any program. In case if resource is not closed, it is
not usable or may be corrupted. Java introduces a mechanism with try block that allows declaring
resources within brackets after the try keyword and before the block begins. Any resource
opened this way is automatically closed which works just like finally block. Following is an
example of copying a file in Java (ignore any file opening statements for now):
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test{
public static void main(String[] args){
try(
FileInputStream fin=new FileInputStream(“infile.txt”);

106
FileOutputStream fout= new FileOutputStream(“outfile.txt”);
)
{
int i;
do{
i=fin.read(); // Reads one byte from fin
if(i!= -1) {
fout.write(i); // If not end of file (-1), write it
}
}while(i != -1);
System.out.println(“File Copied”);
}
catch(IOException e){
System.out.println(“Error Occurred. “+e);
}
}
}
In the above example, fin.close() and fout.close() statements must be present in earlier versions
of Java. Howver, in this case since these resources are declared within try block scope, they
are automatically closed even when an exception occurs.
Multi-Catch blocks
In many cases, there will be common code for some exceptions where each exception type
must be handled with a separate catch block or a generic “Exception” type catch block must be
used. However, in Java 8, multiple exception types can be given for catch block with a pipe (|)
symbol. Following example explains the use of multi-catch block in Java 8.
import java.util.*;
public class Test {
public static void main(String[] args) {
try {
int x;
Scanner scn = new Scanner(System.in);
System.out.println(“Enter a Number:”);
x = scn.nextInt();
scn.close();
System.out.println(“10/x = “ + (10/x));
}
catch(InputMismatchException | ArithmeticException ex){
System.out.println(“Error Occurred. “+ex);
} 107
}
}
The above example can throw two types of exceptions. When the user given a non number
(like abc) as input, it throws “InputMismatchException” and when a zero is given, it throws
“ArithmeticException” error. Both are handled with a single catch block using the multi-catch
feature of Java 8.
The Final Rethrow
The catch block can throw an exception from within it. This is known as rethrow, which was
supported since early versions of Java. However, the final Throwable type is introduced since
Java 7. If a catch block handles all exceptions, makes several operations and then rethrow it, it
can be implemented just by using an Exception type catch block. The big problem is that the
method must add a throws clause to the method signature to manage the new exception launched
by this code where the type is to be defined which is hard to get. This can be done with the
final Throwable without adding an exception throws clause:
try {
// some code
} catch (final Throwable ex)
{
// some more code
throw ex;
}
Using the final keyword allows to throw an exception of the exact dynamic type that will be
throwed. So if an IOException occurs, an IOException will be throwed. However, this feature
is not preferred by many programmers as it will not give any leverage since Exception type
catch and throw is enough for that.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What are three exceptions added newly?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

8.5. SUMMARY
This chapter introduces the Exception handling framework implemented in Java. The use of
try-catch blocks, multiple catch blocks, nested and chained exception handlings are briefed.
Java built-in Exceptions and their classification is also explained.Java classifies these kinds of
errors into two types, viz. exceptions and errors. The difference between error and exception
in Java is that exceptions can be handled at the run time whereas errors cannot be handled. An
Error is a critical condition that cannot be handled by the user most of the time and the program
is terminated eventually. The rest of this chapter discusses how to handle the Exceptions in
Java programs.Chained Exceptions allows one exception describes cause of another exception.
108
For example, an integer is read from keyboard and it is used as a divisor in another statement.
Suppose that the read failed and the value is set to zero. Here the exception will be an
ArithmeticException because the denominator is zero but the actual cause of exception was an
I/O error which caused the divisor to be zero.There are three features added in Java 8, which
are sometimes useful in reducing the code and making the program robust. These three are
Automatic resource release (called try with resource), Multiple Exceptions in a single catch
block (called multi-catch),Rethrow of Exception (called rethrow or final rethrow)

8.6. CHECK YOUR PROGRESS - MODEL ANSWERS


1. An exception is an abnormal condition that arises in a code sequence during runtime.
2. Chained Exceptions allows one exception describes cause of another exception
3. Automatic resource release (called try with resource), Multiple Exceptions in a single
catch block (called multi-catch), Rethrow of Exception (called rethrow or final rethrow)

8.7. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Explain the nested try catch blocks using a java program
2. Write a program to demonstrate multiple catch bloks in one try block..
3. Explain Newly added three exceptions in java 8 with examples.
II. Answer the following questions in about 15 lines each
1. Describe the try catch finally blocks.
2. Explin heirachy of excetion classes with a diagram..
3. Write an erro program that causes arthimatic and input mismatch exceptions

8.8. GLOSSARY
Exception : An exception is an abnormal condition that arises in a
code during runtime
Changed Exception : allows one exception describes cause of another
exception
Cheked Exception : The compiler will not flag any error even if these are
not handled by the programmer..
IOException : Error occurred in I/O operations
ArithmeticException : Arithmetic Errors such as divided by zero.

109
UNIT-9: JAVA COLLECTIONS
Contents
9.0 Objectives
9.1 Introduction
9.2 Java Collections Frame Work
9.3. Important Collection Classes
9.4 Summary
9.5 Check your progress Model Answers
9.6 Model Examination Questions
9.7 Glossary

9.0. OBJECTIVES
After studying this unit, you should be able to
• Understand Java collection framework.
• Describe java util package components.
• Explain how to use different types of objects defined in this framework...
• Understand important colectio of classes.

9.1. INTRODUCTION
Power of any language comes from its representation and organization of data in the program.
Java exceeds in this respect with its powerful collections framework, which defines many new
data containers. These containers can handle almost any type of data. These containers have
enough methods in each class to manage the data they hold like insert, delete, modify and
retrieve apart from many other methods like querying, comparing and sorting data. Java has a
rich collection of various general purpose interfaces and classes. These classes are very generic
and cater to almost all the day to day needs of programming. These classes are packed in the
‘java.util’ package, which should be imported if one of the classes is used in the program. The
list interface provides some important methods which are essential in handling and manipulating
the lists of objects. ArrayList is one of the most used implementation of the List
interface.HashMap is another important tool in programming. It is not derived from the
Collection interface, but it has Map interface as the base class. The HashMap stores data as
Key-Value pairs, where key and value can be objects of any type, though generally key is
limited to primitive data types like integers and strings. Here the map does not allow duplicate
keys.

9.2. JAVA COLLECTIONS FRAMEWORK


Power of any language comes from its representation and organization of data in the program.
Java exceeds in this respect with its powerful collections framework, which defines many new
data containers. These containers can handle almost any type of data. These containers have
enough methods in each class to manage the data they hold like insert, delete, modify and
retrieve apart from many other methods like querying, comparing and sorting data.
110
Formally a collection is an object that can represent groups of other objects such as Strings,
user defined Objects etc. Java collections framework is a generalized architecture to represent
and manipulate these collections. Advantages of a collections framework are:
• Reduces programming effort by providing data structures and algorithms.
• Increases performance by providing optimized code.
• Implementation of all collection classes is uniform and hence learning one will make
the others easy.
• Since most of the data management code is already implemented, coding effort in design
and implementation will be reduced.
• Enables software reuse since they provide a standard interface for collections and
algorithms.
Java has a rich collection of various general purpose interfaces and classes. These classes are
very generic and cater to almost all the day to day needs of programming. These classes are
packed in the ‘java.util’ package, which should be imported if one of the classes is used in the
program.
Interfaces:
Some important interfaces and classes in the java.util package are listed below:
Itarable It is the base of all interfaces including the Collection.
Collection The root interface in the collection hierarchy.
Comparator A comparison function, which imposes a total ordering on some
collection of objects.
Enumeration An object that implements the Enumeration interface generates a
series of elements, one at a time.
List An ordered collection (also known as a sequence).
Observer A class can implement the Observer interface when it wants to be
informed of changes in observable objects.
RandomAccess Marker interface used by List implementations to indicate that they
support fast (generally constant time) random access.
Set A collection that contains no duplicate elements.
Iterator Used for bidirectional scan through a list of objects
Table 9.1
Iterable
The Iterable interface is the root of Collection interface and hence the root of all other classes
in the framework. It has only one abstract method in it
Iterator <T> iterator() – which returns an iterator of its data type that can be used to fetch
objects from the collection sequentially as follows:
Iterator itr = col.iterator(); - Get iterator from the collection col.
while(itr.hasNext()){
System.out.println(itr.next()); // process next element
}
111
Collection
The Collection class forms the basis for most of the components in the Collection Framework.
Since Java 5, most of the classes are made generic, which means the data type objects can be
declared within angular brackets(<>). Some of the important methods defined by Collection
are as follows:
Method Description
boolean add(obj) Adds obj to the collection. The object can be any data type
boolean addAll(Collection c) Adds all elements from c to the collection.
void clear() Removes all elements from the collection
boolean contains(obj) Returns true if obj is in the collection or false otherwise
boolean isEmpty() Returns true if no object is in the collection or false
otherwise
Iterator iterator() Returns an iterator object for this collection that can be
used to list objects.
boolean remove(obj) Removes the given object if exists.
int size() Returns the number of objects in the collection
<T> T[] toArray(T array[]) Fills objects from the collection into the array and returns
it. If the array is insufficient, it creates a new array that is
sufficient to hold all the elements, in the collection, and
this array will be returned.

Table 9.2
Enumeration:
This interface enumerates the values of a container. The implementing class must declare two
functions
boolean hasMoreElements()
Object nextElement();
Generally a while loop is used to iterate through each object as
while(en.hasMoreElements){ en.nextElement(); }

112
List Interface
The list interface provides some important methods which are essential in handling and
manipulating the lists of objects. ArrayList is one of the most used implementation of the List
interface. Some of the methods are as follows:
Method Description
void add(int index, E element) Inserts the element at the given position in a list.
boolean add(E e) Appends the specified element at the end of a list.
boolean addAll(Collection c) Appends all of the elements in the given collection to the end
of a list.
void clear() Removes all elements from this list.
boolean equals(Object o) Compare the given object with the elements of a list.
E get(int index) Returns the element at the index
boolean isEmpty() Returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) Return the index of the last occurrence of the given element,
or -1 if the list does not contain this element.
T[] toArray(T[] a) Return an array containing all of the elements in this list in
the same order.
boolean contains(Object o) Returns true if the list contains the given element or false
otherwise
int indexOf(Object o) Returns the index of the first occurrence of the given element,
or -1 if the List does not contain this element.
E remove(int index) Removes the element at the given position.
boolean remove(Object o) Removes the first occurrence of the given element.
boolean remove All(Collection c) removes all the elements of the collection
from the list.
void sort(Comparator c) Sorts the elements of the list on the basis of given comparator.
List<E> subList Returns a sub list of elements within the given range.
(int fromIndex, int toIndex) Returns the number of elements present in the list.
int size()
Table 9.3
All the methods from various interfaces are available in the classes that implement those
interfaces. Collection interface methods are available to all the Classes:

113
Some of the important classes that implement the Collection framework are given below
ArrayList Container for sequential data just like an array but expandable
HashMap Extends AbstractMap and provides a hash table
implementation
HashSet Provides a collection of keys which can be queries for available
or not. It implements AbstractSet interface.
LinkedList Linked list implementation of the List and Abstract
Sequential List interfaces.
TreeSet It extends AbstractSet and implements a set stored in a tree
structure.
TreeMap Extends AbstractMap to provide tree structured hash table.
Table 9.4
Other Important Classes in java.util Package
Following is a list of important classes other than Collection framework components. Again
the list is large and only important components are presented here. For full list, the reference
manual may be referred.
Arrays This class contains various methods for manipulating arrays
(such as sorting and searching).
BitSet This class implements a vector of bits that grows as needed
and provides bit operations.
Date The class Date represents a specific instant in time, with
millisecond precision.
GregorianCalendar GregorianCalendar is a concrete subclass of Calendar and
provides the standard calendar used by most of the world.
Hashtable This class implements a hashtable, which maps keys to values.
Observable This class represents an observable object, or “data” in the
model-view paradigm.
Random An instance of this class is used to generate a stream of
pseudorandom numbers.
Stack The Stack class represents a last-in-first-out (LIFO) stack of
objects.
StringTokenizer The string tokenizer class allows an application to break a
string into tokens.
TimeZone TimeZone represents a time zone offset, and also figures out
daylight savings.
Scanner Parser class that parses any input stream like System.in, Files and
Strings
Table 9.5

114
Following figure gives a partial hierarchy of the interfaces, abstract classes and implemented
classes purely for the purpose of understanding the collection framework. It is by no means, a
full list. Since the collection has large set of components within it, it is almost impossible to
give the entire picture. However, the user may understand that all the methods available in
Iterable and Collection are available to all the classes. In addition to these, any base class or
base interface methods are also available to the implemented classes. This brings uniformity
of methods and variables across all the collection classes.

Figure.9.1
The full documentation is available with Oracle Corporation’s website.
Some legacy classes like Vector, Hashtable etc. are reengineered to implement these interfaces,
so that they follow the new standards.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit

1. What is the list interface?


............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

9.3. COLLECTION CLASSES


Some of the important classes in “java.util” package are explained in this chapter. The reader
is encouraged to go through the documentation for the entire list of classes in the package.
ArrayList
ArrayList is one of the most used classes in Java as a container. It acts like a dynamic array for
any type of objects where the size can grow or shrink automatically according to the number of
elements in it. It has functions for getting size, converting to array, ensuring a minimum size,
adding and deleting elements etc. To access an element, the get(int index) method may be used. 115
An ArrayList may be constructed using one of its many constructors:
• ArrayList<T>() – Creates a default empty list with a capacity of 10 elements.
• ArrayList<T>(int cap) – Creates a default empty list with a capacity of cap elements.
• ArrayList<T>(Collection c) – Creates a list with a elements from c in that order.
All the methods from Collection and Iterable can be used with ArrayList.
Following example illustrates the use of ArrayList of strings with various operations on it:
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String args[]) {
int i;
ArrayList<String> al = new ArrayList<>();
System.out.println(“Initial Size: “ + al.size()); // size = 0
al.add(“abcd”);
al.add(“def”);
al.add(“ghij”);
al.add(“jklmn”);
System.out.println(“Size Now is: “ + al.size()); // size = 4
System.out.println(“Contents of al are: “ + al);
al.add(1,”pqr”); // Insert at index 1
System.out.println(“Contents of al are: “ + al);
al.remove(1); // remove element at index 1
al.remove(“def”); // Remove element “def”
System.out.println(“Contents of al are: “ + al);

// Listing all elements from list


for(i=0;i<al.size(); i++) {
System.out.println(“Value[“+i+”]=”+ al.get(i));
}
System.out.println(“——————————”);

// Getting elements as an array of Objects


Object a[] = al.toArray(); // Returns array of Objects.
// Since the elements are Objects, they must be casted before using them
for(i = 0; i< a.length; i++) {
System.out.println(“Value[“+i+”]=”+(String)a[i]); //cast as string
}
116
System.out.println (“——————————”);
// Getting elements into an array of Strings directly
String x[] = al.toArray(new String[0]);
for(i = 0; i< x.length; i++) {
System.out.println(“Value[“+i+”]=”+x[i]);
}
System.out.println(“——————————”);
}
}
Note that the second method of getting data as an array of strings, supplies an array list of size
zero. Since it is not sufficient to hold the elements, the method creates a new array of the same
data type (in this case String) with a size equals to the size of the array list.
Output of the program is as follows:
Initial Size: 0
Size Now is: 4
Contents of al are: [abcd, def, ghij, jklmn]
Contents of al are: [abcd, pqr, def, ghij, jklmn]
Contents of al are: [abcd, ghij, jklmn]
Value[0]=abcd
Value[1]=ghij
Value[2]=jklmn
——————————
Value[0]=abcd
Value[1]=ghij
Value[2]=jklmn
——————————
Value[0]=abcd
Value[1]=ghij
Value[2]=jklmn
——————————
A Vector is a class that implements the same interface and is a drop-in replacement for ArrayList
which supports synchronization when used in multi-thread programs. However, due to its
overhead ArrayList is preferred and the use of Vector is very rare.
HashMap
HashMap is another important tool in programming. It is not derived from the Collection
interface, but it has Map interface as the base class. The HashMap stores data as Key-Value
pairs, where key and value can be objects of any type, though generally key is limited to
primitive data types like integers and strings. Here the map does not allow duplicate keys. It
uses a hash function to determine if the given key exists in the map, which makes it very 117
efficient compared to a list, where elements are searched sequentially. HashMap is a kind of
lookup table for the data where each data item is associated with a key (as the keywords in
dictionary). The hierarchy of Map group components is given below:

A hash map can be created with one of its constructors given below:
HashMap<keyType, valueType>( ) - creates a default empty HashMap with keyType object as
key and valueType object as its value.
HashMap<keyType, valueType> (Map m) - Creates a new HashMap with initial data containing
all key-value pairs from map m.
HashMap<keyType, valueType> (int cap) - Creates a HashMap with initial capacity of cap.
HashMap<keyType, valueType> (int capacity, float fillRatio) - Creates a HashMap with given
capacity and fill ratio.
Here fill ratio decides when to expand or shrink memory. For example, for a fill ratio of 0.8,
with capacity of 10 will expand the capacity to 20 when the number of elements reaches 8.
Some of the useful methods of Map interface are given below:
Method Description
Void put(Object key, Object value) inserts an entry in the map.
void putAll(Map map) inserts the given elements from a map
remove(Object key) deletes an entry for the specified key.
void clear() removes all elements from map.
boolean containsKey(Object key) returns true if key exists within the map, else
return false.
boolean containsValue(Object value) returns true if value exists anywhere in the map,
else return false.
V get(Object key) returns the value object for the given key or null.
V getOrDefault(Object key,VdefaultValue) returns the value for a given key, or defaultValue
if the map does not contain the key.
boolean isEmpty() returns true if the map is empty, false otherwise
V replace(K key, V value) replaces the specified value for a given key.
Collection values() returns a collection of all the values in the map.
Table 9.6
Following table gives some important methods defined in HashMap in addition to methods
inherited from its parent classes:

118
Method Description
Set keySet() Returns a set of the keys contained in this map.
int size() This method returns the number of entries in the map.
Following example creates a HashMap, adds some key-value pairs into it, and then removes
some keys based on value or key. Listing of all elements of a HashMap is a little tricky without
iterators (which will be explained shortly). First all the keys are obtained into a Set using
getSet() method and then it is converted to an array. Now using the keys from array, each value
is obtained using get() method.
import java.util.*;
publicclass HashMapTest{
publicstaticvoid main(String args[]) {
int i;
HashMap<String,String> hm = new HashMap<>();
System.out.println(“Initial Size: “ + hm.size()); // size = 0
hm.put(“key0”, “abcd”);
hm.put(“key1”,”def”);
hm.put(“key2”,”ghij”);
hm.put(“key3”,”jklmn”);
System.out.println(“Size Now is: “ + hm.size()); // size = 4
System.out.println(“Contents of hm are: “ + hm);
hm.put(“key1”,”pqr”); // replaces key1
System.out.println(“Contents of hm are: “ + hm);
hm.remove(“key3”); // remove element at index 1
hm.remove(“def”); // Remove element “def”
System.out.println(“Contents of hm are: “ + hm);
// Listing all elements from list
Set<String> keys = hm.keySet();
String k[] = keys.toArray(new String[0]);
for(i=0;i<k.length; i++) {
System.out.println(“Value[“+k[i]+”]=”+ hm.get(k[i]));
}
System.out.println(“——————————”);
}
}
Output of the program is:
Initial Size: 0
Size Now is: 4
Contents of hm are: {key1=def, key2=ghij, key0=abcd, key3=jklmn} 119
Contents of hm are: {key1=pqr, key2=ghij, key0=abcd, key3=jklmn}
Contents of hm are: {key1=pqr, key2=ghij, key0=abcd}
Value[key1]=pqr
Value[key2]=ghij
Value[key0]=abcd
——————————
Accessing Data from Collections
In the previous examples, traversing all the elements of a collection was done using a for loop
either by getting the size of the collection or by getting all the keys. However, the collection
framework provides an easier method through its super class – Iterable, which defines a single
method “iterator()”. This can be used to traverse through all the elements of a collection.
Modern versions of Java supports the simpler ‘for-each’ structure as well.
Accessing Collection with an iterator
Every class that implements Collection interface, has the iterator() method which gives an
iterator object. The iterator object has two methods viz., hasMoreElements() and nextElement()
methods. Using these two methods, any collection can be traversed. Following is an example
for traversing all the elements of an ArrayList. The process is as follows:
Iterator itr = col.iterator(); // Get iterator for the collection col.
while(itr.hasNext()) {
System.out.println(itr.next()); // get value using next() method of iterator
}
Accessing Collection With for-each Loop
In the previous case, an iterator is obtained and a while loop is used to iterate through the
elements. Java has simplified the process with for-each variant of the for loop. For any collection,
the for-each loop is as follows:
for (DataType var:col) { use var here } where var is a variable that will be given next element’s
value every time in the for loop
The variable should be declared within the ‘for’ loop and any variable declared outside the
brackets cannot be used here. Following example demonstrates the use of both iterator and
for-each loop:
import java.util.ArrayList;
import java.util.Iterator;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<>();
al.add(“abcd”);
al.add(“def”);
al.add(“ghij”);
al.add(“jklmn”);
120 System.out.println(“———— Using iterator —————”);
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println(“———— Using for-each —————”);
for(String s:al) {
System.out.println(s);
}
}
}
The data of the array list is printed by both methods correctly when the program is run.
Arrays Class:
Arrays class is added to java.utils in Java 2 and has various static methods for manipulation of
arrays. It has a huge collection of methods (over hundred) where most of them are overloaded
for different data types and generics. Some of the useful functions are given below:
static List asList(Object array[]) - Returns List object from the Array
static int binarySearch(array, value) - Searches for the value in array and returns index if
found or negative value otherwise.
static <T> T[] copyOf(T original[], int newLength) – Copies newLenght elements or nulls if
newLength is greater than the number of elements in the original array and returns a duplicate
array.
static boolean equals(arr1, arr2) - Returns true if both arrays have same elements
static void fill(array, value) - Fills the array with the given value
static void fill(array, start, end, value) - Fills partial array with value
static void sort(array) - Sorts the entire array
static void sort(array, start, end) - Sorts partial array from start to end
static <T> void sort(T arr[], Comparator comp) – Sorts the arr using comparator comp
Following example illustrates the use of Arrays static methods on an array.
import java.util.*;
public class ArrayDemo {
static void display(String msg, int arr[]) {
int i;
System.out.print(msg+”: “);
for(i=0;i<arr.length; i++){
if(i>0){
System.out.print(“, “);
}
System.out.print(arr[i]); 121
}
System.out.println();
}
public static void main(String args[]){
int arr[] = new int[5];
arr[0]= 10; arr[1] = 2; arr[2] = 8; arr[3] = 4; arr[4] = 1;
display(“Initial array”,arr);
Arrays.sort(arr);
display(“After Sort”,arr);
Arrays.fill(arr,2,3,5);
display(“After Fill”,arr);
Arrays.sort(arr);
display(“After Sort”,arr);
int res = Arrays.binarySearch(arr,8);
System.out.println(“Value 8 is at Location “ + res);
}
}
————— Output —————
Initial array: 10, 2, 8, 4, 1
After Sort: 1, 2, 4, 8, 10
After Fill: 1, 2, 5, 8, 10
After Sort: 1, 2, 5, 8, 10
Value 8 is at Location 3
Using User Defined Data in Collections
Collection framework is designed and implemented using Java generics where the data type
can be any object. User defined objects can be managed the same way as with the standard
data types. Following example uses a user defined data type called student with the following
definition:
class Student
{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
122
return (rollno+”, “ + name + “, “ + course);
}
}
Now this data type can be used in any Collection class. As an example, the following program
uses the Student data in the ArrayList:
import java.util.ArrayList;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<Student> al = new ArrayList<>();
ArrayListTest alt = new ArrayListTest();
al.add(alt.new Student(“20A102”, “Bhanu”, “M.A (Economics)”));
al.add(alt.new Student(“20A104”, “Ananda Rao”, “M.C. A”));
al.add(alt.new Student(“20A101”, “Keerthana”, “M.Sc. (Physics)”));
al.add(alt.new Student(“20A103”, “Ranjan”, “M.Sc. (Physics)”));
System.out.println(“———— Using for-each —————”);
for(Student s:al) {
System.out.println(s);
}
}
public class Student{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
return (rollno+”, “ + name + “, “ + course);
}
}
}
Observe how the generic collection is used with user data (<Student>). The output is as follows:
———— Using for-each —————
20A102, Bhanu Kumar, M.A (Economics)
20A104, Ananda Rao, M.C. A
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics) 123
Observe how the Student objects are created using an object of type ArrayListTest. This is
necessary when a program uses an inner class. To avoid this type of instantiation, the Student
class may be defined as a separate class with its own file. The data is printed using the toString
method defined in the Student class.
Sorting User Defined Data in Collections
Consider the above example where four objects of type Student are defined and are printed.
The data is printed in the same order as they were added. However, consider that the data must
be printed in sorted order. Now there is an ambiguity on what field the data should be sorted.
In this case, the user has to define how the compare should work using a special interface
called Comparator or extending the class Comparable. Extending Comparable is not
recommended since it increases the depth of hierarchy of classes and already a class may be
extending another class. Hence, implementing Comparator is the best option.
The Comparator interface declares just one method which is as follows:
class MyComparator implements Comparator<T>{
public int compare (T obj1, T obj2); // where T is any data type
}
Here the compare method should return
negative value if obj1 < obj2
0 if obj1 = obj2
positive value if obj1 > obj2
Mathematically it should return the difference (obj1-obj2). For example, if strings are compared,
the method can use String’s compareTo() method (return obj1.compareTo(obj2);) or if numeric
values are compared, it can use direct difference (return obj1-obj2;)
Following example declares the Comparators based on the name and rollno and sorts data
based on roll number and name.
import java.util.*;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<Student> al = new ArrayList<>();
ArrayListTest alt = new ArrayListTest();
al.add(alt.new Student(“20A102”, “Bhanu Kumar”, “M.A (Economics)”));
al.add(alt.new Student(“20A104”, “Ananda Rao”, “M.C. A”));
al.add(alt.new Student(“20A101”, “Keerthana”, “M.Sc. (Physics)”));
al.add(alt.new Student(“20A103”, “Ranjan”, “M.Sc. (Physics)”));
System.out.println(“———— Unsorted data —————”);
for(Student s:al) {
System.out.println(s);
}
al.sort(new RollnoComparator());
124 System.out.println(“———— Sorted on Roll Number —————”);
for(Student s:al){
System.out.println(s);
}
al.sort(new NameComparator());
System.out.println(“———— Sorted on Name —————”);
for (Student s:al){
System.out.println(s);
}
}
public static class RollnoComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.rollno.toUpperCase().compareTo(s2.rollno.toUpperCase());
}
}
public static class NameComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.name.toUpperCase().compareTo(s2.name.toUpperCase());
}
}
public class Student{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
return (rollno+”, “ + name + “, “ + course);
}
}
}
In the above program two additional classes (‘RollnoComparator’ and ‘NameComparator’)
are defined and in each sort call, one of the object is created and passed as parameter. The sort
method uses the compare method of this object for sorting the data. The output is as follows:
———— Unsorted data —————
20A102, Bhanu Kumar, M.A (Economics)

125
20A104, Ananda Rao, M.C. A
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics)
———— Sorted on Roll Number —————
20A101, Keerthana, M.Sc. (Physics)
20A102, Bhanu Kumar, M.A (Economics)
20A103, Ranjan, M.Sc. (Physics)
20A104, Ananda Rao, M.C. A
———— Sorted on Name —————
20A104, Ananda Rao, M.C. A
20A102, Bhanu Kumar, M.A (Economics)
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics)
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is the Array Class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

9.4. SUMMARY
This chapter introduced the use of Collection framework and java.util package. Some important
classes are explained and examples were given wherever necessary. With this introduction,
the candidate should be in a position to learn about other classes of the package. HashMap
uses a hash function to determine if the given key exists in the map, which makes it very
efficient compared to a list, where elements are searched sequentially. HashMap is a kind of
lookup table for the data where each data item is associated with a key (as the keywords in
dictionary).Every class that implements Collection interface, has the iterator() method which
gives an iterator object. The iterator object has two methods viz., hasMoreElements() and
nextElement() methods. Using these two methods, any collection can be traversed. Following
is an example for traversing all the elements of an ArrayList.Arrays class is added to java.utils
in Java 2 and has various static methods for manipulation of arrays. It has a huge collection of
methods (over hundred) where most of them are overloaded for different data types and
generics.the data must be printed in sorted order. Now there is an ambiguity on what field the
data should be sorted. In this case, the user has to define how the compare should work using
a special interface called Comparator or extending the class Comparable. Extending Comparable
is not recommended since it increases the depth of hierarchy of classes and already a class may
be extending another class. Hence, implementing Comparator is the best option.

126
9.5. CHECK YOUR PROGRESS MODEL ANSWERS
1. Provides some important methods which are essential in handling and manipulating the
lists of objects. 2. It implemnets the array with huge number of built in methods

9.6. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
1. Create a phone directory using a hash map where the key is a phone number and
implement hashmap
2. Write a program to create and access ArrayList with double numbers
3. Write a java program to create and access ArrayList with User Defined Data Type
II. Answer the following questions in about 15 lines each
1. Describe the hierarchy of classes in HashMap..
2. What is list interface? Write about any five built-in metbods in It
3. What is Array class? Write a program to demonstrate Array class

9.7 GLOSSARY
HashMap : HashMap stores data as Key-Value pairs, where key and
value can be objects of any type,
TreeMap : Implements Tree heirachy and derived from SortedMap
Enumeration : This interface enumerates the values of a container. The
implementing class must declare two functions
ArrayList : Is a collection which stoes, iterte array of objects
Collection : Container class which contains various types of objects or
primitive types.

127
128
BLOCK - IV

BACL-END AND FRONT-END TOOLS OF JAVA


This block gives an overall study onJDBC definition, JDBC structure, registering and calling
JDBC drivers, JDBC URL and the connection, using JDBC drivers, Using prepared
statements with mysql database using JDBC, extracting meta-data, transaction management
with JDBC. It also enables the students to understand event handling mechanism, event
classes, key event class, source of events, event listener interfaces, using delegation event
model, adaptor classes, inner classes-Examples of event handling with AWT container and
component classes. This block explains how the Swing isbuilt on AWT, MVC model
connection, swing packages, swing event handling, swing container and components such
as Jlabel and Image icon, JtextField, swing buttons, JTabbedPane, JscrolledPane, JList,
JComboBox, JTable, JTree..

The units included in the block are:


Unit-10: Java Data Base Connectivity
Unit-11: Java AWT and Event Handling
Unit-12: Java Visual Programming with Swing

129
130
UNIT-10: JAVA DATABASE CONNECTIVITY
Contents
10.0 Objectives
10.1 Introduction
10.2 Java Data Base Connectivity
10.3. Using Meta Data
10.4. Transaction Management
10.5. Summary
10.6. Check your progress Model Answers
10.7. Model Examination Questions
10.8. Glossary

10.0. OBJECTIVES
After studying this unit, you should be able to
• Understandimportant concept called Java Database Connectivity (JDBC)
• Describe transaction management.
• Explain how to execute queries on that database through Java programs.

10.1. INTRODUCTION
Java provides a robust API (Application Programming Interface) for connecting and managing
databases of almost all important brands known as JDBC API. It is a part of JavaSE (Java
Standard Edition). JDBC API uses JDBC drivers to connect with the database. JDBC Driver is
a software component that enables java application to interact with the database.The
executeQuery statement returns a ResultSet Object which contains the results and acts as an
iterator for the data. A null indicates that the execution failed. The data from the resultSet
object is retrieved using a while loop with its built-in method next() which advances the current
location to the next record within result set object. The individual columns of a record are
fetched with the getString(), getInt(), getFloat(), … methods with column index that starts
with 1 (not with zero) or with column name in the database.Finally the database connection,
statement, result set etc are closed with their respective close() method. Transaction represents
a single unit of work which may contain one or more SQL statements. If a transaction is
successful, all the statements are executed. If at any stage, one statement fails, all the successful
statements so far should be undone. This process of undoing in case any statement in the
transaction fails, is known as “rollback”.

10.2. JAVA DATABASE CONNECTIVITY (JDBC)


Java provides a robust API (Application Programming Interface) for connecting and managing
databases of almost all important brands known as JDBC API. It is a part of JavaSE (Java
Standard Edition). JDBC API uses JDBC drivers to connect with the database. JDBC Driver is
a software component that enables java application to interact with the database. There are
four types of JDBC drivers:
131
• JDBC-ODBC Bridge Driver(Type 1) – This is used to connect to databases that support
only ODBC (Open DatabaseConnectivity). However, all modern databases support JDBC
and the ODBC is almost extinct and no one is supporting the driver now a days.
• Native Driver(Type 2)– This resides on the client side and every call is translated to
ODBC call and there is no need for an exclusive bridge driver. However it requires that
the vendor driver is installed on each client machine. This is also outdated.
• Network Protocol Driver(Type 3) – It is a driver written entirely in Java. The Network
Protocol driver uses middleware (application server) that converts JDBC calls directly
or indirectly into the vendor-specific database protocol. It requires vendor specific
code in the driver and is difficult to maintain. It is also no more being used.
• Thin Driver(Type 4) – This is also entirely written in Java but uses the JDBC support
from the database. It is the current driver that is most used. There is nothing need to be
installed except the driver.
The type 4 driver is the latest and this is used in the explanation and examples given here. All
major database vendors support JDBC these days.
JDBC Structure
Java application that connects to a database will use JDBC API and registers a Driver
corresponding to the database, which the vendor will supply. Using this driver, the program
connects to the database and executes queries. A block diagram of application with JDBC is
shown below:

132
JDBC offers a uniform procedure and syntax for connecting and querying the database,
irrespective of the vendor and type of database. Following are the entities used in JDBC enabled
programs.
• DriverManager: This class manages a list of database drivers. This is used to establish
a database Connection.
• Driver: This interface handles the communications with the database server which is
transparent to the user.
• Connection: This interface is the handle for all communication with the connected
database.
• Statement: This object is created from the connection which is used to submit the
SQL statements to the database.
• ResultSet: This object holds data retrieved from a database after an SQL query is
executed using Statement object. Result data is retrieved using this object.
• SQLException: This exception is thrown on any errors that occur in a database
application.
Installing JDBC Driver
In normal cases, when database software is installed, it also installs the drivers for that. However,
it is possible to exclusively download the packaged (jar) jdbc driver from the vendor’s website.
In this chapter, MySQL is considered as the database since it is freely available and one of the
most popular databases. The MySQL JDBC driver can be downloaded from the website, which
has a name similar to “mysql-connector-java-5.1.39-bin.jar” where the version number may
vary. The driver may be placed in any directory but the path of the jar file should be in the
CLASSPATH.
Registering and Calling JDBC Drivers
Once the driver is available in the CLASSPATH, it can be used in any Java program. Each
vendor specifies a String for their product. Following are the Strings specified by some of the
popular vendors:
• MySQL - “com.mysql.jdbc.Driver”.
• Oracle - “oracle.jdbc.driver.OracleDriver”
• MS SQL Server - “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Once the driver string is identified, that should be registered using Class.forName() method as
follows:
Class.for Name (“com.mysql.jdbc.Driver”);
For other data databases the appropriate strings may be used. Every JDBC or SQL statement
may throw an exception of type SQL Exception. Hence, all the JDBC connection statements
are inside a try catch block or the method is declared to throw the SQLException with throws
keyword.
JDBC URL and the Connection
After registering the Driver with Class.forname(), the next step is to establish a connection to
the database using its connection ULR. Again each vendor specifies different connection URLs
for their products. The following are URL strings for some popular vendors. Values in square
brackets are optional.
• MySQL - “jdbc:mysql://host[:port]/myDB” where default port is generally 3306
133
• Oracle: “jdbc:oracle:thin:@host[:port]:myDB” where default port is 1521
• MS SQL Server: “jdbc:sqlserver://host[:port];databaseName=uDB;
user=uName;password=uPWD;” where default port is 1433
A connection to MySQL database can be obtained with:
Connection con = DriverManager.getConnection(url,username, userPassword);
The driver manager has two methods to get a connection:
i. public static Connection getConnection(String url)
ii. public static Connection getConnection(String url,String userName,String password)
One of them can be used depending on whether the database supports user name and password
as separate arguments or as a single argument like in Microsoft SQL server.
Using JDBC Drivers
After a connection is established without any problem, the next step is to create a statement
from the connection.
Statement smt = con.createStatement();
Now this statement object is used to execute the query using either executeQuery(“sql
statement”) if it is a data retrieval statement, or executeUpdate(“sql statement”) if it is an
update statement (update, insert or delete).
For updateQuery statements, the result returned will be an integer that tells how many records
are affected by the query. A value of negative indicates an SQL error, 0 indicates no records
were modified and any positive number indicates that many number of records are updated.
The execute Query statement returns a ResultSet Object which contains the results and acts as
an iterator for the data. A null indicates that the execution failed. The data from the resultSet
object is retrieved using a while loop with its built-in method next() which advances the current
location to the next record within result set object. The individual columns of a record are
fetched with the getString(), getInt(), getFloat(), … methods with column index that starts
with 1 (not with zero) or with column name in the database.
Finally the database connection, statement, result set etc are closed with their respective close()
method.
The process steps can be summarized as follows:
Step 1: Import required classes
Step 2: Register the Driver with Driver Manager using Class.forName()
Step 3: Get a connection from the DriverManager
Step 4: Create a Statement from the connection
Step 5: Execute an SQL statement with the statement
Step 6: Process results if it is a Query statement or get number of records affected otherwise
Step 7: Close resources
The following example extracts all records from the table and shows them on the screen.
//STEP 1. Import required packages
import java.sql.*;
134
public class JdbcExample{
public static void main(String[] args){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String user = “guest”;
String pass = “guest123”;
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(driver);
//STEP 3: Open a connection
conn = DriverManager.getConnection(url,user,pass);
//STEP 4: Create Statement
stmt = conn.createStatement();
String sql = “SELECT name, phno FROM test”;
//STEP 5: Execute a query
ResultSet rs = stmt.executeQuery(sql);
//STEP 6: Extract data from result set
while(rs.next()){
//Retrieve by column name
System.out.print(“Name: “ + rs.getString(1) +
“ Ph: “ + rs.getString(2));
}
//STEP 7: Close/release resources
rs.close();
stmt.close();
conn.close();
}
catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
finally{
//finally block used to close resources
try{
135
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(Exception se2){
se.printStackTrace();
}// nothing we can do
}//end try
System.out.println(“Exiting the program”);
}//end main
}//end JdbcExample
To execute this program the MySQL server should be running and the database mydb should
be created. Within the mydb database, there should be a table named ‘test’ should exist. Table
test contains two columns viz., the name of type varchar(20) and the phno of type varchar(10).
Assume that the user name for the database is “guest” and the password is “guest123”.
To create a database with MySQL and a table, refer to any help (either internet or MySQL
documentation or User Guide). Following is a brief list of commands that should be given at
the mysql command prompt and the output from the server:
mysql> create database mydb;
Query OK, 1 row affected (0.00 sec)
mysql> use mydb;
Database changed
mysql> create table test(name varchar(20), phno varchar(10)) ENGINE = InnoDB;
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test values(‘Bhanu’,’12345678');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(‘Pratap’,’23456789');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;

name phno
Bhanu 12345678
Pratap 23456789

2 rows in set (0.00 sec)

136
Prepared Statement
When a query is submitted by the program to the server, the query is first translated into
appropriate query that is understood by the server (compiled). If a query is repeatedly submitted
with different data, the translation step can be reused by converting the data into parameters.
This saves considerable time from second query onwards and results in performance
improvement. For example, consider an insert query that is used to insert 10 records. Instead
of compiling and executing the query 10 times, the prepared statement just compiles it once,
and each time new data is sent as parameters.
Following steps are necessary for using prepared statements in JDBC.
As a first step, a prepared statement is obtained from Connection object using
PreparedStatement ps = con.preparedStatement(sql); where con is the connection object and
sql is the SQL string where each variable data item is denoted with a question (?) symbol.
String sql=”insert into mydb.test values(?,?)”;
Here the two question marks represent the two parameters (name and phno) where both are
string type in Java. These parameters will be supplied actual values by calling the setter methods
of PreparedStatement like setInt(paramIndex, int Value) or setString(paramIndex, String value)
or setFloat(paramIndex, float value) … Similar to the statement, prepared statement also has
the two methods executeUpdate(String sql) for update, delete or insert and executeQuery(String
sql) for retrieving results into a ResultSet.
The parameter index is counted from 1 (unlike Java array index which starts with 0). Once
statement is created, the same procedure is followed for both statement and prepared statement.
Example
The following example inserts two records into the mydb.test table using prepared statement.
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “dbUser”; // Replace with actual user name
String pwd = “password”;// Replace with actual password
String sql = “insert into test values(?,?)”;
try{
Class.forName(driver);
Connection con = DriverManager.getConnection(url,uname,pwd);
PreparedStatement stmt= con.prepareStatement(sql);
// Add record using prepared statement
stmt.setString(1, “Rupa”);// first parameter in the query
stmt.setString(2,”33445566"); // Second parameter
intres = stmt.executeUpdate();
System.out.println(res+” records inserted”);
137
// Add One more record
stmt.setString(1, “Hari”);
stmt.setString(2,”33556677");
res = stmt.executeUpdate();
System.out.println(res+” records inserted”);
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
After running this program check the records from mysql command prompt again:
mysql> select * from test;
name phno
Bhanu 12345678
Pratap 23456789
Rupa 33445566
Hari 33556677
4 rows in set (0.00 sec)
The same procedure that is used to retrieve records can be applied to execute select query with
prepared statements also. The partial code gives an idea of how to retrieve data using prepared
statement.
PreparedStatement stmt=con.prepareStatement(“select * from test”);
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+” “+rs.getString(2));
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What an Execute Query method does?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

10.3. USING META DATA)


Result Set Meta Data
Metadata means data about data i.e. the programmer can get further information from the data.
If the metadata of a table is obtained, information like total number of column, column name,
138 column type etc. can be obtained which can be used in the program to generalize the application
for various tables. ResultSetMetaData interface is provided to get metadata from the ResultSet
object. Some common methods that are useful are given below.
• int getColumnCount() - Returns the total number of columns in the ResultSet object.
• String getColumnName(int index) - Returns the column name of the given column
index.
• String getColumnTypeName(int index) - Returns the column type name for given index.
• String getTableName(int index) - Returns the table name for the given column index.
To get the metadata object, ResultSet provides the getMetaData() method.
ResultSetMetaData rsmd = rs.getMetadData();
Following example shows the details of the test table using the result set metadata.
import java.sql.*;
class RSMD
{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “dbUser”; // Replace with actual user name
String pwd = “password”; // Replace with actual password
String sql = “select * from test”;
try{
Class.forName(driver);
Connection con = DriverManager.getConnection(url,uname,pwd);
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println(“Total columns: “+rsmd.getColumnCount());
for (int i=0;i<rsmd.getColumnCount(); i++){
System.out.println(“Column “ + (i+1) + “ Name:”+
rsmd.getColumnName(i+1));
System.out.println(“Column “ + (i+1) + “ Type:”+
rsmd.getColumnTypeName(i+1));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

139
The output of the run will be as follows:
Total columns: 2
Column 1 Name:name
Column 1 Type: VARCHAR
Column 2 Name:phno
Column 2 Type: VARCHAR
Database Meta Data
DatabaseMetaData interface provides methods to get metadata of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc. Some commonly used methods of DatabaseMetaData interface are
given below:
• String getDriverName():Returns the name of JDBC driver.
• String getDriverVersion(): Returns the version of JDBC driver.
• String getUserName(): Returns the user name of database.
• String getDatabaseProductName(): Returns the product name of the database.
• String getDatabaseProductVersion(): Returns the product version of the database.
• ResultSet getTables(String catalog, String schemaPattern, String table Name Pattern,
String[] types): Returns the description of the tables of the specified catalog where the
table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
The database metadata object can be obtained using connection object’s getMetaData method:
DatabaseMetaData dmd = con.getMetaData();
Following example presents the metadata of the mydb database.
import java.sql.*;
class JdbcTest{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “root”; // Replace with actual user name
String pwd = “pwd123”;// Replace with actual password
try{
Class.forName(driver);
Connection con = DriverManager.getConnection(url,uname,pwd);
DatabaseMetaData dbmd=con.getMetaData();
System.out.println(“Driver Name: “+dbmd.getDriverName());
System.out.println(“Driver Version: “+dbmd.getDriverVersion());
System.out.println(“UserName: “+dbmd.getUserName());
System.out.println(“Database Product Name: “+
140
dbmd.getDatabaseProductName());
System.out.println(“Database Product Version: “+
dbmd.getDatabaseProductVersion());
String types[]={“TABLE”,”VIEW”};
ResultSet rs=dbmd.getTables(null,null,null,types);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Typical output of the program will be similar to the following:
Driver Name: MySQL Connector Java
Driver Version: mysql-connector-java-5.1.39(Revision: 3289a357………)
UserName: root@localhost
Database Product Name: MySQL
Database Product Version: 5.7.14
Test
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is JDBC?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

10.4. TRANSACTION MANAGEMENT INJDBC


Transaction represents a single unit of work which may contain one or more SQL statements.
If a transaction is successful, all the statements are executed. If at any stage, one statement
fails, all the successful statements so far should be undone. This process of undoing in case
any statement in the transaction fails, is known as “rollback”. Simply put, a transaction is
“execute all” or “execute none”. JDBC fully supports transaction management. The connection
object by default sets auto commit to true, where as each command is executed, the database is
saved (committed). If transaction is required, the auto commit has to be set to false first.
con.setAutoCommit(false);
There are two more methods that are important in transaction management, which are commit()
and rollback().
141
Following example uses a transaction model that inserts two records into the table and then
asks the user for confirmation. If the user says ‘no’ or if something goes wrong both the
transactions are rolled back. Note that MySQL supports many types of database engines, and
the user can select one engine per table. Here, the table should be created with
ENGINE=InnoDB. Otherwise, MySQL may default to MyISAM database engine, which doesn’t
support transactions.
Example:
import java.sql.*;
import java.util.Scanner;
class JdbcTest{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “uname”; // Replace with actual user name
String pwd = “upwd”;// Replace with actual password
Connection con = null;
try{
Class.forName(driver);
con = DriverManager.getConnection(url,uname,pwd);
con.setAutoCommit(false);
Statement stmt=con.createStatement();
Savepoint save1 = con.setSavepoint();
stmt.executeUpdate(“insert into test values(‘Latha’,’555555')”);
stmt.executeUpdate(“insert into test values(‘Amar’,’12344321')”);
System.out.println(“Do you really want to Commit? (Y/n)”);
Scanner scn = new Scanner(System.in);
String answer=scn.next();
scn.close();
if(answer.toUpperCase().startsWith(“Y”)){
con.commit();
System.out.println(“Committed”);
}
else{
con.rollback(save1);
System.out.println(“Rolled back”);
}
con.setAutoCommit(true);
142 con.close();
}catch(Exception e){
try{
con.rollback();
}catch (SQLException e1){
e1.printStackTrace();
}
System.out.println(e.getMessage());
}
}
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What is a transaction?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

10.6. SUMMARY
This chapter introduced the basics of Database connectivity from a Java program to any DBMS
engine. It also introduced the concept of JDBC support for transaction management and metadata
retrieval, with simple examples.In this chapter, MySQL is considered as the database since it
is freely available and one of the most popular databases. The MySQL JDBC driver can be
downloaded from the website, which has a name similar to “mysql-connector-java-5.1.39-
bin.jar” where the version number may vary. The driver may be placed in any directory but the
path of the jar file should be in the CLASSPATH.Java application that connects to a database
will use JDBC API and registers a Driver corresponding to the database, which the vendor will
supply. Using this driver, the program connects to the database and executes queries.When a
query is submitted by the program to the server, the query is first translated into appropriate
query that is understood by the server (compiled). If a query is repeatedly submitted with
different data, the translation step can be reused by converting the data into parameters. This
saves considerable time from second query onwards and results in performance improvement.
For example, consider an insert query that is used to insert 10 records. Instead of compiling
and executing the query 10 times, the prepared statement just compiles it once, and each time
new data is sent as parameters.

10.6. CHECK YOUR PROGRESS MODEL ANSWERS


1. API for connecting and managing databases of almost all important brands known as
JDBC.
2. The executeQuery statement returns a ResultSet Object which contains the results and
acts as an iterator for the data
143
3. Transaction represents a single unit of work which may contain one or more SQL
statements.

10.7. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Create a MySQL database table of Student roll number and total marks. Now use a Java
program to read data from the table and finds the average mark, maximum mark and
minimum mark.
2. Write a Java program that insert new student records in the above table.
3. Explain various methos of ResultSetMetaData and DatabaseMetaData classes with
exampls each.
II. Answer the following questions in about 15 lines each
1. Write a Java method that updates a given student’s record in the above table.
2. Write a Java method that creates a given studenttable.
3. What is prepared statement? Describe with an example

10.8 GLOSSARY
JDBC : Java Data Base Connectivity
Connector/j : Java Connector Driver to Connect to MySQL
database
Meta Data : Data about Data
Prepared Statement : Uses parameters to execute the updating of database
Transacion : Represents a single unit of work which may contain
one or more SQL statements.

144
UNIT-11: JAVA AT AND EVENT HANDLING
Contents
11.0 Objectives
11.1 Introduction
11.2 Java Event Handling
11.3. Adaptor Classes and Inner Classes
11.4. Summary
11.5. Check your progress Model Answers
11.6. Model Examination Questions
11.7. Glossary

11.0. OBJECTIVES
After studying this unit, you should be able to
• Understandimportant concept called Java event handling
• Describe adaptor classes.
• Explain how to use inner clasees.

11.1. INTRODUCTION
An event is a signal received by a program from the operating system as a result of some action
taken by the user, or because something else has happened within a graphical user interface.
Examples of events are:
The user pressed a key, The user clicked the Button or Menu item, The user closed or resized
a window.There are three entities in the event handling, viz., the event, the source of the event,
and an event listener. The delegation event model relates these three entities with a well defined
standard process. Whenever the source generates an event it is sensed or noticed by the listener
and the listener handles the event immediately.The program has to implement all the methods
since it is implementing that listener where code is written only in the windowClosed() method
and all the others are written with empty code like “void windowActivated(WindowEvent e){}”.
This is unnecessarily increasing the complexity of the code. The dummy implementations can
be observed in the examples given above.
Java provides adapter classes, which simplify the creation of event handlers in such situations.
An adapter class provides an empty implementation of all methods in an event listener interface.
The user can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events of interest.

11.2. JAVA EVENT HANDLING


An event is a signal received by a program from the operating system as a result of some action
taken by the user, or because something else has happened within a graphical user interface.
Examples of events are:
The user pressed a key
145
The user clicked the Button or Menu item.
The user closed or resized a window.
...
Each event must be handled by an event listener else there will be not action for that event.
Event Handling Mechanism
Events were handled in Java 1.0 by implementing a set of methods for that event within the
user class. However this monolithic implementation was deprecated and will be removed from
future versions of Java and hence not recommended to be used. Since Java 1.1, the system has
been modified and an event delegation model is followed. The delegation event model defines
standard and consistent mechanisms to generate and process events. Events should be handled
by all new programs using this delegation model.
Delegation Event Model
There are three entities in the event handling, viz., the event, the source of the event, and an
event listener. The delegation event model relates these three entities with a well defined
standard process. Whenever the source generates an event it is sensed or noticed by the listener
and the listener handles the event immediately. Data pertaining to the event is placed in the
event object which is passed to the listener for its use. The delegation event model enables the
user to implement the code for event handling as a completely separate set of code. The process
is as follows:
• A listener registers with a source to receive event notifications.
• When the user gives an input, the appropriate source generates an event and sends
notification about this event to all those listeners who have registered to receive this
kind of event.
• When a listener receives notification of an event, the listener then handles the event and
returns.
Event Classes
In the delegation model, the Event class is the data carrier between the source and the listener.
When an event occurs (as a result of the user interacting with the GUI like clicking a button,
selecting a menu item, or checking or un-checking a checkbox etc), an object of type Event or
its subclass is generated which describes a state change in a source. Java defines several types
of events and some of them will be discussed in this chapter. The Event class hierarchy is as
shown below:

146
java.lang.Object

java.util.Event Object

java.awt.AWT Event

Action Event Adjustment Event Component Event Item Event Text Event

Container Event Focus Event Input Event Window Event

Key Event Mouse Event Mouse Wheel Event

The EventObject, in java.utilis the superclass for all events. It has one constructor and defines
two methods as shown below:
• EventObject(Object src) where, srcis the object that generates this event.
• Object getSource( ) – Returns the source of the event
• String toString( ) – Returns the string equivalent of the event
The AWTEvent class is a subclass of EventObject which is the superclass of all AWTbased
events used by the delegation event model.
Key Event Class
As an example of an Event class, the ‘KeyEvent’ class is considered here. A KeyEventis
generated when keyboard input occurs. There are three types of key events, which are defined
as three integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first
two events are generated when any key is pressed or released. The KEY_TYPED event is
generated only when a character is generated (for example, pressing SHIFT or CTRL key does
not generate a character and hence KEY_TYPED is not generated). The KeyEvent class defines
device independent ASCII characters constants like VK_0 through VK_9 and VK_A through
VK_Z, where VK stands for virtual key. These key codes are fixed even with modifiers (Shift,
alt, ctrl or any combination). The KeyEvent has one constructor:
• KeyEvent(Component src, int type, long time, int modifiers, int code, char ch)
Where,
src is a reference to the source component of the event.
type is the type of the event
time is the system time at which the key was pressed
modifiers indicates which modifiers were pressed
code is the virtual key code, such as VK_UP, VK_DOWN, VK_A etc.
ch is the character equivalent or contains CHAR_UNDEFINED.
Commonly used methods of KeyEvent class are given below: defines several methods, but
probably the most commonly used ones are getKeyChar( ), which returns the character that
was entered, and getKeyCode( ), which returns the key code. Their general forms are shown
147
here.
• char getKeyChar() – returns character entered
• int getKeyCode() – returns key code
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a
KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
Each type of event generates an event with its own methods and constructor. The system uses
this constructor and constructs an event object appropriate for that event and sends it to the
listener.
Source of Events
Source is the object which undergoes state change and generates an event. It also provides
information about the event to the listener. A source can register listeners so that it can send
notifications to the listeners when an event occurs. Each type of event has its own registration
method which has a generic form:
public void addTypeListener (TypeListener el )
Where Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener() and the method
for mouse motion listener is addMouseMotionListener(). The Key and MouseMotion are the
event type.
When an event occurs, all registered listeners are notified and sent a copy of the event object
which is known as multicasting the event.
Some sources may allow only one listener to register and if another listener tries to register for
this event, the add method throws java.util.TooManyListenersException. This is known as
unicasting the event.
Every source provides a method to unregister a listener which is as follows:
public void removeTypeListener(TypeListener el )
Where Type is the name of the eve-nt, and el is a reference to the event listener. For example,
to remove a keyboard listener removeKeyListener().is called.
The Component class (super class of all GUI components) provides methods to add and remove
keyboard and mouse event listeners.
Following table shows some of the event classes and source of the event
Following table shows some of the event classes and source of the event
Event Class Generated when
ActionEvent A button Is pressed, a list item is double clicked, or a
menu item is selected.
AdjustmentEvent A scroll bar is manipulated.
ComponentEvent A component is hidden, moved, resized, or becomes
visible.
ItemEvent A check box, list item, selection, or menu is clicked
TextEvent Value of a text area or text field is changed.
ContainerEvent A component is added to or removed from a container.
FocusEvent A component gains or loose keyboard focus.
148
WindowEvent A window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
KeyEvent An input is received from the keyboard.
MouseEvent Mouse is dragged, moved, clicked, pressed, released,
entered or exited
MouseWheelEvent Mouse wheel is moved.
Event Listener Interfaces
The class that implements a listener (also called event handler) is the actual handler of the
event. A listener is an object that will be notified when an event occurs. It must have been
registered with one or more sources to receive notifications about specific types of events. It
must also implement methods as defined in the listener interface to receive and handle these
notifications.
For example a listener that handles mouse events must implement the
MouseMotionListenerinterface which defines two methods to receive notifications when the
mouse is dragged or moved.
An event handler should not take too much time to process the event. Otherwise, some events
may be missed or program appears sluggish. Following is a list of some of the event listeners.

Event EvenListener Methods to Override


ActionEvent. ActionListener actionPerformed(ActionEvent e)
KeyEvent. KeyListener keyPressed(KeyEvent ke)
keyTyped(KeyEvent ke)
keyReleased (KeyEvent ke)
ItemEvent ItemListener itemState Changed (ItemEvent ie )
MouseEvent MouseMotionListener MouseListener
mouseMoved(MouseEvent me) mouseDragged(MouseEvent me)
Following is an example that uses ActionListener to handle ActionEvent which is generated
by a button. Ignore statements or code that is not immediately understood since, it uses AWT
components. Observe the statements that are specific to event handling. When the user clicks
a button, it generates the ActionEvent and calls the method “actionPerformed()” method of the
registered class that implements ActionListener.
import java.awt.*;
import java.awt.event.*;
class Test extends Frame implements ActionListener{
TextField textField;
Test(){
setLayout(new GridLayout(2,1));// set 2 rows x 1 column grid
setPreferredSize(new Dimension(200,150)); // Set window size
textField = new TextField(); // Create a text field
textField.setPreferredSize(new Dimension(200, 50)); // set size
//textField.setBounds(60,50,170,20); // Set size and location 149
Button button = new Button(“Click”); // Create a button
// Register this class itself for Action Events to the button
button.addActionListener(this);
add(textField); // Add text field to the frame
add(button); // Add button to the frame
pack(); // Pack the window by re-computing the sizes
setVisible(true); // Show the window
}
// The only method to be implemented for an ActionListener
public void actionPerformed(ActionEvent e)
{
textField.setText(“Button Clicked”);
}
// Entry point to the application
public static void main(String args[]){
new Test(); // Create object and the constructor shows window
}
}

In the above image the left side window shows the initial screen and when the user clicks the
button, the message is shown in the text field by calling the action listener’s actionPerformed()
method. Read the comments carefully for an understanding of the process.
Other Examples of Event Handling:
Mouse Example:
Following example uses the mouse events.
import java.awt.*;
import java.awt.event.*;
class Test implements MouseListener{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); // Set size of the window
150
f.addMouseListener(this);
f.pack();
f.setVisible(true);
}
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”, e.getX(), e.getY());
}
// Other dummy methods of the listener
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public static void main(String args[]){
new Test();
}
}
This program listens for mouse events and takes action when the mouse is clicked, ignoring
other events. When the mouse is clicked the location is filled in the event object that is passed
to the method. The string is printed starting at that location after clearing the screen first. A
screenshot of the output is shown below:

Keyboard Example:
Following program uses the key event to count the characters and words. The words are counted
whenever there is a space.
import java.awt.*;
import java.awt.event.*;
class KeyEventTest implements KeyListener{
Frame f=null;
Label l;
TextArea area;
KeyEventTest(){
f=new Frame(“Key Listener”);
151
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split(“ *”);
l.setText(“Words: “+words.length+” Characters:”+text.length());
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){}
public static void main(String args[]){
new KeyEventTest();
}
}
When a key is released, the keyReleased() method is called with KeyEvent which contains the
key pressed. The method just gets the string so far typed and splits it based on the space into
words array. The length of the array is the words and the length of the string is the number of
characters. This is set to the Label component’s text.

words:9 Characters : 40
this is a test string to test key events

152
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What is an event handler?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

11.3. ADAPTOR CLASSES AND INNER CLASSES


Consider that a program requires handling of windowClosed event. Hence, it must implement
WindowListener, which defines the following seven methods.
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowIconified(WindowEvent e)
void windowOpened(WindowEvent e)
The program has to implement all the methods since it is implementing that listener where
code is written only in the windowClosed() method and all the others are written with empty
code like “void windowActivated(WindowEvent e){}”. This is unnecessarily increasing the
complexity of the code. The dummy implementations can be observed in the examples given
above.
Java provides adapter classes, which simplify the creation of event handlers in such situations.
An adapter class provides an empty implementation of all methods in an event listener interface.
The user can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events of interest.
For example, in the above case, since the program is only interested in windowClosed event,
the user can extend WindowAdapter and override windowClosed() method. The empty
implementation of remain methods are already implemented by the adapter. A brief list of
commonly used adapter classes in java.awt.event and their corresponding listeners is given
below:
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
153
A simple example that uses the adapter class to override WindowClosing event is given below:
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterTest{
Frame f;
WindowAdapterTest(){
f=new Frame(“Window Adapter”);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new WindowAdapterTest();
}
}
Observe that an anonymous class that extends WindowAdapter is created on the fly which
overrides the WindowClosing() method, which disposes the graphical object.
For example, the mouse listener example given above can be rewritten to extend the
MouseAdapter and the dummy methods can be removed as shown below:
import java.awt.*;
import java.awt.event.*;
class Test extends MouseAdapter{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); // Set size of the window
f.addMouseListener(this);
f.pack();
f.setVisible(true);
}

154
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”, e.getX(), e.getY());
}
// Other dummy methods of the listener are removed
public static void main(String args[]){
new Test();
}
}
Inner Classes and Anonymous Classes
The examples with and without adapters shown before use the same class as a listener
and hence must implement all the required methods within the same class. This is what was
done in Java version 1.0 which was discarded for the very same reason. Hence, it is always
better to use a separate class that handles the events. If the class is implemented outside the
class code, it cannot access the variables of the original class of importance. Hence, the event
handler class is implemented within the main class since any inner class can access all the data
of the parent class. The structure of such a design is as follows:
class Outer {
… code here …
evtSource.addTypeListener(new EventHandler());
… code …
class EventHandler implements TypeListener {
… event handling methods here …
}
}
Mouse Example with Inner Class:
import java.awt.*;
import java.awt.event.*;
class Test{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); //Set window size
f.addMouseListener(new MyMouseAdapter()); // Add listener
f.pack();
f.setVisible(true);
}
// This is an inner class that handles mouse events
155
class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”,e.getX(),e.getY());
}
}
public static void main(String args[]){
new Test();
}
}
In the above example, an adapter class is defined within the main class which is set as the
listener for the mouse events. Here the event code is separated from main code by means of an
inner class. In this specific case, the definition of a separate class is used only once, during the
addMouseListener() call. Java provides anonymous classes where the definition is given along
with the parameter, which is used only within the method. The above code can be modified to
send the adapter class during the call itself without declaring it explicitly. The modified code
is presented below:
import java.awt.*;
import java.awt.event.*;
class Test{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); //Set window size
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”,e.getX(),e.getY());
}
}); // Add listener
f.pack();
f.setVisible(true);
}
public static void main(String args[]){
new Test();
}
}

156
Observe that the MouseAdapter’s code is written within the brackets () of method
addMouseListener().
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is an anonymous class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

11.4. SUMMARY
This chapter introduces the event handling mechanism that is one of the essentials in GUI
programs in Java. . Events were handled in Java 1.0 by implementing a set of methods for that
event within the user class. However this monolithic implementation was deprecated and will
be removed from future versions of Java and hence not recommended to be used. Since Java
1.1, the system has been modified and an event delegation model is followed. The delegation
event model defines standard and consistent mechanisms to generate and process events. Events
should be handled by all new programs using this delegation model.
.The class that implements a listener (also called event handler) is the actual handler of the
event. A listener is an object that will be notified when an event occurs. It must have been
registered with one or more sources to receive notifications about specific types of events. It
must also implement methods as defined in the listener interface to receive and handle these
notifications.For example a listener that handles mouse events must implement the
MouseMotionListenerinterface which defines two methods to receive notifications when the
mouse is dragged or moved. An event handler should not take too much time to process the
event. Otherwise, some events may be missed or program appears sluggish

11.5. CHECK YOUR PROGRESS MODEL ANSWERS


1. The class that implements a listener (also called event handler) is the actual handler of
the event.
2. The method whose parameter is passed the code that handles the Window event

11.6. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Explain the evemt classes and their source of events along with listener interfaces in
Java
2. Write a Java programusing awt an event hadling to count the words and characters in
the text as you type the text in the text area control.
3. Write a java program that displays mouse clicked where ever you click a left mouse
button.
II. Answer the following questions in about 15 lines each
1. Write a Java program to close the awt window using adapter class.
157
2. Write a Java program to demonstrate inner classes..
3. Describe anonymous class with an example.

11.7 GLOSSARY
Event : Java Data Base An event is a signal received by a program
from the operating system as a result of some action taken by
the user
Event Hanlwe : The class that implements a listener (also called event handler)
is the actual handler of the event.
Delegation Model : Separating event handlng mechanism into event, source,
handler
Adapter class : An adapter class provides an empty implementation of all
methods in an event listener interface.
Anonymous class : The method whose parameter is passed the code that handles
the Window event

158
UNIT-12: JAVA VISUAL PROGRAMMING WITH SWING
Contents
12.0. Objectives
12.1. Introduction
12.2. Swing Packages
12.3. Swing GUI Components-Lable,Imagge Icon, Button, Text Field, Text Area
12.4 . Swing GUI Components-Check Boz, Radio Button, Combo Box, List, Tabbed Pane,
Scroll Pane, Table, Tree
12.5. Summary.
12.6. Check your progress Model Answers
12.7. Model Examination Questions
12.8. Glossary

12.0. OBJECTIVES
After studying this unit, you should be able to
• Understand GUI programming with Java Swing components.
• Describe Swing packages.
• Explain how to write programs using Swing event handling.

12.1. INTRODUCTION
Java originally incorporated the AWT components which translate each graphical instruction
to corresponding native call specific to the platform. As a result, the behavior of the GUI
components are platform specific which was against the “run anywhere” principle of Java,
since the GUI looks different on different platforms. Further there was overhead of converting
each call to machine specific call. These drawbacks lead to the development of swing which
uses pure Java implementation of the entire GUI stack. Swing components appear and behave
alike on all platforms.
Swing uses the AWT and replaced the native code with Java code. The same event handling
used by AWT is used in swing as well. However, there are some important changes in the
design of the swing components. The swing components are pure Java implementation unlike
AWT which uses native code. Hence, swing components have the same look and feel on all
platforms. Furthermore, the user can change the look and feel within the program.

12.2. SWING PACKAGES


Swing uses model view controller (MVC) architecture which gives a clean separation among
the three components. Here, there are three different internal entities:
Model – contains the information (data about the state). For example, a checkbox contain a
value which will indicate whether it is checked or unchecked.
View – defines how the component should look like and may use the data from model.
Controller – defines what to do when an event occurs. 159
Following table gives a list of differences between AWT and Swing
Java AWT Java Swing
Platform dependent Platform independent
Heavyweight since calls are to be translated Lightweight since they are pure Java
implementation
Doesn’t support pluggable look and feel Supports pluggable look and feel
Limited set of components Large set of components
Doesn’t support MVC Designed with MVC architecture
Swing is a large subsystem of GUI programming. It has a considerably large set of components
and containers to accommodate these components. Almost every possible screen can be designed
with swing components and an appropriate container. Swing adds J for each component to
distinguish it from AWT equivalent like JFrame for Frame, JButton for Button and so on.
Similarly swing is organized into a large set of packages which are different from AWT packages.
Following is a list of various components, containers and packages used by swing. A partial
hierarchy of components is as shown in the following diagram:

Swing Components
Swing has a considerably large set of components. Following is a list of some important
components supported by swing:

160
Component Name Description
JButton Push button that can display text, images, or both
JCheckBox Toggle button for displaying choices (allows multiple
selection)
JColorChooser Component that allows the user to select a color
JComboBox Combination of a text entry field and a drop-down list of
choices
JEditorPane Customizable text editor component for displaying and
editing text and HTML
JFileChooser Component that allows the user to select a file or directory
JLabel Component that displays text, an image, or both
JList Component that displays a selectable list of choices
JMenu Pull-down menu in a JMenuBar or a submenu within another
menu
JMenuBar Component that displays a set of pull-down menus
JMenuItem Selectable item within a menu
JOptionPane Customizable dialog box for display simple messages
JPasswordField Text input field that displays the text as stars or dots
JPopupMenu Window that pops up to display a menu
JProgressBar Component that displays the progress of an operation
JRadioButton Toggle button for displaying mutually exclusive choices
JScrollBar Horizontal or vertical scrollbar
JSeparator Component that draws a horizontal or vertical line
JSlider Component that simulates a slider control
JTable A complex and powerful component for displaying and
editing tables
JTextArea Component for displaying and editing multiple lines of plain
text
JTextField Component for the display, input, and editing of a single
line of plain text
JToolBar Component that displays a set of user-selectable tools or
actions
JToolTip Lightweight pop-up window that displays simple tips when
the mouse pointer hovers over a component
JTree Component for the display of tree-structured data.

161
Swing Containers
Swing components must be placed inside a container before they are shown. There are two
types of containers available in swing. The first one is the top level containers, which are
JFrame, JDialog, JWindow and JApplet. A top level container cannot be contained by another
container. Any other components can be directly added to this category of containers. The
JApplet is deprecated and may be removed in future and hence not recommended to be used.
The second category of containers is the JPanel, which can contain other components and
even other JPanels. This is very useful since the nested panels can yield any design requirement
as far as component layout is concerned.
Layout Managers
When components are added to a container, the order or place where these components should
be added is controlled by a layout manager. Swing provides layout managers defined by AWT
which are FlowLayout, BorderLayout, GridLayout, GridbagLayout and CardLayout. If the
user wants to take control of the layout, the layout may be set to null. Each layout adds the
components in a specified way.
FlowLayout: It places the components left to right and top to bottom order if components
overflow from one row.
BorderLayout: It places components in 5 places (top – NORTH, bottom – SOUTH, right (EAST),
left (WEST) or center – CENTER).
GridLayout: It places components in rows and columns (right to left, top to bottom)
CardLayout: It places each component on a layer and the order can be changed programmatically.
GridBagLayout: It uses FlowLayout but with horizontal and vertical constraints.
By default the JFrame uses BorderLayout and the JPanel uses FlowLayout.
Swing Packages
Swing components are organized into different packages. Some packages generally used are
given here:
javax.swing javax.swing.text javax.swing.border
javax.swing.text.html javax.swing.colorchooser javax.swing.event
javax.swing.filechooser javax.swing.tree javax.swing.table
Appropriate package should be imported to use a component. To avoid clashing with existing
names, swing uses javax.swing as its base package directory. Every component is a part of
“javax.swing” package directly.
Check Your Progress

Note: a) Space is given below for writing your answers


b) Compare your answers with the one given at the end of the unit

1. What is Swing model?


............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
162
12.3.SWING GUI COMPONENTS-LABLE, IMAGE ICON,
BUTTON, TEXT FIELD, TEXT AREA
Swing doesn’t provide a separate event handle mechanism and it uses the same delegate event
model. It perfectly supports events from AWT (java.awt.event package) and it has its own
package for events (javax.swing.event), which augments AWT events and hence nothing extra
need to be learned. Many example that this chapter presents, use different event handlers. The
java.awt.event.* is still the package to use to import required events that are handled in a
program.
Gui components
Following sections describes some of the important swing components and examples are given
wherever necessary, sometimes combining many components within a single example. These
examples give an overall understanding of how the components work and how to use them.
Once the candidate understands the pattern of usage, it is advised to go through the Java
documentation or other websites for any new component that is required to be used in real
projects.
Swing Standalone Program Structure
Any standalone swing application should extend or contain a JFrame. If events are to be handled,
an event handler has to be defined. In the examples, the class itself implements the event
listeners or an anonymous inner class is used for simplicity. The skeleton of a typical swing
standalone application is as follows:
import javax.swing.*;
import java.awt.event.*;
public class SwingTest extends JFrame implements ActionListener, MouseListener, ... {
// variables declarations here
// Constructor which generally initialize the components
// Event handling methods
// Main method
public static void main(String args[]) {
// initializations if any
// Create object of type SwingTest
SwingTest st = new SwingTest();
// Other statements
}
}
JLabel
In many cases the program may have to show some constant text with no interactive behavior.
For example a prompt that appears before an input like text box, which doesn’t require any
interaction with the user. In such situations a JLabel is used. Almost every GUI design involves
some text to be shown and hence, JLabel is almost ubiquitous. It shows a single line text and
the text cannot be changed directly. However, it can be changed programmatically. JLabel has
different constructors and one of them can be used as needed.
163
JLabel() – Creates an empty label and the program can set text using its setText() method.
JLabel(String s) – Creates a label with given string as its message
JLabel(Icon i) – Creates a label with an Icon
JLabel(String s, Icon i, int horizontalAlignment) – Creates a label with given string and icon
and aligns it according to the horizontal alignment which can be one of the predefined static
constant such as JLabel.LEFT, JLabel.RIGHT, JLabel.CENTER.
Example:
import javax.swing.*;
public class JLabelTest extends JFrame{
JLabel jl1,jl2;
public JLabelTest() {
super(“JLabel Example”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl1=new JLabel(“Welcome to Java”);
jl1.setBounds(50,50, 200,30); // x,y, width, height
jl2=new JLabel(“JLabel Test”);
jl2.setBounds(50,100, 200,30);
add(jl1);
add(jl2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new JLabelTest();
}
}
Since the class extends JFrame, it inherits all the properties of JFrame. JFrame has a constructor
that takes the title of the window as a parameter. The first line in the constructor calls that
constructor with the title. By default the JFrame cannot be closed and the user sets the behavior
to exit on close, which is defined as a static constant in JFrame. Since null layout is used, the
program defines the x,y coordinates and the dimensions (height and width) of each component.
It may be observed that it is similar to the AWT program given in the Event Handling section.
The same example can be rewritten with a JFrame object declared inside the class without
extending JFrame. The output is identical in both cases.
import javax.swing.*;
public class JLabelTest{
JFrame jf;
164 JLabel jl1,jl2;
public JLabelTest() {
jf = new JFrame(“JLabel Example”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl1=new JLabel(“Welcome to Java”);
jl1.setBounds(50,50, 200,30); // x,y, width, height
jl2=new JLabel(“JLabel Test”);
jl2.setBounds(50,100, 200,30);
jf.add(jl1);
jf.add(jl2);
jf.setSize(300,300);
jf.setLayout(null);
jf.setVisible(true);
}
public static void main(String args[]){
new JLabelTest();
}
}
The output window is like this:

Image Icon,
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
An object of type ImageIcon can be created using any of its constructors. Here are the important
and very useful constructors:
ImageIcon() – Creates an empty icon
ImageIcon(Image image) – Creates an icon from an image
ImageIcon(String filename) – Creates an icon from given JPG or PNG file
ImageIcon(URL locationURL, String description) – Creates an icon from a remote location
Some of the important methods that are useful are:
int getIconHeight(): Gets the height of the icon.
int getIconWidth(): Gets the width of the icon.

165
Image getImage(): Returns this icon’s Image.
void setImage(Image image): Sets the image displayed by this icon.
Example:
For this example, an image is required, which can be created with any
graphics editor like paint. In this case an image called myicon.png is
created and is placed in the same directory as that of the code. The
image looks as shown. Following example uses the image to create an
icon and shows it along with a label.
import java.awt.*;
import javax.swing.*;
publicclass IconTest
{
JFrame jf;
JLabel jl;
public IconTest(){
jf = new JFrame(“Icon Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new FlowLayout());
jf.setSize(300,300);
ImageIcon ico = new ImageIcon(“myicon.png”);
jl = new JLabel(“Icon Demo:”, ico, JLabel.LEFT);
jf.add(jl);
jf.setVisible(true);
}
publicstaticvoid main(String[] args)
{
new IconTest();
}
}
The output of the program is as shown below:

166
JButton
JButton class provides functionality of a button. JButton supports ActionEvent, i.e., when a
button is pressed an ActionEvent is generated. JButton class has three constructors which
allow a button to be created using icon, a string or both:
JButton(Icon ic)
JButton(String str)
JButton(String str, Icon ic)
When a button is clicked, an ActionEvent is generated and is passed to the actionPerformed()
method as parameter. This action event contains the source of the event which can be used to
differentiate different button clicks, though both will generate the same action event.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass ButtonTest{
JFrame jf;
JButton jb1, jb2;
JLabel jl;
public ButtonTest(){
jf = new JFrame(“Button Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new FlowLayout());
jb1 = new JButton(“Upper”);
jb1.addActionListener(new ButtonEventHandler());
jb2 = new JButton(“Lower”);
jb2.addActionListener(new ButtonEventHandler());
jl = new JLabel(“Test Message”);
jf.add(jb1);
jf.add(jb2);
jf.add(jl);
jf.setVisible(true);
}
publicstaticvoid main(String[] args){
new ButtonTest();
}

167
class ButtonEventHandler implements ActionListener {
publicvoid actionPerformed(ActionEvent ae) {
if(ae.getSource() == jb1) {
jl.setText(jl.getText().toUpperCase());
}
else {
jl.setText(jl.getText().toLowerCase());
}
}
}
}
The program attaches the same handler class to both buttons. ActionEvent’s getSource() method
that gives the reference to the source which is used to distinguish the buttons. That reference
is compared with jb1 and jb2 to know which object (Button) is clicked. Output of the program
when the first button was clicked is as shown below:

JTextfield and JPasswordField


JTextField is used for taking input of single line of text. It is most widely used text component.
It has three constructors,
JTextField(int cols) – where cols represent the number of columns in the text field
JTextField(String str,int cols) – where str is the initial String
JTextField(String str)
JPasswordField is also takes a single line of input but it shows dots or stars for the characters
thus protects the input from viewing. The getPassword() method is used to get data from this
component, which gives an array of characters which should be converted to a string using
new String(component.getPassword()) before it is used as a string for comparison.
Following program takes user name and password from the user and when the user clicks the
“OK” button, it shows User OK if user name and password are same and each has more than
3 characters. Otherwise it shows User Not OK.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldTest{
JFrame jf;
JButton jb;
JLabel jl1, jl2, jl3;
168
JTextField jtf;
JPasswordField jpf;
public TextFieldTest(){
jf = new JFrame(“TextField Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new GridLayout(3,2)); // 4 Rows x 2 columns
jl1 = new JLabel(“User Name”);
jtf = new JTextField(“”);
jl2 = new JLabel(“Password”);
jpf = new JPasswordField();
jl3 = new JLabel(“”);
jb = new JButton(“OK”);
jb.addActionListener(new ButtonEventHandler());
jf.add(jl1);
jf.add(jtf);
jf.add(jl2);
jf.add(jpf);
jf.add(jl3);
jf.add(jb);
jf.setVisible(true);
}
public static void main(String[] args){
new TextFieldTest();
}
class ButtonEventHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
String s1 = jtf.getText();
String s2 = new String(jpf.getPassword());
System.out.println(“S1: “ + s1);
System.out.println(“S2: “ + s2);
if(s1.equals(s2) && s1.length() > 3) {
jl3.setText(“User OK”);
}
else {
jl3.setText(“User Not OK”);
169
}
}
}
}
Following is the output of this program. The first screen shows the initial screen where jl3 is
empty and the next screen shows when the user name and password are both ‘aaaa’ which sets
jl3 to “User OK”. If name length is less than 4 or name not equals to password, jl3 is set to
“User Not OK”.

Text Field Text Field

User Name User Name aaaa

password
password ****

User OK OK

JTextArea
JTextArea works just like a JTextField, but can take multi-line input like address, feedback
etc. It can be created with its constructor JTextArea(int rows, int cols) where rows and cols are
integers that represent the minimum number of rows and number of columns on the screen.
Following example uses a JTextArea.
import java.awt.*;
import javax.swing.*;
public class TextAreaTest{
JFrame jf;
JScrollPane jsp;
public TextAreaTest() {
jf = new JFrame(“TextArea Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
JTextArea jta = new JTextArea(5, 30); // 5 rows x 30 columns area
jf.add(new JLabel(“Enter some text”), BorderLayout.NORTH);
jf.add(jta, BorderLayout.CENTER);// Add to the content pane.
jf.setVisible(true);
}
public static void main(String[] args){
new TextAreaTest();
}
}
170 A typical output of the program is shown below:
Enter some text
This is a !text area than can take
multi-line input
from the user!

Check Your Progress


Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is JTextArea?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
12.4. SWING GUI COMPONENTS-CHECK BOZ,RADIO BUTTON,
COMBO BOX, LIST,TABBED PANE,SCROLL PAE, TABLE, TREE
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for JCheckBox,
JCheckBox(String str)
A checkbox is checked for whether it is checked or not using the method
isSelected() – which returns true if it is checked or false otherwise
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckTest{
JFrame jf;
JButton jb;
JCheckBox jcb1, jcb2;
JLabel jl;
public CheckTest(){
jf = new JFrame(“Check Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new GridLayout(4,1));
jb = new JButton(“OK”); 171
jb.addActionListener(new ButtonEventHandler());
jcb1 = new JCheckBox(“Java”);
jcb2 = new JCheckBox(“C++”);
jl = new JLabel(“”);
jf.add(jcb1);
jf.add(jcb2);
jf.add(jb);
jf.add(jl);
jf.setVisible(true);
}
public static void main(String[] args){
new CheckTest();
}
class ButtonEventHandler implements ActionListener{
public void actionPerformed(ActionEvent ae) {
String s=””;
if(jcb1.isSelected()){
s += “Java “;
}
if(jcb2.isSelected()){
s += “C++ “;
}
jl.setText(s);
}
}
}
The output of the program is as shown when both are checked.

172
JRadioButton
Radio buttons work like check boxes except that, when grouped, only one out of them can be
selected making them mutually exclusive. Radio buttons are created with one of its constructors.
Two important constructors are given below:
• JRadoiButton(String str) – Creates a radio button object with the given string as its
value
• JRadioButton(String str, boolean selected) – Creates and selects it if selected is true
Once the buttons are created they can be grouped logically with ButtonGroups. A ButtonGroup
is created for each group, and add each radio button to appropriate group. Once, grouped, only
one out of the group can be selected. Following application selects the gender and handles the
event.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioTest {
JFrame jf;
JLabel jl;
JRadioButton jr1, jr2;
public RadioTest() {
jf = new JFrame(“TextArea Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new FlowLayout());
jr1 = new JRadioButton(“Male”);
jr2 = new JRadioButton(“Female”);
MyListener ml = new MyListener();
jr1.addItemListener(ml);
jr2.addItemListener(ml);
ButtonGroup bg = new ButtonGroup();
bg.add(jr1);
bg.add(jr2);
jl = new JLabel(“Selected: “);
jf.add(jr1);
jf.add(jr2);
jf.add(jl);
jf.setVisible(true);
}
173
public static void main(String[] args){
new RadioTest();
}
class MyListener implements ItemListener{
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()== jr1) {
jl.setText(“Selected: Male”);
}
else if(e.getSource()==jr2)
{
jl.setText(“Selected: Female”);
}
else {
jl.setText(“Selected: None”);
}
}
}
}
The output of the program with ‘Female’ selected is shown below:

JList
In Java, Swing toolkit contains a JList Class. It is under package javax.swing.JList class. It is
used to represent a list of items together. One or more than one item can be selected from the
list. A JList object can be created with one of its constructors:
JList()
JList(ary[] listData)
While declaring a JList variable, a data type should be given within angular brackets since a
list uses Java generics feature, where the user can define what type of data it contains. Observe
how it is defined and how it is instantiated in the following example. The example shows a list
with some colors to select from. When the user selects a color, the list selection event is
triggered and it is handled by the inner anonymous class which sets the color to the label. Note
that JList generates events defined in javax.swing.event.ListSelectionListener, not from the
standard java.awt.event. Following is an example of a list:
import java.awt.*;
import javax.swing.*;
174
import javax.swing.event.*;
public class ListTest{
JFrame jf;
JList<String> jl;
String items[]={“Red”, “Green”, “Blue”, “Pink”,
“Yellow”, “White”, “Black”};
JLabel jlb;
public ListTest(){
jf= new JFrame();
jf.setSize(400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new FlowLayout());
jl = new JList<>(items);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jf.add(jl);
jlb = new JLabel(“Selected: “);
jf.add(jlb);
jf.setVisible(true);
jl.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
String sel = jl.getSelectedValue();
jlb.setText(“Selected: “ + sel);
}
});
}
public static void main(String args[]){
new ListTest();
}
}
The output is as shown below. For every change in selection, the label is reset to that color.

Red
GREEN
Blue
Pink Selected : Green
Yellow
White
Black

175
JCombobox
Combo box is a combination of text fields and drop-down list. A combo box is created with
one of the following constructors:
JComboBox() – Creates an empty combo box which will be populated later.
JComboBox(String arr[]) – Creates a combo box with the elements of the array
When a combo box is created, items can be added to or removed from it with addItem() and
removeItem() respectively. When an item is selected, it generates an action event which can be
handled by creating a handler with actionPerformed() method. Following example shows a
simple JcomboBox with its handling mechanism. Following is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboTest{


String items[] = {“Java”,”C”,”C++”,”Python”}; //list of languages
JLabel jlb;
JFrame jf;
JComboBox<String> jcb; // Combo box of String items
public ComboTest(){
jf = new JFrame(“Button Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new FlowLayout());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jcb = new JComboBox<>(items); //initialize with items.
jcb.addItem(“Fortran”); // Add an item programmatically
jf.add(jcb);//adding JComboBox to frame.
jlb = new JLabel(“Selected: “);
jf.add(jlb);
jcb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String x = (String)jcb.getSelectedItem();
jlb.setText(“Selected: “ + x);
}
});
jf.setVisible(true);
}
176
public static void main(String[] args){
new ComboTest();
}
}
Output of the program when ‘Fortran’ is selected is shown below:

JScrollPane
JScrollPane is an advanced component which adds functionality of scrolling to any component
by adding scrollbars. The scroll pane object is created with its constructor
JScrollPane(Component cp). The scrollbars can be selectively added or can be made automatic.
Following program adds scroll capability to a panel which is populated with 20 x 20 labels as
a grid.
import java.awt.*;
import javax.swing.*;
public class ScrollTest {
JFrame jf;
JScrollPane jsp;
public ScrollTest() {
jf = new JFrame(“Scroll Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20,20));
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++) {
jp.add(new JLabel(“Label (“ + i+”,”+j+”)”));
}
}
JScrollPane jsp = new JScrollPane(jp);// Create Scroll Pane
jf.add(jsp, BorderLayout.CENTER);// Add Scroll pane at center
jf.setVisible(true);
}
177
public static void main(String[] args){
new ScrollTest();
}
}
The output of the program is as shown below, with horizontal and vertical scrollbars.

JTabbedPane
JTabbedPane provides an advanced view for the components, where the components are
organized into different screens with tabs. Each tab contains a panel which will be shown
when that tab is clicked. The panel acts as the container for components. A JTabbedPane can
be created with its constructor JTabbedPane(). Once, a tabbed pane object is created, it can be
populated with different panels using its add(String tabName, Component cp) method. Following
example creates a tabbed pane with three tabs where each tab is attached with a different panel
and each panel is populated with different items.
Example:
import javax.swing.*;

public class TabbedPaneTest{


JFrame jf;
JPanel jp1, jp2, jp3;
JTabbedPane jtp;
public TabbedPaneTest() {
jf = new JFrame(“Tabbed Pane Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jtp = new JTabbedPane();

jp1 = new JPanel(); // Create first panel


JButton b1 = new JButton(“Hyderabad”);
178
jp1.add(b1);
JButton b2 = new JButton(“Bangalore”);
jp1.add(b2);
jp2 = new JPanel();
JCheckBox jcb1 = new JCheckBox(“C++”);
jp2.add(jcb1);
JCheckBox jcb2 = new JCheckBox(“Java”);
jp2.add(jcb2);
jp3 = new JPanel();
JCheckBox jcb3 = new JCheckBox(“Sports”);
jp3.add(jcb3);
JCheckBox jcb4 = new JCheckBox(“Movies”);
jp3.add(jcb4);
jtp.addTab(“Cities”, jp1);
jtp.addTab(“Languages”, jp2);
jtp.addTab(“Hobbies”, jp3);
jf.add(jtp);
jf.setVisible(true);
}
public static void main(String[] args){
new TabbedPaneTest();
}
}
The three tabs are shown in the following figures:

JTable
JTable is an advanced container component that shows a two dimensional array of elements as
a table. It can be used to display data in tabular format including a header line. The JTable
contains two constructors:
JTable()
JTable(Object[][] data, Object[] headers)
Example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
179
import javax.swing.JTable;
public class TableTest{
JFrame jf;
// Initialize column headings.
String[] heading = { “Name”, “Phone”, “Ext” };
// Initialize data.
String[][] data = {
{“Anand”, “11223344”, “865”}, {“Bhanu”, “11223344”, “565”},
{“Charles”, “11223344”, “578”}, {“Dharma”, “22334455”, “111”},
{“Eeswar”, “22334455”, “333”}, {“Fathima”, “22334455”, “222”},
{“Gangaram”, “33445566”, “111”}, {“Hari”, “33445566”, “444”},
{“Irfan”, “33445566”, “222”}, {“Jagan”, “33445566”, “333”},
{“Krishna”, “11111111”, “111”}, {“Lakshmi”, “11111111”, “112”},
{“Malini”, “11111111”, “113”}
};
public TableTest() {
jf = new JFrame(“Table Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
//jf.setLayout(new FlowLayout());
JTable table = new JTable(data, heading); // Create the table.
JScrollPane jsp = new JScrollPane(table); // Add to a scroll pane.
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jf.add(jsp); // Add the scroll pane to the content pane.
jf.setVisible(true);
}
public static void main(String args[]) {
new TableTest();
}
}
The output of a table example is given below:

180
JTree
JTree is an advanced container introduced in swing to create and manage a hierarchical view
of data. A JTree starts with one root node, which contains sub-root nodes and their children
nodes. The tree can be expanded or collapsed similar to a file explorer in windows.
When a node is selected from the JTree, it generates a TreeSelectionEvent which can be handled
by implementing TreeSelectionListener interface. A JTree object can be constructed using one
its constructors :
• public JTable() - Creates a JTree with a sample model.
• public JTree(TreeModel newModel) - Creates a JTree using TreeModel.
• public JTree(TreeNode root) - Creates a JTree with the specified TreeNode as its root.
Some useful methods in JTree are as shown below:
• public TreeModel getModel() - Gets the TreeModel whose data is displayed by JTree.
• public int getRowCount() - Gets the total number of the rows in the JTree.
• public void addTreeSelectionListener(TreeSelectionListener tsl) - Adds a listener for
TreeSelectionEvents with JTree.
An example of a simple JTree is given below.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class TreeTest{
JFrame jf;
JTree tree;
JLabel jlab;
public TreeTest(){
jf = new JFrame(“Tree Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
// Create top node of tree.
DefaultMutableTreeNode root = new DefaultMutableTreeNode(“Root”);
// Create subtree of “A”.
DefaultMutableTreeNode st1 = new
DefaultMutableTreeNode(“Language”);
root.add(st1);
DefaultMutableTreeNode t11 = new DefaultMutableTreeNode(“Java”);
st1.add(t11);
DefaultMutableTreeNode t12 = new DefaultMutableTreeNode(“Python”);
st1.add(t12); 181
// Create subtree of “B”.
DefaultMutableTreeNode st2 = new DefaultMutableTreeNode(“Hobbies”);
root.add(st2);
DefaultMutableTreeNode t21 = new DefaultMutableTreeNode(“Sports”);
st2.add(t21);
DefaultMutableTreeNode t22 = new DefaultMutableTreeNode(“Movies”);
st2.add(t22);
DefaultMutableTreeNode t23 = new
DefaultMutableTreeNode(“Reading”);
st2.add(t23);
// Create the tree.
tree = new JTree(root);
// Add the tree to a scroll pane.
JScrollPane jsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
jf.add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
jf.add(jlab, BorderLayout.SOUTH);
// Handle tree selection events.
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent tse){
jlab.setText(“Selection is “ + tse.getPath());
}
});
jf.setVisible(true);
}
public static void main(String[] args) {
new TreeTest();
}
}
The output of the tree example is given below. Whenever the user selects a node, the label at
the bottom is set to the new path.

182
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What is a JTree?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................

12.5. SUMMARY
This chapter introduced the major components of swing GUI programming along with procedure
to handle different events. Swing is a large subsystem of GUI programming. It has a considerably
large set of components and containers to accommodate these components. Almost every
possible screen can be designed with swing components and an appropriate container. Swing
adds J for each component to distinguish it from AWT equivalent like JFrame for Frame,
JButton for Button and so on. Similarly swing is organized into a large set of packages which
are different from AWT packages.When components are added to a container, the order or
place where these components should be added is controlled by a layout manager. Swing
provides layout managers defined by AWT which are FlowLayout, BorderLayout, GridLayout,
GridbagLayout and CardLayout. If the user wants to take control of the layout, the layout may
be set to null. Each layout adds the components in a specified way.JTable is an advanced
container component that shows a two dimensional array of elements as a table. It can be used
to display data in tabular format including a header line. The JTable contains two constructors.
JTree is an advanced container introduced in swing to create and manage a hierarchical view
of data. A JTree starts with one root node, which contains sub-root nodes and their children
nodes. The tree can be expanded or collapsed similar to a file explorer in windows. When a
node is selected from the JTree, it generates a TreeSelectionEvent which can be handled by
implementing TreeSelectionListener interface. A JTree object can be constructed using one its
constructors

183
12.6. CHECK YOUR PROGRESS MODEL ANSWERS
1. Swing uses model view controller (MVC) architecture which gives a clean separation
among the three components.
2. JTextArea works just like a JTextField, but can take multi-line input like address, feedback
etc.
3. JTree is an advanced container introduced in swing to create and manage a hierarchical
view of data.

12.7. MODEL EXAMINATION QUESTIONS


I. Answer the following questions in about 30 lines each
i. Create a GUI registration form application that takes the input from the user and shows
it in a text area. The user should be able to fill the following: Name (text box), Gender
(Radio Buttons), Age (Combo box with 18 to 25) and Hobbies (check boxes with Movies,
Reading, and Sports). When the user clicks the OK button, the input must be shown to
the user in a text area one item per line. When the user clicks the Cancel button, it
should clear all the fields.
2. Create a tree with books as root node where the user can select a book, which contains
chapters, and each chapter contain one or two topics. When the user selects a topic, it
should show its content in the bottom portion of the window. (Tip: Use the tree example
as the basis. For simplicity, add two books, with each having at least 2 chapters, and
each chapter contains at least two topics. Each topic has text of a simple sentence.
3. Describe various swing components with their constructors
II. Answer the following questions in about 15 lines each
1. Create a table with data from a database table which contains name, phone number,
gender and age as columns. Show this within a scroll pane.
2. Write a Java program to demonstrate swing image icon component with an image and
lable.
3. Describe the differences between swing and awt..

12.8 GLOSSARY
MVC : Swing uses model view controller (MVC) architecture which
gives a clean separation among the three components.
JTabbedPane : Provides an advanced view for the components, where the
components are organized into different screens with tabs.
Delegation Model :Separating event handlng mechanism into
event, source, handler
JTree : An advanced container introduced in swing to create and
manage a hierarchical view of data.
Image Icon : Is an implementation of the Icon interface that paints Icons
from Images.
Layout Manager : When components are added to a container, the order or place
where these components should be added is controlled by a
184 layout manager.
Dr. B.R. Ambedkar Open University
B.Sc / B.Com./ B.A.
th
3rd Year 5 Semester (3 year degree course)
MODEL QUESTION PAPER
COMPUTER APPLICATIONS DSCC-4
DATA BASE MANAGEMENT SYSTEM
[Time: 3 hours] [Max. Marks: 80]
Section – A
[Short Answer Questions]
[Marks: 4x5=20]
Note: a) Answer any four of the following in about 10 lines each
b) Each question carries 5marks
1. [Block-I] Describe the steps to set the path and class path of Java 8..
2. [Block-I] Write a java program to print the size of various data types..
3. [Block-II] Write a java program to demonstrate box and Unbox int data type.
4. [Block-II] Describe final key word with inheritance in Java..
5. [Block-III] Describe the try catch finally blocks.
6. [Block-III] What is Array class? Write a program to demonstrate Array class.
7. [Block-IV] What is prepared statement? Describe with an example.
8. [Block-IV] Write a java program to close the awt window using adapter class
Section –B
[Essay type]
[Marks: 4x10=40]
Note: a) Answer any four of the following in about 30 lines each
b) Each question carries 10marks
9. [Block-I] Explain bitwise operators with suitable code examples in Java..
(Or)
10. [Block-I] Write program to find the prime numbers in a given range.

11. [Block-II] Explain static variables, static methods.static block with examples
(Or)
12. [Block-II] Explain multilevel inheritance with an example java program.

13. [Block-III] Describe nested interfaces using a java program.


(Or)
14. [Block-III] Explain Newly added three exceptions in java 8 with examples

15. [Block-IV] Wrote a java program to update database table in mysql.


(Or)
16. [Block-IV] Write a java program to demonstrate JLable, Image Icon using Swing 185
Section –C
[Objective type questions]
[Marks: 20]
Total Number of questions 20-[15 from (Theory) and 5 from (Practical’s)]
I. Multiple choice questions (10 marks)
1. Tells the JVM Where to find theclass libraries, user-defined class libraries (2)
1) Path 2) Class Path 3) Package 4) Class
2. Abbreviation of Java Runtime Environment………… (2)
1) JREV 2) JRE 3) JRET 4) IERM
3. .................is automatically added to every class, if we do not write our own. (1)
1) Constructor 2) Member function 3) Class name 4) Private
4. Operator overloading is supported by ……………………feature of Java (2)
1) Encapsulation 2) Polymorphism
3) Late Management System 4) Inheritance
5. A member function can always access the data in ............., (in Java) (4)
1) Public member 2) Private member
3) Members of same class 4) All members
6. ………………..is size of float data type in Java (2)
1) 2 Bytes 2) 4 Bytes 3) 6 Bytes 4) 8 Bytes
7. .............Contains constants, method declarations, default methods (3)
1) Class 2) Package 3) Interface 4) Method
8. .....................Container which contains classes and interfaces to reuse names. (2)
1) Class 2) Package 3) Interface 4) Method
9. …………………..is Java Connector Driver to Connect to MySQL database (2)
1) Connector/MySQL 2) Connector/J 3) JDBC?ODBC 4) ) J/Connector
10. ………Is an implementation of the Icon interface that paints Icons from Images. (3)
1) ITree 2) JLabel 3) Image Icon 4) JTabbed Pane
II. Match the following (5 marks)
1. Encapsulation (c) a. Polymorphism
2. AWT (e) b. Data type
3. Operator Overloading ( a ) c. Class
4. int (b ) d. Collection
5. HashMap (d) e. Java GUI Programming
( ) f. Object

186
III. Fill in the blanks (5 marks)
1. Full form of JVM Java Virtual Machine
2. Full form ofJava SE 8 is Java Standard Edition 8
3. Full form ofJava JDK 8 is Java Development Kit 8
4. A member function with class name which initialize members is Constructor.
5. In Java members of classes are by default private

187

You might also like