You are on page 1of 175

SYLLABUS

Basic concepts of Object Oriented Programming, Genesis of java, History of java, Features of
java, Java Virtual Machine (JVM), Difference between java and C++, Java Tokens, Variables
and Operators, Array, Conditional Statements, Control Statements. Garbage Collector

Classes and Objects, Assess Specifier, Constructor, Subclasses, Inheritance, Abstract Class,
Packages and Interfaces, Exception Handling, Applet Programming, AWT package, Layout,
Swings, Java Streams, JDBC, Multithreading, Java.Util package

www.arihantinfo.com
Table of Content

UNIT 1: Concepts of Object Oriented Programming

1. Basics of OOP’s
1.1Introduction
1.2Object Oriented Paradigm
1.3Basic concepts of Object Oriented Programming
1.3.1 Object
1.3.2 Classes
1.3.3 Data Abstraction and Encapsulation
1.3.4 Inheritance
1.3.5 Polymorphism

UNIT 2: Fundamentals of Java Language


1. Introduction to Java
2.1 Genesis of Java
2.2 Why Java?
2.3 History of Java
2.4 Oak
2.5 Java Feature
2.5.1 Simple
2.5.2 Secure
2.5.3 Portable
2.5.4 Object Oriented
2.5.5 Interpreted
2.5.6 Robust
2.5.7 Multithreaded
2.5.8 Interpreted
2.5.9 Dynamic and Distributed
2.5.10 Architecture Nature and Portable
2.6 Difference between java and C++
2.7 The Java Virtual Machine
2.8 Java Program Structure
2.9 Java Token
2.9.1 Identifiers
2.9.2 Keywords
2.9.3 Literals
2.9.4 Operators
2.9.5 Separators
2.10Comments
2.11White Space
2.12Constants
2.13Backslash Character Constant

UNIT 3: Variables and Operators


3.1Variables
3.2Data Types in java
3.3Scope of Variables
www.arihantinfo.com
3.4Array
3.4.1 One-Dimensional Array
3.4.2 Two-Dimensional Array
3.5Strings
3.6Operators
3.6.1 Arithmetic Operators
3.6.2 Assignment Operators
3.6.3 Conditional Operators
3.6.4 Special Operators
3.6.5 Relational Operators
3.6.6 Boolean Logical Operators
3.6.7 Incrementing and Decrementing Operators
3.6.8 Bitwise Operators
3.7Operator Precedence

UNIT 4: Control Statements


4.1Selection Statements
4.1.1 If
4.1.2 If ..Else
4.1.3 If..Else if .. else
4.2The Switch Statement
4.3Iteration Statement
4.3.1 The while Statement
4.3.2 The do Statement
4.3.3 The for Statement
4.4The Comma Operator
4.5The break Statement
4.6The continue Statement

UNIT 5: Classes and Objects


5.1Classes
5.1.1 The class Declaration
5.1.2 Declaring a class’s Superclass
5.1.3 Listing the interface implemented by a class
5.1.4 Summary of a class Declaration
5.2Declaring Member Variables
5.3Declaring Constants
5.4The Method Declaration
5.5Object Creation and Constructors
5.5.1 Object Creation
4.5.2 Constructor
5.6Controlling access to member of a class
5.6.1 Private
5.6.2 Protected
5.6.3 Public
5.7Subclasses and Inheritance
5.7.1 Definition
5.7.2 Creating Subclasses
5.8Overriding Methods
5.9Final classes and Methods
5.9.1 Final Classes

www.arihantinfo.com
5.9.2 Final Methods
5.10 Abstract classes and Methods
5.10.1 Abstract classes
5.10.2 Abstract Methods

UNIT 6: Packages and Interfaces


6.1Packages
6.1.1 How to create your own packages
6.2Classpath
6.3The meaning of static
6.4Cleanup: Finalization and Garbage collection
6.5Forcing Finalization and Garbage collection
6.6Interfaces
6.6.1 What is an interface
6.6.2 The interface Declaration
6.6.3 Multiple Extension (Inheritance)
6.6.4 Implementing an interface
6.6.5 Using an interface as a type
6.6.6 Interfaces verses abstract classes

UNIT 7: GUI Programming

7.1Introduction to Applet Programming


7.2What are Applets
7.2.1 What applet can do
7.2.2 What applet can not do
7.3Types of an Applet
7.3.1 Local Applet
7.3.1.1 Remote Applet
7.4Lifecycle of an Applet
7.5Passing parameters to an Applet

UNIT 8: Programming the Abstract Windowing Toolkit (AWT)


8.1Introduction of AWT
8.2AWT Component Hierarchy
8.3How to Add a Component to a Container
8.4AWT Component
8.4.1 Labels
8.4.2 Buttons
8.4.3 Checkbox
8.4.4 TextFields
8.4.5 TextAreas
8.4.6 Choice lists
8.4.7 Scrolling Lists
8.5Event Handling
8.5.1 Introduction
2.5.2 Event Listener Interfaces
8.6How to implement event handlers:
8.6.1 Buttons
8.6.2 Canvases
8.6.3 Checkboxes

www.arihantinfo.com
8.6.4 Choices
8.6.5 Lists
8.6.6 ScrollPanes
8.6.7 TextComponent
8.6.8 Menus
8.7AWT Containers
8.7.1 Frames
8.7.2 Panels
8.7.3 Dialogs
8.8Layouts
8.8.1 The FlowLayout Class
8.8.2 The BoderLayout Class
8.8.3 The GridLayout Class
8.8.4 The GridBagLayout Class
8.8.5 The CardLayout class
8.8.6 Combining Layouts with Nested Panels
8.9Using Adapters to Handle Events

UNIT 9: JFC AND SWING COMPONENT


9.1Introduction
9.2Difference between AWT and Swing Components
9.3Overview of Jcomponent
9.4All about Controls (JComponents)
9.4.1 JApplet Example
9.4.2 JFrame
9.4.3 Changing the Look and Feel (LAF)
9.4.4 Jlabel
9.4.5 JButton
9.4.6 New Feature in JDK 1.2.2
9.4.7 JtoolTip
9.4.8 JtextField
9.4.9 JcheckBox
9.4.10 Jpanel
9.4.11 JSlider Basics

UNIT 10: Advance Programming Element


Java Streams
10.1What is Stream
10.2Byte Stream
10.2.1 File Stream
10.2.2 Data Stream
10.3 Character Streams
10.3.1 Reading Text Files
10.3.2 Writing Text Files

UNIT 11: Exception Handling


11.1Introduction
11.2What are Exception
www.arihantinfo.com
11.3Try/catch
11.4The finally clause
11.5The throws clause
11.6The throw clause
11.7User Define Exception

UNIT 12: Java Database Connectivity


12.1 Getting started with JDBC
12.2 What is JDBC
12.3 JDBC Architecture
12.4 JDBC API Interface in a Nutshell
12.4.1 Driver Manager
12.4.2 Connection
12.4.3 Statement
12.4.4 Resultset
12.4.5 CallabelStatement
12.4.6 DatabaseMetaData
12.4.7 Driver
12.4.8 PreparedStatement
12.4.9 ResultSetMetaData
12.4.10DriverPropertyInfo
12.4.11Date
12.4.12Time
12.4.13TimeStamp
12.4.14Types
12.4.15Numeric
12.4.16Driver Interface
12.5 Application Area
12.6 Getting to Work
12.6.1 How to configure ODBC Driver
12.6.2 Connecting to a database
12.6.3 Executing database Queries
12.7 The Statement clause
12.8 The ResultSet class
12.9 More Complex Uses of JDBC
12.9.1 The PreaparedStatement class
12.9.2 The CallableStatement class
12.10Working with Multiple Database
12.11“DNSLess” Connection with the JDBC-ODBC “Bridge” Driver
12.11.1.1 MS Access Example
12.11.1.2 ODBC Driver for Oracle(from Oracle)
12.11.1.3 ODBC Driver for Oracle(from Microsoft)
12.11.1.4 ODBC Driver for Excel

UNIT 13: Multithreaded Application


13.1Introduction of Multithreading
13.2What is a Thread
13.3Creating New Threads
13.3.1 Subclassing the Thread class
13.4Implementing the Runnable Interface
13.5Thread States

www.arihantinfo.com
13.6The Thread API
13.7Scheduling and Priority
13.7.1 Setting Thread Priority
13.7.2 Waking up a Thread
13.7.3 Suspending and Resuming Thread Execution
13.7.4 Putting a Thread to Sleep

UNIT 14: The Java.util Package


14.1Introduction
14.2The Java collection Advantage: An Overview
14.3A good API
14.4Other Capabilities
14.5Sorting a Collection
14.6Unmodifiable collection
14.7Synchronized Collection

www.arihantinfo.com
UNIT 1: BASICS OF OOP’S

1.1 Introduction
1.2 Object Oriented Paradigm
1.3 Basic concepts of Object Oriented Programming
1.3.1 Object
1.3.2 Classes
1.3.3 Data Abstraction and Encapsulation
1.3.4 Inheritance
1.3.5 Polymorphism

1.1 Introduction

The object-oriented paradigm was first conceived in the 1960's and implemented in
languages such as SIMULA-67. One of the initial concerns with early object-oriented
languages was their efficiency. Programs written using structured languages, such as Pascal
and C, executed faster than programs written using early object-oriented languages.
Although programs which used the object-oriented paradigm were more extensible and
easier to maintain from a programmer's point of view, an unacceptable price had to be paid
in the program's runtime behaviour. Recently, however, the runtime execution of object-
oriented programs has improved considerably. This has been due in part to both the
development of faster hardware and the creation of efficient languages and compilers which
support object-oriented programming, such as C++. These facts, in addition to the ever-
increasing accessibility of object-oriented languages to the common programmer has created
a major evolution in the area of software development.

There is, as yet, no universally agreed upon definition of exactly what constitutes object-
oriented programming. Booch suggests:
“Object-oriented programming is a method of implementation in which programs are
organized as cooperative collections of objects, each of which represents an instance of some
class, and whose classes are all members of a hierarchy of classes united via inheritance
relationships.''
From this definition, one can infer that object-oriented programming consists of
instantiating a number of objects which communicate with one another so as to achieve
some desired behaviour. This paradigm is natural with how humans see the world; as a
series of cause-effect relationships, where an action performed on one object has effects on
the objects with which it communicates.

1.2 Object Oriented Paradigm

The major objectives of object-oriented approach are to eliminate some of the flaws
encountered in the procedural approach. OOP treat data as a critical element in the
program development and does not allow it to flow freely around the system. It ties data
more closely to the functions that operate on it and protect it from unintentional

www.arihantinfo.com
modification by other functions. OOP allows us to decompose a problem into a number of
entities called Object and then build data and function (known as methods in java) around
these entities. The combination of data and methods make up an object.

The data of an object can be accessed only by the methods associated with that object.
However, methods of one object can access the methods of other objects. Some of the
features of object-oriented paradigm are:

• Emphasis is on data rather than procedure.

• Programs are divided into what are known as Objects.

• Data structures are designed such that they characterized the objects.

• Methods that operate on the data of an object are tied together in the data structure.

• Data is hidden and cannot be accessed by external functions.

• Objects may communication with each other through methods.

• New data and methods can be easily added whenever necessary.

1.3 Basic concepts of Object Oriented Programming

1.3.1 Object
Objects are key to understanding object-oriented technology. You can look around you now
and see many examples of real-world objects: your dog, your desk, your television set, your
bicycle.
These real-world objects share two characteristics: They all have state and behavior. For
example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and
wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, and
number of gears) and behavior (braking, accelerating, slowing down, and changing gears).

Software objects are modeled after real-world objects in that they too have state and
behavior. A software object maintains its state in one or more variables. A variable is an
item of data named by an identifier. A software object implements its behavior with
methods. A method is a function (subroutine) associated with an object.

Definition: An object is a software bundle of variables and related methods.

You can represent real-world objects by using software objects. You might want to represent
real-world dogs as software objects in an animation program or a real-world bicycle as
software object in the program that controls an electronic exercise bike. You can also use
software objects to model abstract concepts. For example, an event is a common object used
in GUI window systems to represent the action of a user pressing a mouse button or a key
on the keyboard.
The following illustration is a common visual representation of a software object:

www.arihantinfo.com
Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and the methods within that object. A software object that modeled your real-
world bicycle would have variables that indicated the bicycle's current state: its speed is 10
mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are
formally known as instance variables because they contain the state for a particular bicycle
object, and in object-oriented terminology, a particular object is called an instance.
The following figure illustrates a bicycle modeled as a software object.

In addition to its variables, the software bicycle would also have methods to brake, change
the pedal cadence, and change gears. (The bike would not have a method for changing the
speed of the bicycle, as the bike's speed is just a side effect of what gear it's in, how fast the
rider is pedaling, whether the brakes are on, and how steep the hill is.) These methods are
formally known as instance methods because they inspect or change the state of a particular
bicycle instance.

1.3.2 Classes
In the real world, you often have many objects of the same kind. For example, your bicycle
is just one of many bicycles in the world. Using object-oriented terminology, we say that
your bicycle object is an instance of the class of objects known as bicycles. Bicycles have
some state (current gear, current cadence, two wheels) and behavior (change gears, brake)
in common. However, each bicycle's state is independent of and can be different from that of
other bicycles.
When building bicycles, manufacturers take advantage of the fact that bicycles share
characteristics, building many bicycles from the same blueprint. It would be very inefficient
to produce a new blueprint for every individual bicycle manufactured.

In object-oriented software, it's also possible to have many objects of the same kind that
share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle
manufacturers, you can take advantage of the fact that objects of the same kind are similar
and you can create a blueprint for those objects. A software blueprint for objects is called a
class.

www.arihantinfo.com
Definition: A class is a blueprint, or prototype, that defines the variables and the methods
common to all objects of a certain kind.

The class for our bicycle example would declare the instance variables necessary to contain
the current gear, the current cadence, and so on, for each bicycle object. The class would
also declare and provide implementations for the instance methods that allow the rider to
change gears, brake, and change the pedaling cadence, as shown in the next figure.

After you've created the bicycle class, you can create any number of bicycle objects from the
class. When you create an instance of a class, the system allocates enough memory for the
object and all its instance variables. Each instance gets its own copy of all the instance
variables defined in the class.

In addition to instance variables, classes can define class variables. A class variable
contains information that is shared by all instances of the class. For example, suppose that
all bicycles had the same number of gears. In this case, defining an instance variable to
hold the number of gears is inefficient; each instance would have its own copy of the
variable, but the value would be the same for every instance. In such situations, you can
define a class variable that contains the number of gears. All instances share this variable.
If one object changes the variable, it changes for all other objects of that type. A class can
also declare class methods. You can invoke a class method directly from the class, whereas
you must invoke instance methods on a particular instance.

www.arihantinfo.com
1.3.3 Data Abstraction and Encapsulation

The wrapping up of data and methods into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world and only those methods, which are wrapped in the class, can
access it. These methods provide the interface between the object’s data and program. The
insulation of data from direct access by the program is called data hiding. Encapsulation
makes it possible for objects to be treated like ‘black boxes’, each performing a specific task
without any concern for internal implementation.

Information “in” Data Information “out”


and
Method

Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far
too small for you to see is the structure of the compound or molecule that does work in your
bloodstream or organs to cure your disease. You don't even see the components of the
mixture, which might be white medicine mixed with, say green flour. The complexity is
hidden from you. Your orders are simple and external to the encapsulation: take one green
pill each day with water.

Encapsulation is like a black box. When you purchase a television set, you do not need to
know the details of the electronics inside (raster-scanning cathode ray tube with magnetic
electron gun, alternating current transformer, hundreds of capacitors, thousands of
transistors). Instead, you only need to know how to plug in the UNIT, attach the cable, turn
the on switch, and press buttons on the remote control. You have a UNIT that sends visual
and audio messages to you, and you do not care about the hidden actions within the unit.

Abstraction

Refers to the act of representing essential features without including the background details
or explanations.

1.3.4 Inheritance

www.arihantinfo.com
Generally speaking, objects are defined in terms of classes. You know a lot about an object
by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a
bicycle, you would know that it had two wheels, handle bars, and pedals.
Object-oriented systems take this a step further and allow classes to be defined in terms of
other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of
bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all
subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain
bikes, racing bikes, and tandems. This relationship is shown in the following figure.

Each subclass inherits state (in the form of variable declarations) from the superclass.
Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like.
Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes,
and tandems share some behaviors: braking and changing pedaling speed, for example.
However, subclasses are not limited to the state and behaviors provided to them by their
superclass. Subclasses can add variables and methods to the ones they inherit from the
superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain
bikes have an extra set of gears with a lower gear ratio.

Subclasses can also override inherited methods and provide specialized implementations for
those methods. For example, if you had a mountain bike with an extra set of gears, you
would override the "change gears" method so that the rider could use those new gears.

You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy,
can be as deep as needed. Methods and variables are inherited down through the levels. In
general, the farther down in the hierarchy a class appears, the more specialized its behavior.

The Object class is at the top of class hierarchy, and each class is its descendant (directly or
indirectly). A variable of type Object can hold a reference to any object, such as an instance
of a class or an array. Object provides behaviors that are required of all objects running in
the Java Virtual Machine. For example, all classes inherit Object's toString method, which
returns a string representation of the object.

Inheritance offers the following benefits:

• Subclasses provide specialized behaviors from the basis of common elements provided by
the superclass. Through the use of inheritance, programmers can reuse the code in the
superclass many times.

• Programmers can implement superclasses called abstract classes that define "generic"
behaviors. The abstract superclass defines and may partially implement the behavior,
but much of the class is undefined and unimplemented. Other programmers fill in the
details with specialized subclasses.
www.arihantinfo.com
1.3.5 Polymorphism

Polymorphism is the combination of the two Greek world, poly i.e. many and morphism i.e.
forms, means the ability to take more than one form. For example, an operation may exhibit
different behavior in different instance. The behavior depends upon the types of data used
in the operation. For example, consider the operation of addition. For two numbers, the
operation will generate a sum. If the operands are string, then the operation would produce
a third string by concatenation.

www.arihantinfo.com
UNIT 2 : INTRODUCTION TO JAVA

Introduction to Java
2.1Genesis of Java
2.2Why Java?
2.3History of Java
2.4Oak
2.5Java Feature
2.5.1 Simple
2.5.2 Secure
2.5.3 Portable
2.5.4 Object Oriented
2.5.5 Interpreted
2.5.6 Robust
2.5.7 Multithreaded
2.5.8 Interpreted
2.5.9 Dynamic and Distributed
2.5.10 Architecture Nature and Portable
2.6Difference between java and C++
2.7The Java Virtual Machine
2.8Java Program Structure
2.9Java Token
2.9.1 Identifiers
2.9.2 Keywords
2.9.3 Literals
2.9.4 Operators
2.9.5 Separators
2.10Comments
2.11White Space
2.12Constants
2.13Backslash Character Constant

2.1 Genesis of Java


Java is related to C++, which is a direct descendent of C. Much of the character of Java is
inherited from these two languages. From C, Java derives its syntax. Many of Java's object
oriented features were influenced by C++.

By the end of the 1980's and early 1990's object oriented programming using C++ took hold.
It seemed that programmers had finally found the perfect language but there were forces
brewing that would drive the computer language evolution forward. These forces were the
World Wide Web and the Internet.

As stated earlier in these notes, in 1990 a group at SUN Microsystems developed Java. In
some sense Java is what C++ might have been if it was not required to be backward
compatible with C. Java was originally called Oak but that turned out to be a copyrighted
name so after some brainstorming they chose the name Java. It doesn't really mean Just
another Vague Acronym.
www.arihantinfo.com
The original motivation of Java was not the Internet but was the need for a platform
independent language. This platform independence is exactly what is needed for Internet
programming. The Internet helped push Java to the forefront of programming and Java in
turn has a profound effect on the Internet.

Java has gone through two major upgrades from the original version 1.0.2 to version 1.1
and now to version 1.2 (also called Java 2). There are major changes in the language
between the versions.

2.2 Why Java?

In one of their early papers about the language, Sun described Java as follows:
Java: a simple, object-oriented, distributed, interpreted, robust, secure, architecture
neutral, portable, high-performance, multithreaded, and dynamic language.
Even though this is quite a string of buzzwords, they aptly describe the language.

2.3 History of Java

At first glance, it may appear that Java was developed specifically for the World Wide Web.
However, interestingly enough, Java was developed independently of the web, and went
through several stages of metamorphosis before reaching its current status of de facto
programming language for the World Wide Web. Below is a brief history of Java since its
infancy to its current state.

2.4 Oak
Bill Joy, currently a vice president at Sun Microsystems, is widely believed to have been the
person to conceive of the idea of a programming language that later became Java. In late
1970's, Joy wanted to design a language that combined the best features of MESA and C. In
an attempt to re-write the UNIX operating system in 1980's, Joy decided that C++ was
inadequate for the job. A better tool was needed to write short and effective programs. It was
this desire to invent a better programming tool that swayed Joy, in 1991, in the direction of
Sun's "Stealth Project" - as named by Scott McNealy, Sun's president.

In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the
project leader of Sun's OpenWindows user environment), and several other individuals met
in Aspen, Colorado for the first time to discuss the ideas for the Stealth Project. The goal of
the Stealth Project was to do research in the area of application of computers in the
consumer electronics market. The vision of the project was to develop "smart" consumer
electronic devices that could all be centrally controlled and programmed from a handheld-
remote-control-like device. According to Gosling, "the goal was ... to build a system that
would let us do a large, distributed, heterogeneous network of consumer electronic devices
all talking to each other." With this goal in mind, the stealth group began work.

www.arihantinfo.com
Members of the Stealth Project, which later became known as the Green Project, divided the
tasks amongst themselves. Mike Sheradin was to focus on business development, Patrick
Naughton was to begin work on the graphics system, and James Gosling was to identify the
proper programming language for the project. Gosling, who had joined Sun in 1984, had
previously developed the commercially unsuccessful NEWS windowing system as well as
GOSMACS - a C language implementation of GNU EMACS. He began with C++, but soon
after was convinced that C++ was inadequate for this particular project. His extensions and
modifications to C++ (also know as C++ ++ --), were the first steps towards the development
of an independent language that would fit the project objectives. He named the language
"Oak" while staring at an oak tree outside his office window! The name "Oak" was later
dismissed due to a patent search which determined that the name was copyrighted and
used for another programming language. According to Gosling, "the Java development team
discovered that Oak was the name of a programming language that predated Sun's
language, so another name had to be chosen."

"It's surprisingly difficult to find a good name for a programming language, as the team
discovered after many hours of brainstorming. Finally, inspiration struck one day during a
trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java
came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy
bechtolsheim.

There were several criteria that Oak had to meet in order to satisfy the project objective
given the consumer electronics target market. Given the wide array of manufacturers in the
market, Oak would have to be completely platform independent, and function seamlessly
regardless of the type of CPU in the device. For this reason, Oak was designed to be an
interpreted language, since it would be practically impossible for a complied version to run
on all available platforms. To facilitate the job of the interpreter, Oak was to be converted to
an intermediate "byte-code" format, which is then passed around across the network, and
executed/interpreted dynamically.

Additionally, reliability was of great concern. A consumer electronics device that would have
to be "rebooted" periodically was not acceptable. Another important design objective for Oak
would then have to be high reliability by allowing the least amount of programmer-
introduced errors. This was the motivation for several important modifications to C++. The
concepts of multiple-inheritance and operator overloading were identified as sources of
potential errors, and eliminated in Oak. Furthermore, in contrast to C++, Oak included
implicit garbage collection thereby providing efficient memory utilization and higher
reliability. Finally, Oak attempted to eliminate all unsafe constructs used in C and C++ by
only providing data structures within objects.

Another essential design criterion was security. By design, Oak-based devices were to
function in a network and often exchange code and information. Inherently, security is of
great concern in a networked environment, especially in an environment as network
dependent as the conceived Oak-based systems. For this reason, pointers were excluded in
the design of Oak. This would theoretically eliminate the possibility of malicious programs
accessing arbitrary addresses in memory.

2.5 Java Feature

• Simple
• Secure
• Portable
www.arihantinfo.com
• Object Oriented
• Robust
• Multithreaded
• Interpreted
• Distributed
• Architecture Neutral and Portable

2.5.1 Simple

Java was designed to be easy for the professional programmer. It is easy to learn and
can be used effectively. If you are an experienced C++ programmer, moving to Java
will require very little effort.

Does not use pointers. Since Java does not have structures, and strings and arrays
are objects, there's no need for pointers.

Does not use goto -- instead, provide labeled Break and Continue statements, and
exception handling.
Unlike C++, Java has no operator overloading, no multiple inheritance.

2.5.2 Secure

There is a concept of applets in Java, which can be downloaded without fear or virus or
malicious content, because the Java programs are confined to Java execution environment
and are not allowed to access other parts of the CPU.

Java programs cannot forge pointers to memory, or overflow arrays, or read memory outside
of the bounds of an array or string.

Byte-code verification process, performed by interpreter on any untrusted code that it loads
-- checks for stack overflows and underflows, illegal byte-codes, etc.

2.5.3 Portable

The Java programs called Applets run in the JVM (Java virtual machine) environment that
is in every browser therefore the programs can run anywhere.

2.5.4 Object Oriented


Class: collection of data and methods that operate on that data

Java comes with an extensive set of classes, arranged in packages.

Most things in Java are objects. The only exceptions: the primitive number, character, and
boolean types.

Strings are represented by objects, as are threads.

www.arihantinfo.com
A class is the basic unit of compilation and of execution in Java; all Java programs are
classes.

2.5.5 Interpreted

The Java compiler generates byte-codes for the Java Virtual Machine (JVM), rather than
native machine code.

2.5.6 Robust

Garbage collection and Exception handling make Java a robust language. In garbage
collection the user doesn’t have to bother about the memory allocation as, when the object
is no longer in use it is automatically deleted to release memory space.

2.5.7 Multithreaded

A single threaded application has one thread of execution running at all times and such
programs can do only one task at a time. A multi-threaded application can have several
threads of execution running independently and simultaneously. These threads may
communicate and cooperate and will appear to be a single program to the user.

2.5.8 Interpreted

The Java code is compiled into the byte code, which is the class file. The byte code is then
interpreted to the machine language by the JVM environment.
2.5.9 Dynamic and Distributed

Any class can be loaded into a running Java interpreter at any time, then dynamically
instantiated. Native code libraries can also be dynamically loaded.

Classes in Java are represented by the Class class. Information about a class is available
dynamically at run-time. See Reflection....

"Distributed" means lots of high-level support for networking (e.g. URL class in java.net
package).

Distributed nature of Java, combined with dynamic class loading capabilities, make it
possible for a Java interpreter to download and run code across the Internet.

1.5.10 Architecture Neutral and Portable

"Write once, run anywhere"

JVM = interpreter and run-time system, ported to various platforms

www.arihantinfo.com
No implementation-dependent aspects -- e.g. all primitive data types are defined in Java,
have same byte size on all platforms.

2.6 Differences between Java and C++


• Perhaps the single biggest difference between Java and C++ is that Java does not
support pointers. After examining C++ in detail we know that the pointer is one of C++'s
most powerful and important language features. It is also one of the most dangerous.
Pointers don't exist in Java, as their existence would violate security aspects of the
language. For example, using a pointer to gain access to memory addresses outside a
program's code and data a malicious program could damage the system, perform
unauthorized access etc.

• In Java all object variables, arguments and return types are references. There is no need
for the reference operator, &, of C++.

• In Java, assigning one object to another does not invoke an assignment operator
function. Instead, assigning one object to another has the effect of associating the
variable with another location in memory, much like a pointer assignment.

• Java has a streamlined approach to memory allocation. Like C++, it supports the new
keyword (which returns a reference). However it does not have a delete. Instead, when
the last reference to an object is destroyed (goes out of scope), the object itself is
destroyed the next time garbage collection occurs. The garbage collector runs as a
background process freeing up unused memory.

• Java does not support operator overloading. This is not such a big restriction as we
might think. After all, it is just as easy to say u = v.add (w) as u = v + w. This is precisely
the notation used when we make the matrix class within Java.

• Java does not support complex numbers and since it does not support operator
overloading we can't build complex numbers ourselves as is done in C++.

• Java does not include a preprocessor nor does it support preprocessor directives. The
preprocessor plays a lesser role in C++ than in C and the designers of Java felt that it
was time to eliminate it entirely.

• Java does not support automatic type conversions that result in a loss of precision.

• All the code in a Java program is encapsulated within one or more classes. Therefore
Java does not have what you would normally think of as global variables or functions.

• Java does not allow default arguments.

• Java does not support multiple inheritance. Java does support the interface, which is
similar to abstract classes in C++, and does give a form of multiple inheritance.

• Java does not support templates. In Java all classes inherit from a single class called
Object so that it is not difficult to write generalized classes building on the Object class
as the base type.

www.arihantinfo.com
2.7 The Java Virtual Machine
MACHINE LANGUAGE CONSISTS of very simple instructions that can be executed directly
by the CPU of a computer. Almost all programs, though, are written in high-level
programming languages such as Java, Pascal, or C++. A program written in a high-level
language cannot be run directly on any computer. First, it has to be translated into machine
language. This translation can be done by a program called a compiler. A compiler takes a
high-level-language program and translates it into an executable machine-language
program. Once the translation is done, the machine-language program can be run any
number of times, but of course it can only be run on one type of computer (since each type
of computer has its own individual machine language). If the program is to run on another
type of computer it has to be re-translated, using a different compiler, into the appropriate
machine language.
There is an alternative to compiling a high-level language program. Instead of using a
compiler, which translates the program all at once, you can use an interpreter, which
translates it instruction-by-instruction, as necessary. An interpreter is a program that acts
much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the
interpreter runs in a loop in which it repeatedly reads one instruction from the program,
decides what is necessary to carry out that instruction, and then performs the appropriate
machine-language commands to do so.

One use of interpreters is to execute high-level language programs. For example, the
programming language Lisp is usually executed by an interpreter rather than a compiler.
However, interpreters have another purpose: they can let you use a machine-language
program meant for one type of computer on a completely different type of computer. For
example, there is a program called "Virtual PC" that runs on Macintosh computers. Virtual
PC is an interpreter that executes machine-language programs written for IBM-PC-clone
computers. If you run Virtual PC on your Macintosh, you can run any PC program,
including programs written for Windows. (Unfortunately, a PC program will run much more
slowly than it would on an actual IBM clone. The problem is that Virtual PC executes
several Macintosh machine-language instructions for each PC machine-language instruction
in the program it is interpreting. Compiled programs are inherently faster than interpreted
programs.)

The designers of Java chose to use a combination of compilation and interpretation.


Programs written in Java are compiled into machine language, but it is a machine language
for a computer that doesn't really exist. This so-called "virtual" computer is known as the
Java virtual machine. The machine language for the Java virtual machine is called Java
bytecode. There is no reason why Java bytecode could not be used as the machine language
of a real computer, rather than a virtual computer. In fact, Sun Microsystems -- the
originators of Java -- have developed CPU's that run Java bytecode as their machine
language.

However, one of the main selling points of Java is that it can actually be used on any
computer. All that the computer needs is an interpreter for Java bytecode. Such an
interpreter simulates the Java virtual machine in the same way that Virtual PC simulates a
PC computer.

Of course, a different Java bytecode interpreter is needed for each type of computer, but
once a computer has a Java bytecode interpreter, it can run any Java bytecode program.
And the same Java bytecode program can be run on any computer that has such an

www.arihantinfo.com
interpreter. This is one of the essential features of Java: the same compiled program can be
run on many different types of computers.

Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute
the original Java program and let each person compile it into the machine language of
whatever computer they want to run it on? There are many reasons. First of all, a compiler
has to understand Java, a complex high-level language. The compiler is itself a complex
program. A Java bytecode interpreter, on the other hand, is a fairly small, simple program.
This makes it easy to write a bytecode interpreter for a new type of computer; once that is
done, that computer can run any compiled Java program. It would be much harder to write
a Java compiler for the same computer.

Furthermore, many Java programs are meant to be downloaded over a network. This leads
to obvious security concerns: you don't want to download and run a program that will
damage your computer or your files. The bytecode interpreter acts as a buffer between you
and the program you download. You are really running the interpreter, which runs the
downloaded program indirectly. The interpreter can protect you from potentially dangerous
actions on the part of that program.

2.8 Java Program Structure

public class ClassName


{

www.arihantinfo.com
class body
public static void main (String[] args)
{
method body
}
}

public class Hello {


public static void main(String[] args)
{
System.out.println("Hello");
}
}

Save this program in the folder say C:\javaprogram. The name of the class is the same as
the name of the file. When you’re creating a stand-alone program such as this one, one of
the classes in the file must have the same name as the file. (The compiler complains if you
don’t do this.) That class must contain a method called main () with the signature shown:

public static void main(String[] args)

The public keyword means that the method is available to the outside world. The static
keyword means that no need to create an object of this class to access the main function.
The void means function is not returning anything. The main keyword is the name of the
main function from where the execution will start and args are the command line
arguments.

By default java import a package java.lang and in this package we have a System class, and
System class has a static object out of PrintStream class. Since it’s static you don’t need to
create anything. The out object is always there and provides a println( ) function, which is
used to print the string on the console and end with a new line.” Thus, in any Java program
you write you can say System.out.println("things") whenever you want to print something to
the console.

Compiling and running

In order to compile the program open the command prompt and go to your directory and
write this command.

C:\javaprogram>javac Hello.java

This command should produce no response. But it will create Hello.class file in your folder
which is the bytecode of this program.

In order to run this program, write this command on the same command prompt.

C:\javaprogram>java Hello

Output will be: Hello

www.arihantinfo.com
2.9 Java Token:

A java program is a collection of tokens, comments and white spaces. Java language
includes five types of tokens. They are:

• Identifier
• Keyword
• Literal
• Separator
• Operator
2.9.1 Identifiers

The Java identifiers are the names given for classes, methods, variables, objects, labels,
packages and interfaces in a program. Here are the rules for creating a properly formed
identifier:

1. are names for classes, methods, or variables.

2. begin with a letter, underscore (_), or dollar sign ($).


Java
3. are case sensitive.
Identifiers
4. have no maximum length.

5. must not begin with digit.

Identifiers must be meaningful, short enough to be quickly and easily typed and long
enough to be descriptive and easily read.

2.9.2 Keywords
The following character sequences are reserved for use as keywords and cannot be used as
identifiers
Keyword: one of

abstract default if private this boolean


do implements protected throw break double
import public throws byte else instanceof
return transient case extends int short
try catch final interface static void
char finally long strictfp volatile class
float native super while const for
new switch continue goto package synchronized

The keywords const and goto are reserved, even though they are not currently used. This
may allow a Java compiler to produce better error messages if these C++ keywords
incorrectly appear in programs.

2.9.3 Literals

www.arihantinfo.com
Literal in java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. Java language specifies five major types
of literals. They are:

Integer Literal
Floating-Point Literal
Boolean Literal
Character Literal
String Literal
Null Literal

2.9.4 Operators
An operator is a symbol that takes one or more arguments and operates on them to produce
a result. The following 37 tokens are the operators, formed from ASCII characters:

Operator: one of
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ %
<< >> >>> += -= *= /= &=
|= ^= %= <<= >>= >>>=

2.9.5 Separators
Separators are symbols used to indicate where groups of code are divided and arranged.
They basically define the shape and function of our code. The following ASCII characters are
the separators (punctuators):
Separator: one of

() Parentheses
{ }Braces
[] Brackets
; Semicolon
, Comma
. Period
2.10 Comments
There are two kinds of comments

/* text */ A traditional comment: all the text from the ASCII characters
/* to the ASCII characters */ is ignored (as in C and C++).

// text A end-of-line comment: all the text from the ASCII characters
// to the end of the line is ignored (as in C++).

2.11 White Space


White space is defined as the ASCII space, horizontal tab, and form feed characters, as well
as line terminators
WhiteSpace:
www.arihantinfo.com
the ASCII SP character, also known as "space"
the ASCII HT character, also known as "horizontal tab"
the ASCII FF character, also known as "form feed"
LineTerminator

2.12 Constants

• A constant is an identifier that is similar to a variable except that it holds one value
for its entire existence

• The compiler will issue an error if you try to change a constant

• In Java, we use the final modifier to declare a constant

final int count = 100;

2.13 Backslash Character Constants

Constants Meanings

• ‘\b’ back space


• ‘\f’ form feed
• ‘\n’ new line
• ‘\r’ carriage return
• ‘\t’ horizontal tab
• ‘\’’ single quote
• ‘\”’ double quote
• ‘\\’ backslash

www.arihantinfo.com
UNIT 3: VARIABLES AND OPERATORS

3.1Variables
3.2Data Types in java
3.3Scope of Variables
3.4Array
3.4.1 One-Dimensional Array
3.4.2 Two-Dimensional Array
3.5Strings
3.6Operators
3.6.1 Arithmetic Operators
3.6.2 Assignment Operators
3.6.3 Conditional Operators
3.6.4 Special Operators
3.6.5 Relational Operators
3.6.6 Boolean Logical Operators
3.6.7 Incrementing and Decrementing Operators
3.6.8 Bitwise Operators
3.6.9 Operator Precedence

3.1 Variables

A variable is an identifier that denotes a storage location used to store a data value. A
variable name can be chosen by the programmer in a meaningful way so as to reflect what it
represents in the program. Variable name may consist of alphabets, digits, the underscore
( _ ) and dollar character, subject to the following conditions:

1. They must not begin with a digit.


2. Uppercase and lowercase are distinct. This means that the variable Amount is not
equal to amount or AMOUNT.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable name can be of any length.

www.arihantinfo.com
Data Types

Primitive Non-primitive

Numeric Non-numeric classes Interface Arrays

Integer Floating-point Character Boolean

char boolean
byte

short float

int
double

long

Every variable must have a data type. A variable's data type determines the values that the
variable can contain, size it takes in memory and the operations that can be performed on
it.

2.2 Data type in Java

The Java programming language has two categories of data types:

1. Primitive
2. Reference

A variable of primitive type contains a single value of the appropriate size and format for its
type: A Number, A Character, or A boolean value.
The following table lists, by keyword, all of the primitive data types supported by Java, their
sizes and a brief description of each.

Primitive Data Types

Keyword Description Size

(integers)

www.arihantinfo.com
Byte Byte-length integer One byte
Short Short integer Two bytes
Int Integer Four bytes
Long Long integer Eight bytes
(real numbers)
Float Single-precision floating point Four bytes
Double Double-precision floating point Eight bytes
(other types)
Two bytes
Char A single character
(Unicode character)
Boolean A Boolean value (true or false) true or false

Purity Tip: In other languages, the format and size of primitive data types may depend on the
platform on which a program is running. In contrast, the Java programming language
specifies the size and format of its primitive data types. Hence, you don't have to worry about
system-dependencies.

You can put a literal primitive value directly in your code. For example, if you need to assign
the value 4 to an integer variable you can write this:
int anInt = 4;

The digit 4 is a literal integer value. Here are some examples of literal values of various
primitive types:
Examples of Literal Values and Their Data Types

Literal Data Type


178 Int
8864L Long
37.266 Double
37.266D Double
87.363F Float
26.77e3 Double
'c' Char
True Boolean
False Boolean

Generally speaking, a series of digits with no decimal point is typed as an integer. You can
specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred, as it cannot be
confused with the digit '1'. A series of digits with a decimal point is of type double. You can
specify a float by putting an 'f' or 'F' after the number. A literal character value is any single

www.arihantinfo.com
Unicode character between single quote marks. The two boolean literals are simply true and
false.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in
contrast to that of a primitive type, is a reference to (an address of) the value or set of values
represented by the variable.

A reference is called a pointer or a memory address in other languages. The Java


programming language does not support the explicit use of addresses like other languages
do. You use the variable's name instead.

3.3 Scope of Variables


A variable's scope is the region of a program within which the variable can be referred to by
its simple name. Secondarily, scope also determines when the system creates and destroys
memory for the variable. Scope is distinct from visibility, which applies only to member
variables and determines whether the variable can be used from outside of the class within
which it is declared. Visibility is set with an access modifier.
The location of the variable declaration within your program establishes its scope and places
it into one of these categories:

• Instance variables

• Class variables

• Local variable

Instance and class variables are declared inside a class. Instance variable are created when
the objects are instantiated and therefore they are associated with the objects. They take
different values for each object. On the other hand, class variables are global to a class and
belong to the entire set of objects that class creates. Only one memory location is created for
each class variable.

Variables declared and used inside methods are called local variables. They are called so
because they are not available for use outside the method definition. Local variables can
also be declared inside program blocks that are defined between an opening brace { and a
closing brace }.These variables are visible to the program only from the beginning of its
program block to the end of the program block. When the program control leaves a block, all
the variables in the block will cease to exist. The are of the program where the variable is
accessible (i.e. usable) is called its scope.

3.4 Array

An array is a group of contiguous or related data items that share a common name.
Or we can say that an array stores multiple variables of
• the same type.

www.arihantinfo.com
• a specific number of indices ("slots").

• you access an element by using its index.

3.4.1 One-Dimensional Arrays

A list of items can be given one variable name using only one subscript and such a variable
is called a single-subscript variable or a one-dimensional array.

Declaration of Arrays:

type arrayname [] = new type[size];

For example we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array
variable number, then we may create the variable number as follows

int number[]=new int[5];

and computer reserves five storage locations as shown below

35 40 20 57 19

number[0] number[1] number[2] number[3] number[4]

Note that java creates arrays starting with a subscript of 0 and ends with a value one less
than the size specified. Unlike C, Java protects arrays from overruns and underruns. Trying
to access an array beyond its boundaries will generate an error message.

Initialization of Arrays:

arrayname[subscript]=value;

we can also initialize array automatically in the same way as the ordinary variables when
they are declared, as shown below.

type arrayname[ ] = {list of values};

Example :

int number [ ] = {35, 40, 20, 57, 19};

Array Length

In java, all arrays store the allocated size in a variable named length. We can access the
length of the array a using a.length. Example:

int aSize = a.length;

3.4.2 Two-Dimensional Arrays

www.arihantinfo.com
So far we have discussed the array variables that can store a list of values. There will be
situations where a table of values will have to be stored. Consider the following data table,
which shows the value of sales of three items by four salesgirls:

Item1 Item2 Item3

Salesgirl #1 310 275 365


Salesgirl #2 210 190 325
Salesgirl #3 405 235 240
Salesgirl #4 260 300 380

The table contains a total of 12 values, there in each line. We can think of this table as a
matrix consisting of four rows and three columns. Each row represents the values of sales
by a particular salesgirl and each column represents the values of sales of a particular item.

For creating two-dimensional arrays, we must follow the same steps as that of simple
arrays, we may create a two-dimensional array like this:

type arrayname[][]=new type[row][col];


int myarray = new int[3][4];

like the one-dimensional array, two-dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces. For example,

int table[2][3] = {2, 2, 2, 4, 4, 4};

initialize the elements of the first row to zero and the second row to one. The initialization is
done row by row. The above statement can be equivalently written as

int table[ ] [ ] = { {2, 2, 2}, {4, 4, 4}};

by surrounding the elements of each row by braces.

3.5 Strings
Internally, a String is an array of characters, an array of char. The Java API, however,
considers a String to be an object. Therefore, you benefit from built-in methods and
property to help you handle strings.

3.6 Operators

3.6.1 Arithmetic Operators

Operator Name Use Description

+ Addition Op1 + op2 Adds op1 and op2

- Subtraction Op1 - op2 Subtracts op2 from op1

www.arihantinfo.com
* multiplication Op1 * op2 Multiplies op1 by op2

/ Division Op1 / op2 Divides op1 by op2

% modulus (or mod) Op1 % op2 Computes the remainder of dividing op1 by op2

The arithmetic operators return a number.


numeric return value = <operand1> <operator> <operand2>;
example: myLongString = myShortString + myOtherString;
• + addition

o adds two numbers

o concatenates two string objects

• - subtraction

o subtract one number from another

• * multiplication

o multiply two numbers

• / division

o divide two numbers

• % modulus

o the remainder of an integer division

o 5 % 3 = 2 Because 5/3 = 1 and leaves 2.

o myRemainder = 5 % 3;

3.6.2 Assignment Operator

You use the assignment operator, =, to assign one value to another.

Compound Assignment Operator

Operator Use Equivalent to


+= Op1 += op2 Op1 = op1 + op2
-= Op1 -= op2 Op1 = op1 - op2
*= Op1 *= op2 Op1 = op1 * op2
/= Op1 /= op2 Op1 = op1 / op2
%= Op1 %= op2 Op1 = op1 % op2

www.arihantinfo.com
&= Op1 &= op2 Op1 = op1 & op2
|= Op1 |= op2 Op1 = op1 | op2
^= Op1 ^= op2 Op1 = op1 ^ op2
<<= Op1 <<= op2 Op1 = op1 << op2
>>= Op1 >>= op2 Op1 = op1 >> op2
>>>= Op1 >>>= op2 Op1 = op1 >>> op2

3.6.3 Conditional Operator

Operator Use Description

If op1 is true, returns op2. Otherwise, returns


?: Exp1 ? exp2 : exp3
op3. (This is the conditional operator.)

3.6.4 Special Operators

Declares an array of unknown length, which contains type


[] Type []
elements.

Creates and array with op1 elements. Must be used with the
[] Type[ op1 ]
new operator.

Accesses the element at op2 index within the array op1. Indices
[] op1[ op2 ] begin at 0 and extend through the length of the array minus
one.

. op1.op2 Is a reference to the op2 member of op1.

Declares or calls the method named op1 with the specified


() op1(params ) parameters. The list of parameters can be an empty list. The
list is comma-separated.

Casts (converts) op1 to type. An exception will be thrown if the


(type) (type) op1
type of op1 is incompatible with type.

new New op1


Creates a new object or array. op1 is either a call to a
constructor, or an array specification.
op1 instanceof
Instanceof
op2 Returns true if op1 is an instance of op2

3.6.5 Relational Operators

Logical operators test a condition by comparing values and return a boolean value (true or
false).
• == equal (two adjacent equal signs)
if (sum = = 100) { // do something ...

www.arihantinfo.com
WARNING: Testing for identical values with = = is different from assigning a value
with =

• != not equal
if (sum != 100) { // do something ...

• > greater than


if (sum > 100) { // do something ...

• < less than


if (sum < 100) { // do something ...

• >= greater than or equal to


if (sum >= 100) { // do something ...

• <= less than or equal to


if (sum <= 100) { // do something ...
Here's two comparison operators in a sequence:
isBigSum = sum > 100;
The variable isBigSum gets the value true only if the sum is greater than 100.

3.6.6 Boolean Logical Operators


• & - ampersand is the logical and operator
boolean isAllExpensive = (cost1 >= 100) & (cost2 >= 100);
Both cost1 and cost2 must be >= 100 to return true and both cost1 and cost2 are
evaluated

• && - double ampersand is the logical and operator that can "shortcircuit" when
appropriate
boolean isAllExpensive = (cost1 >= 100) && (cost2 >= 100);
// Both cost1 and cost2 must be >= 100 to return true and if cost1 fails the test,
cost2 is NOT evaluated.

• | - the logical or operator is the "pipe" key


boolean hasExpensive = (cost1 >= 100) | (cost2 >= 100);
Either cost1 or cost2 must be >= 100 to return true and both cost1 and cost2 are
evaluated

• || or - double "pipe" is the logical or operator that can "shortcircuit" when


appropriate
boolean isAllExpensive = (cost1 >= 100) || (cost2 >= 100);
Either cost1 or cost2 must be >= 100 to return true and if cost1 passes the test,
cost2 is NOT evaluated.
Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of
the logical operators (||).

Truth table

Operand1 Operand2 == != && ||


www.arihantinfo.com
True true True false true true
true false False true false true
False true False true false true
False false True false false false

3.6.7 Incrementing and Decrementing

These short cut unary operators increment or decrement a number by one.


Operator Use Description

++ Op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op after it was incremented

-- Op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented


Note the difference between prefix versus post-fix.

3.6.8 Bitwise Operators

Bitwise operators are used for testing the bits, or shifting them to right or left. Bitwise
operators may not be applied to float or double.

Operator Meaning

& bitwise AND


! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill

3.7 Operator Precedence

Mnemonic Operator type Operators


Ulcer Unary + - ++--
Addicts Arithmetic (and * / % + - << >>
shift)
Really Relational > < >= <= == !=
Like Logical (and bitwise) && || & | ^
C Conditional (ternary) A>B?X:Y

www.arihantinfo.com
A Lot Assignment = (and compound
assignment like *=)

www.arihantinfo.com
UNIT 4: CONTROL STATEMENTS

4.1Selection Statements
4.1.1 If
4.1.2 If ..Else
4.1.3 If..Else if .. else
4.2The Switch Statement
4.3Iteration Statement
4.3.1 The while Statement
4.3.2 The do Statement
4.3.3 The for Statement
4.4The Comma Operator
4.5The break Statement
4.6The continue Statement
4.7Selection Statements
4.7.1 If
4.7.2 If ..Else
4.7.3 If..Else if .. else
4.8The Switch Statement
4.9Iteration Statement
4.9.1 The while Statement
4.9.2 The do Statement
4.9.3 The for Statement
4.10The Comma Operator
4.11The break Statement
4.12The continue Statement

4.1 Selection Statements

• A conditional statement lets us choose which statement will be executed next

• Therefore they are sometimes called selection statements

• Conditional statements give us the power to make basic decisions

• Java's conditional statements are the if statement, the if-else statement, and the
switch statement

4.1.1 if
if( boolean expression ) {
statement1;
...
statementn;
}

www.arihantinfo.com
Note: Curly braces only required if there is more than one execution statement.

4.1.2 If..else
if(x==y){
// do this
} else {
// do this
}
Note: The "else" is for the last statement.

4.1.3 If..else if .. else


if( x == y ) {
// do this
} else if( x > y ) { // nested 'if'
// do this
// Note: any number of "else if" clauses after "if" and before "else"
} else {
// do this
}
Note: The "else" is for the last statement.

The output is:


x not > or = to y

4.2 The switch Statement

• The switch statement provides another means to decide which statement to execute
next

• The switch statement evaluates an expression, then attempts to match the result to
one of several possible cases

• Each case contains a value and a list of statements


www.arihantinfo.com
• The flow of control transfers to statement list associated with the first value that
matches

The general syntax of a switch statement is:

switch ( expression )
{
case value1 :
statement-list1; break;
case value2 :
statement-list2; break;
case value3 :
statement-list3; break;
default :
statement-list4; break;
}

• Often a break statement is used as the last statement in each case's statement list

• A break statement causes control to transfer to the end of the switch statement

• If a break statement is not used, the flow of control will continue into the next case

• A switch statement can have an optional default case

• If the default case is present, control will transfer to it if no other case value matches
• The test variable or expression to be tested can be of the primitive types byte, char,
short, or int

Example :
For example, the program:
class Toomany {
static void howMany(int k) {
switch (k) {
case 1: System.out.print("one ");
case 2: System.out.print("too ");
case 3: System.out.println("many");
}
}
public static void main(String[] args) {
howMany(3);
howMany(2);
howMany(1);
}
}
contains a switch block in which the code for each case falls through into the code for the
next case. As a result, the program prints:
many
too many

www.arihantinfo.com
one too many
If code is not to fall through case to case in this manner, then break statements should be
used, as in this example:
class Twomany {
static void howMany(int k) {
switch (k) {
case 1: System.out.println("one");
break; // exit the switch
case 2: System.out.println("two");
break; // exit the switch
case 3: System.out.println("many");
break; // not needed, but good style
}
}
public static void main(String[] args) {
howMany(1);
howMany(2);
howMany(3);
}
}
This program prints:
one
two
many

4.3 Iteration Statements

Java has three kinds of repetition statements: the while loop, the do loop, and the for loop

4.3.1 The while Statement


The while statement executes an Expression and a Statement repeatedly until the value of
the Expression is false.
While Statement:
while (Expression) Statement

The Expression must have type boolean, or a compile-time error occurs. The while is an
entry-controlled loop statement. Therefore, the body of a while loop will execute zero or more
times

public class WhileTest


{
public static void main(String[] args) {
int r = 0;
while(r < 3)
{
System.out.println(r);
}
}
}
www.arihantinfo.com
The output will be
0
1
2

4.3.2 The do Statement


The do statement executes a Statement and an Expression repeatedly until the value of the
Expression is false.

do
{
statement;
}
while ( condition )

The statement is executed once initially, and then the condition is evaluated
The statement is repetitively executed until the condition becomes false

• A do loop is similar to a while loop, except that the condition is evaluated after the
body of the loop is executed

• Therefore the body of a do loop will execute at least one time


• The do while is an exit control loop statement.

4.3.3 The for Statement


The for statement executes some initialization code, then executes an Expression, a
Statement, and some update code repeatedly until the value of the Expression is false.

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at the end of each iteration

Example:

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("value: " + (int)c + " character: " + c);
}
}

www.arihantinfo.com
4.4 The comma operator
Comma operator is used to separate definitions and function arguments
public class CommaOperator {
public static void main(String[] args) {
for(int i = 1, j = i + 10; i < 5;i++, j = i * 2) {
System.out.println("i= " + i + " j= " + j);
}}}

4.5 The break Statement

The Java break statement causes the Java interpreter to transfer the flow of execution to the
end of an enclosing statement. In other words, it is used to break out of a do, for, switch, or
while statement.

The syntax of the Java break statement is:

break;

Example:
for (int i=0; i < myArray.length; i++)
{
if (myArray[i] == null;
{
break; // break out of for loop
}
} // execution resumes at following statement on break

4.6 The continue statement


A Java continue statement is used to terminate the current iteration of a loop and continue
with the next iteration. A continue statement can only be used within a do, for, or while
loop.

The syntax of the Java continue statement is:

continue;

Example:
for (int i=0; i < myArray.length; i++)
{
if (myArray[i] == null;
{
continue; // skips remainder of loop and begins next iteration
}
myMethod (myArray[i]); // do something with a non-null myArray[i]
}

www.arihantinfo.com
The different types of looping statements vary in how the continue statement begins a new
iteration.

• do loop: On encountering a continue statement, the Java interpreter jumps to the


bottom of the do loop. Then, it evaluates the test condition to determine whether to begin
a new iteration.

• for loop: On encountering a continue statement, the Java interpreter begins at the top of
the loop in the for statement. First, it evaluates the update expression, e.g. i++. Then, it
evaluates the test expression, e.g. i < myArray.length. The important thing is that the
update expression is evaluated.

• while loop: On encountering a continue statement, the Java interpreter begins at the top
of the loop in the while statement. Then, it evaluates the test condition to determine
whether to begin a new iteration.

www.arihantinfo.com
UNIT 5: CLASSES AND OBJECTS

5.1Classes
5.1.1 The class Declaration
5.1.2 Declaring a class’s Superclass
5.1.3 Listing the interface implemented by a class
5.1.4 Summary of a class Declaration
5.2Declaring Member Variables
5.3Declaring Constants
5.4The Method Declaration
5.5Object Creation and Constructors
5.5.1 Object Creation
5.5.2 Constructor
5.6Controlling access to member of a class
5.6.1 Private
5.6.2 Protected
5.6.3 Public
5.7Subclasses and Inheritance
5.7.1 Definition
5.7.2 Creating Subclasses
5.8Overriding Methods
5.9Final classes and Methods
5.9.1 Final Classes
5.9.2 Final Methods
5.10 Abstract classes and Methods
5.10.1 Abstract classes
5.10.2 Abstract Methods

5.1 Classes

A class is a blueprint or prototype that you can use to create many objects.
classDeclaration {
memberVariableDeclarations
methodDeclarations
}

5.1.1 The Class Declaration

At minimum, a class declaration must contain the class keyword and the name of the class
that you are defining:
class NameOfClass {
...
}

www.arihantinfo.com
5.1.2 Declaring a Class's Superclass
In Java, every class has a superclass. If you do not specify a superclass for your class, it is
assumed to be the Object class (declared in java.lang).
class NameOfClass extends SuperClassName {
...
}
A subclass inherits variables and methods from its superclass.

5.1.3 Listing the Interfaces Implemented by a Class


An interface declares a set of methods and constants without specifying the implementation
for any of the methods. When a class claims to

implement an interface, it's claiming to provide implementations for all of the methods
declared in the interface.
class ImaginaryNumber extends Number implements Arithmetic {
...
}

5.1.4 Summary of a Class Declaration

[ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] {


...
}
• modifiers declare whether the class is public, abstract, or final

• ClassName sets the name of the class you are declaring

• SuperClassName is the name of ClassName's superclass

• InterfaceNames is a comma-delimited list of the interfaces implemented

5.2 Declaring Member Variables


class IntegerClass {
int anInteger;
. . . // define methods here . . .}
In short, a member variable declaration looks like this:
[accessSpecifier] [static] [final] type variableName
accessSpecifier defines which other classes have access to the variable. You control access
to methods using the same specifiers, so Controlling Access to Members of a Class covers
how you can control access to both member variables and methods.

static indicates that the variable is a class member variable as opposed to an instance
member variable. You also use static to declare class methods. Instance and Class Members
talks about declaring instance and class variables and writing instance and class methods.

www.arihantinfo.com
5.3 Declaring Constants
class Avo {
final double AVOGADRO = 6.023e23;
}

5.4 The Method Declaration


returnType methodName() { . . . }

Passing Information into a Method

The Method Body


...
boolean isEmpty() {
if (topelement == STACK_EMPTY)
return true;
else
return false;
}

5.5 Object Creation and Constructor

5.5.1 Object Creation


Although most of the design work in object-oriented programming is creating classes, you
don't really benefit from that work until you create instances (objects) of those classes. To
use a class in a program, you must first create an instance of it.

5.5.2 Constructor

Before getting into the details of how to create an object, there is an important method you
need to know about: the constructor. When you create an object, you typically want to
initialize its member variables. The constructor is a special method you can implement in all
your classes; it allows you to initialize variables and perform any other operations when an
object is created from the class. The constructor is always given the same name as the
class.

The following Listing contains the complete source code for the Alien class, which contains
two constructors.

Listing . The Alien class.


class Alien extends Enemy {
protected Color color;
protected int energy;
protected int aggression;

public Alien() {
color = Color.green;
energy = 100;
aggression = 15;
}
www.arihantinfo.com
public Alien(Color c, int e, int a) {
color = c;
energy = e;
aggression = a;
}

public void move() {


// move the alien
}

public void move(int x, int y) {


// move the alien to the position x,y
}

public void morph() {


if (aggression < 10) {
// morph into a smaller size
}
else if (aggression < 20) {
// morph into a medium size
}
else {
// morph into a giant size
}
}
}

The Alien class uses method overloading to provide two different constructors. The first
constructor takes no parameters and initializes the member variables to default values. The
second constructor takes the color, energy, and aggression of the alien and initializes the
member variables with them. As well as containing the new constructors, this version of
Alien uses access modifiers to explicitly assign access levels to each member variable and
method. This is a good habit to get into.

5.6 Controlling Access to Members of a Class


Specifier class subclass package world
-----------------------------------------------------
private X

protected X X* X
public X X X X
package X X

5.6.1 Private
The most restrictive access level is private. A private member is accessible only
to the class in which it is defined.

www.arihantinfo.com
class Alpha {
private int iamprivate;
private void privateMethod() {
System.out.println("privateMethod");
}
}
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iamprivate = 10; // illegal
a.privateMethod(); // illegal
}}

5.6.2 Protected
It allows the class itself, subclasses, and all classes in the same package to
access the members.
package Greek;
class Alpha {
protected int iamprotected;
protected void protectedMethod() {
System.out.println("protectedMethod");
}
}
package Greek;
class Gamma {
void accessMethod() {
Alpha a = new Alpha();
a.iamprotected = 10; // legal
a.protectedMethod(); // legal
}
}
package Latin;
class Delta extends Alpha {
void accessMethod(Alpha a, Delta d) {
a.iamprotected = 10; a.protectedMethod(); // illegal
d.iamprotected = 10; d.protectedMethod(); // legal
}
}

5.6.3 Public
Any class, in any package, has access to a class's public members.
package Greek;

class Alpha {
public int iampublic;
public void publicMethod() {
System.out.println("publicMethod");

www.arihantinfo.com
}
}
import Greek.*;

package Roman;

class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iampublic = 10; // legal
a.publicMethod(); // legal
}
}

5.7 Subclasses and Inheritance

The derived class is called a subclass. The class from which its derived is called the
superclass.

In Java all classes must be derived from some class. The top-most class, the class from
which all other classes are derived, is the Object class defined in java.lang:

www.arihantinfo.com
5.7.1 Definition:
A subclass is a class that derives from another class. It subclass inherits state and behavior
in the form of variables and methods from all of its ancestors. It can just use the items
inherited from its superclass as is, or the subclass can modify or override it. So, as you drop
down in the hierarchy, the classes become more and more specialized.

5.7.2 Creating Subclasses

To declare a subclass you would write:


class SubClass extends SuperClass { . . . }

Note:- A Java class can have only one direct superclass. Java does not support multiple
inheritance.
Member variables defined in the subclass hide member variables of the same name in the
superclass. Consider this superclass and subclass pair:

class Super {
void addNum(int x,int y) {
int sum;
sum=x + y;
System.out.println(“Sum of Number = “+sum);
}
void display() {
System.out.println(“I am from SuperClass”);
}
}

class Sub extends Super {


public static void main(String args[]) {

www.arihantinfo.com
Sub s1 = new Sub();
s1.display();
s1.addNum(10,20);
}}

Output is :
I am from SuperClass
Sum of Number = 30

5.8Overriding Methods

The following example shows method overriding. When an object’s method is called, java
looks for the method definition in the object’s class. If it can not find, then it checks one
level up in the hierarchy of classes. Consider the case when the same method name is used
in both the superclass and superclass with the same signature (same number of arguments
with the same type). Here when the method is called, method defined in the subclass is
invoked. The method defined in the super class is overridden. It is now hidden for the
objects of the subclass. If the method defined in the super class has to be used, then the
super keyword can be used along with the name of the method. In the example below, the
method display() and this.display() will invoke method display() of the subclass. The call
super.display() will invoke the method display() of the super class. This program uses the
super class coded earlier as the program Super.java

class OverRide extends Super {


void access() {
System.out.println(“Displays from a different palce”);
//display method of subclass
display();
//display method of superclass
super.display();
//display method of subclass
this.display();
}
void display()
{
System.out.println(“I am from SubClass”);
}
public static void main(String args[]) {
OverRide s1= new OverRide();
s1.access();
}
}

5.9 Final Classes and Methods

5.9.1 Final Classes


You can declare that your class is final; that is, that your class cannot be subclassed. There
are (at least) two reasons why you might want to do this: security reasons and design
reasons.

www.arihantinfo.com
5.9.2 Final Methods
You can use the final keyword in a method declaration to indicate to the compiler that the
method cannot be overridden by subclasses.

5.10 Abstract Classes and Methods

5.10.1 Abstract Classes


Classes, which implement abstract concepts and should not be instantiated, are called
abstract classes. An abstract class is a class that can only be subclassed--it cannot be
instantiated.

5.10.2 Abstract Methods


An abstract class may contain abstract methods, that is, methods with no implementation.
In this way, an abstract class can define a complete programming interface thereby
providing its subclasses with the method declarations for all of the methods necessary to
implement that programming interface.

Example:
//use of abstract class and method
abstract class AbstractClass {
public void printHello() {
System.out.println(“Printing from abstract class”);
}
abstract void printMe();
}

class TestAbstract extends AbstractClass {


public void printMe() {
System.out.println(“Implementing abstract method”);
}
public static void main(String args[]) {
TestAbstract p =new TestAbstract();
p.printHello();
p.printMe();
}
}

Architectural advantage
Abstract classes provide a way to represent objects at a conceptual generic level.

In a graphic library, you can create an abstract class to represent a generic graphic object
and a method for drawing it. This method is then only implemented on the derived classes.

www.arihantinfo.com
www.arihantinfo.com
UNIT 6: PACKAGES AND INTERFACES

6.1Packages
6.1.1 How to create your own packages
6.2Classpath
6.3The meaning of static
6.4Cleanup: Finalization and Garbage collection
6.5Forcing Finalization and Garbage collection
6.6Interfaces
6.6.1 What is an interface
6.6.2 The interface Declaration
6.6.3 Multiple Extension (Inheritance)
6.6.4 Implementing an interface
6.6.5 Using an interface as a type
6.6.6 Interfaces verses abstract classes

6.1 Packages:

A package is a collection of classes and interfaces of similar nature. For example java.io
package contains classes and interfaces for various kinds of input and output. Package
defines a boundary to see how classes and interfaces interact with one another. Therefore it
also acts as a mode of protection. Java language programs automatically import all classes
in the java.lang package. Packages gives us the following advantages :

Advantages:
• It makes classes easier to find and use.

• It avoids naming conflicts.


To import classes from a package, import command is used.

Import java.io.*;
Import pack.subpack.MyClass;
In the first case all public classes in the package java.io are available. In the second case
only class having the name pack.subpack.MyClass is available for use.

6.1.1 How to Create Your Own Packages

The first statement in a java program should be a package statement.

package pack.subpack;
Example :
package graphics;
interface Draggable { . . . }
class Circle { . . . }
class Rectangle { . . . }
The .class files generated must be placed in a directory named graphics
somewhere in your CLASSPATH.
www.arihantinfo.com
6.2 CLASSPATH

A list of directories that indicate where on the file system you've installed
various compiled Java classes and interfaces.

Java searches your CLASSPATH for a directory whose name matches the
package name of which the class is a member.

Note: If you don't specify a package, your classes and interfaces become
members of the default package, which has no name.

6.3 The meaning of static

With the this keyword in mind, you can more fully understand what it means to make a
method static. It means that there is no this for that particular method. You cannot call
non-static methods from inside static methods1 (although the reverse is possible), and you
can call a static method for the class itself, without any object. In fact, that’s primarily what
a static method is for. It’s as if you’re creating the equivalent of a global function (from C).
Except global functions are not permitted in Java, and putting the static method inside a
class allows it access to other static methods and to static fields.

Some people argue that static methods are not object-oriented since they do have the
semantics of a global function; with a static method you don’t send a message to an object,
since there’s no this. This is probably a fair argument, and if you find yourself using a lot of
static methods you should probably rethink your strategy. However, statics are pragmatic
and there are times when you genuinely need them, so whether or not they are “proper
OOP” should be left to the theoreticians. Indeed, even Smalltalk has the equivalent in its
“class methods.”

6.4 Cleanup: Finalization and Garbage collection


Programmers know about the importance of initialization, but often forget the importance of
cleanup. After all, who needs to clean up an int? But with libraries, simply “letting go” of an
object once you’re done with it is not always safe. Of course, Java has the garbage collector
to reclaim the memory of objects that are no longer used. Now consider a very unusual case.
Suppose your object allocates “special” memory without using new. 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. To handle this case, Java provides a method called finalize( ) that
you can define for your class. Here’s how it’s supposed to work. 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 if you choose to use
finalize( ), it gives you the ability to perform some important cleanup at the time of garbage
collection.

The one case in which this is possible occurs if you pass a reference to an object into the
static method. Then, via the reference (which is now effectively this), you can call non-
static methods and access non-static fields. But typically if you want to do something like
this you’ll just make an ordinary, non-static method.
www.arihantinfo.com
This is a potential programming pitfall because some programmers, especially C++
programmers, might initially mistake finalize( ) for the destructor in C++, which is a function
that is always called when an object is destroyed. But it is important to distinguish between
C++ and Java here, because in C++ objects always get destroyed (in a bug-free program),
whereas in Java objects do not always get garbage-collected. Or, put another way:

Garbage collection is not destruction.

If you remember this, you will stay out of trouble. What it means is that if there is some
activity that must be performed before you no longer need an object, you must perform that
activity yourself. Java has no destructor or similar concept, so you must create an ordinary
method to perform this cleanup. For example, suppose in the process of creating your object
it draws itself on the screen. If you don’t explicitly erase its image from the screen, it might
never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if
an object is garbage-collected, the image will first be removed from the screen, but if it isn’t,
the image will remain. So a second point to remember is:
Your objects might not get garbage-collected.

You might find that the storage for an object never gets released because your program
never nears the point of running out of storage. If your program completes and the garbage
collector never gets around to releasing the storage for any of your objects, that storage will
be returned to the operating system en masse as the program exits. This is a good thing,
because garbage collection has some overhead, and if you never do it you never incur that
expense.

What is finalize( ) for?

You might believe at this point that you should not use finalize( ) as a general-purpose
cleanup method. What good is it?
A third point to remember is:

Garbage collection is only about memory.

That is, the sole reason for the existence of the garbage collector is to recover memory that
your program is no longer using. So any activity that is associated with garbage collection,
most notably your finalize( ) method, must also be only about memory and its deallocation.
Does this mean that if your object contains other objects finalize( ) should explicitly release
those objects? Well, no—the garbage collector takes care of the release of all object memory
regardless of how the object is created. It turns out that the need for finalize( ) is limited to
special cases, in which your object can allocate some storage in some way other than
creating an object. But, you might observe, everything in Java is an object so how can this
be?

It would seem that finalize( ) is in place because of the possibility that you’ll do something C-
like by allocating memory using a mechanism other than the normal one in Java. This can
happen primarily through native methods, which are a way to call non-Java code from Java.
(Native methods are discussed in Appendix B.) C and C++ are the only languages currently
supported by native methods, but since they can call subprograms in other languages, you
can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions
might be called to allocate storage, and unless you call free( ) that storage will not be
released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to
call it in a native method inside your finalize( ).
www.arihantinfo.com
After reading this, you probably get the idea that you won’t use finalize( ) much. You’re
correct; it is not the appropriate place for normal cleanup to occur. So where should normal
cleanup be performed?

6.5 Forcing Finalization and Garbage Collection

System.runFinalization(): This method calls the finalize() methods on all


objects that are waiting to be garbage collected.

System.gc(): It asks the garbage collector to run at any time by calling System's gc()
method.
//: c04:Garbage.java

// Demonstration of the garbage

// collector and finalization

class Chair {

static boolean gcrun = false;

static boolean f = false;

static int created = 0;

static int finalized = 0;

int i;

chair() {

i = ++created;

if(created == 47)

System.out.println("Created 47"); }

public void finalize() {

if(!gcrun) {

// The first time finalize() is called:

gcrun = true;

System.out.println(

"Beginning to finalize after " +

created + " Chairs have been created");

if(i == 47) {

www.arihantinfo.com
System.out.println(

"Finalizing Chair #47, " +

"Setting flag to stop Chair creation");

f = true;

finalized++;

if(finalized >= created)

System.out.println(

"All " + finalized + " finalized");

public class Garbage {

public static void main(String[] args) {

// As long as the flag hasn't been set,

// make Chairs and Strings:

while(!Chair.f) {

new Chair();

new String("To take up space");

System.out.println(

"After all Chairs have been created:\n" +

"total created = " + Chair.created +

", total finalized = " + Chair.finalized);

// Optional arguments force garbage

// collection & finalization:

if(args.length > 0) {

if(args[0].equals("gc") ||

args[0].equals("all")) {

System.out.println("gc():");

www.arihantinfo.com
System.gc();

if(args[0].equals("finalize") ||

args[0].equals("all")) {

System.out.println("runFinalization():");

System.runFinalization();

System.out.println("bye!");

} ///:~

The above program creates many Chair objects, and at some point after the garbage
collector begins running, the program stops creating Chairs. Since the garbage collector can
run at any time, you don’t know exactly when it will start up, so there’s a flag called gcrun
to indicate whether the garbage collector has started running yet. A second flag f is a way
for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are
set within finalize( ), which is called during garbage collection.

Two other static variables, created and finalized, keep track of the number of Chairs created
versus the number that get finalized by the garbage collector. Finally, each Chair has its
own (non-static) int i so it can keep track of what number it is. When Chair number 47 is
finalized, the flag is set to true to bring the process of Chair creation to a stop.

All this happens in main( ), in the loop


while(!Chair.f) {
new Chair();
new String("To take up space");
}

You might wonder how this loop could ever finish, since there’s nothing inside the loop that
changes the value of Chair.f. However, the finalize( ) process will, eventually, when it
finalizes number 47.
The creation of a String object during each iteration is simply extra storage being allocated
to encourage the garbage collector to kick in, which it will do when it starts to get nervous
about the amount of memory available.

When you run the program, you provide a command-line argument of “gc,” “finalize,” or
“all.” The “gc” argument will call the System.gc( ) method (to force execution of the garbage
collector). Using the “finalize” argument calls System.runFinalization( ) which—in theory—
will cause any unfinalized objects to be finalized. And “all” causes both methods to be
called.

www.arihantinfo.com
The behavior of this program and the version in the first edition of this book shows that the
whole issue of garbage collection and finalization has been evolving, with much of the
evolution happening behind closed doors. In fact, by the time you read this, the behavior of
the program may have changed once again.

If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily
the case with previous implementations of the JDK, although the documentation claimed
otherwise. In addition, you’ll see that it doesn’t seem to make any difference whether
System.runFinalization( ) is called.

However, you will see that only if System.gc( ) is called after all the objects are created and
discarded will all the finalizers be called. If you do not call System.gc( ), then only some of
the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was
introduced that caused programs to run all the finalizers as they exited, but the design
turned out to be buggy and the method was deprecated. This is yet another clue that the
Java designers were thrashing about trying to solve the garbage collection and finalization
problem. We can only hope that things have been worked out in Java 2.
</#></#TIJ3_CHAPTER4_I66>

The preceding program shows that the promise that finalizers will always be run holds true,
but only if you explicitly force it to happen yourself. If you don’t cause System.gc( ) to be
called, you’ll get an output like this:
Created 47
Beginning to finalize after 3486 Chairs have been created
Finalizing Chair #47, Setting flag to stop Chair creation
After all Chairs have been created:
total created = 3881, total finalized = 2684
bye!

Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called,
it will finalize and destroy all the objects that are no longer in use up to that point.
Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual
Machine (JVM) isn’t close to running out of memory, then it will (wisely) not waste time
recovering memory through garbage collection.

6.6 Interfaces

6.6.1 What is an Interface?

It is a promise that your class will implement certain methods with certain signatures. In
other words an interface is a collection of method definitions (without implementations) and
constant values. You even use the keyword implements to indicate that your class will keep
these promises.

Advantages:
• Capturing similarities between unrelated classes without forcing a class
relationship.

• Declaring methods that one or more classes are expected to implement.

www.arihantinfo.com
• Revealing an object's programming interface without revealing its class (objects
such as these are called anonymous objects and can be useful when shipping a
package of classes to other developers)

Defining an Interface

The interface declaration and the interface body;


interfaceDeclaration {
interfaceBody
}

6.6.2 The interface Declaration:


[public] interface InterfaceName [extends listOfSuperInterfaces]
{
...
}
interface Collection {
int MAXIMUM = 500;
void add(Object obj);
void delete(Object obj);
Object find(Object obj);
int currentCount();
}

6.6.3 Multiple Extensions (Inheritance)


An interface can extend multiple interfaces (while a class can only extend one),
and an interface cannot extend classes.

6.6.4 Implementing an Interface

To use an interface, you write a class that implements the interface.

Definition: To implement an interface a class has to provides a method


implementation for all of the methods declared within the interface.
class FIFOQueue implements Collection {
...
void add(Object obj) { . . . }
...
}

6.6.5 Using an Interface as a Type

An interface is a new reference data type.

You can use interface names anywhere you'd use any other type name:
variable declarations, method parameters and so on:
interface CellAble {
void sdraw();

www.arihantinfo.com
void toString();
void toFloat();
}
class Row {
...

private CellAble[] contents;


...
void setObjectAt(CellAble ca, int index) {
...
}
...
}
Any object that implemented the callable interface can be contained in the
contents array and can be passed into the setObjectAt () method

6.6.6 Interfaces verses abstract classes

While an interface is used to specify the form that something must have, it does not actually
provide the implementation for it. In this sense, an interface is a little like an abstract class
that must be extended in exactly the manner that its abstract methods specify.

• An abstract class is an incomplete class that requires further specialization. An


interface is just a specification or prescription for behavior.

• An interface does not have any overtones of specialization that are presented with
inheritance.

• A class can implement several interfaces at once, whereas a class can extends only
one parent class.

www.arihantinfo.com
UNIT 7: INTRODUCTION TO APPLET PROGRAMMING

7.1What are Applets


7.1.1 What applet can do
7.1.2 What applet can not do
7.2Types of an Applet
1.2.1 Local Applet
1.2.2 Remote Applet
7.3Lifecycle of an Applet
7.4Passing parameters to an Applet

7.1 What are APPLETS ?

An applet is a program written in the Java programming language that can be included in
an HTML page, much in the same way an image is included. When you use a Java
technology-enabled browser to view a page that contains an applet, the applet's code is
transferred to your system and executed by the browser's Java Virtual Machine (JVM). In
other words we can define an applet is a java program that can be embedded in a web page.
Java application is run by using a java interpreter. Applets are run on any browser that
support java. Applets can also be tested using the appletviewer tool included in the java
development kit. In order to run an applet it must be included in a web page, using HTML
tags. When a user browses a web page containing an applet, the browser downloads the
applet from the web server and runs it on the user’s system. Applets have certain
restrictions put on them.

7.1.1 What applets can do

 Applets can make network connections to the host they came from.

 Applets running within a Web browser can easily cause HTML documents to be
displayed.

 Applets can invoke public methods of other applets on the same page.

 Applets that are loaded from the local file system have none of the restrictions that
applets loaded over the network do.

 Although most applets stop running once you leave their page, they don't have to.

7.1.2 What applets can not do

 An applet can't load libraries or define native methods.

 It can't ordinarily read or write files on the host that's executing it.

 It can't make network connections except to the host that it came from.

 It can't start any program on the host that's executing it.


www.arihantinfo.com
 It can't read certain system properties. Windows that an applet brings up look different
than windows that an application brings up.
All applets are subclasses of the Applet class in the java.applet package. Applets do not have
main() method. All applets must be declared public.

7.2 Types of an Applet

Basically, your Web pages can contain two types of applets: local and remote.

7.2.1 Local Applets


A local applet is one that is stored on your own computer system. When your Web page
must find a local applet, it doesn't need to retrieve information from the Internet-in fact,
your browser doesn't even need to be connected to the Internet at that time. As you can see
in example, a local applet is specified by a path name and a file name.

Specifying a Local Applet.


<applet

codebase="tictactoe"

code="TicTacToe.class"

width=120

height=120>

</applet>

In this example the codebase attribute specifies a path name on your system for the local
applet, whereas the code attribute specifies the name of the byte-code file that contains the
applet's code. The path specified in the codebase attribute is relative to the folder containing
the HTML document that references the applet.

www.arihantinfo.com
7.2.2 Remote Applets
A remote applet is one that is located on another computer system. This computer system
may be located in the building next door or it may be on the other side of the world-it makes
no difference to your Java-compatible browser. No matter where the remote applet is
located, it's downloaded onto your computer via the Internet. Your browser must, of course,
be connected to the Internet at the time it needs to display the remote applet.
To reference a remote applet in your Web page, you must know the applet's URL (where it's
located on the Web) and any attributes and parameters that you need to supply in order to
display the applet correctly. If you didn't write the applet, you'll need to find the document
that describes the applet's attributes and parameters. This document is usually written by
the applet's author. Example given below shows how to compose an HTML <applet> tag that
accesses a remote applet.

Specifiying a Remote Applet.


<applet

codebase="http://www.myconnect.com/applets/"

code="TicTacToe.class"

width=120

height=120>

</applet>

The only difference between local and remote is the value of the codebase attribute. In the
first case, codebase specifies a local folder, and in the second case, it specifies the URL at
which the applet is located.

7.3 Lifecycle of an Applet

www.arihantinfo.com
There are 4 important phases in the life cycle of an applet.

1. Initialization occurs when the applet is loaded. This is implemented by the init()
method. To implement a specific initialization process such as setting up initial
state, loading images or fonts, init() method is overridden.
2. An applet is started after it is initialized. Starting can occur if it is in a stopped
state. The method start() can be overridden to implement start operation. An
applet is stopped when the user goes to a different web page and comes back to
the page containing applet. Initialization occurs only once whereas starting occurs
any number of times.
3. stopping occurs when the user leaves the page containing the applet or when an
applet stops itself by calling stop() method.
4. Destruction is done using destroy() method. This method perform cleanup process
when the browser exits.

Begin Born Initialization


(Load Applet)

start()

stop ( )
Running Idle Stopped
start ( )
Display destroy ( )
Paint ( )

Dead
Destroyed End

Exit of Browser

An applet’s state transition diagram

import java.awt.*;
import java.applet.*;
/*
<applet code=”sample” width=300 height=50></applet>
*/
public class Sample extends Applet {
String msg;
//set the foreground and background colors.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
msg=”Inside init() – “;
}
//Initialize the string to be displayed.
www.arihantinfo.com
public void start() {
msg +=”Inside start() –“;
}
//Display msg in applet window.
public void paint(Graphics g) {
msg += “Inside paint() – “;
g.drawString(msg,10,30);
}
public void stop() {
msg=”Inside Stop -- “;
}
public void destroy() {
System.out.println(“Inside Destroy”);
}
}

7.4 Passing parameters to an applet.

The parameters are passed to applets by using the attribute PARAM in the applet tag.
The example below shows passing of parameters.

TestParam.java
import java.awt.*;
import java.applet.Applet;

public class TestParam extends Applet {


Font f = new Font(“Arial”,Font.BOLD,24);
String s;
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.blue);
g.drawstring(s,10,50);
}
public void init() {
s= getParameter(“s”);
if(s==null)
s=”Null value returned”;
}
}

The html code for viewing the applet is shown below.

TestApplet.htm
<html>
<head>
<title>My page</title>
</head>
<body>
<h2>This page shows use of Applet</h2>

www.arihantinfo.com
<p><applet code=”TestParam.class” width=300 height=100>
<param name=s value=”Passing values from HTML”>
</applet>
<hr>
<body></html>

In order to view the applet, an HTML code has to be written. This code contains <applet>
tag. The above code uses the <applet> tag. It has three attributes.
• CODE – Specifies the name of the applet’s main class file.
• WIDTH – Specifies the width of the applet window on the Web Page.
• HEIGHT – Specifies the height of the applet window.
Other attribute that could be added to the applet tag are
• ALIGN – This could be set to LEFT,RIGHT,MIDDLE,TOP
• HSPACE – Controls the horizontal space to the left and right of the applet.
• VSPACE - Controls the vertical space above and below the applet.
• CODEBASE – Indicates an alternate folder or alternate web site for the browser to
locate the applet.
• ALT – Specifies the text to be display if the browser understands the applet tag, but
can’t run Java applets.

The applet can be viewed by typing appletviewer TestApplet.htm at the command prompt.

Adding graphics and colors

import java.awt.*;
import java.applet.*;
public class Face extends Applet
{
public void paint (Graphics g)
{
g.drawOval (40, 40, 120, 150); //Head
g.drawOval (57, 75, 30, 20); //Left eye
g.drawOval (110, 75, 30, 20); //Right eye
g.fillOval (68, 81, 10, 10); //Pupil (left)
g.fillOval (121, 81, 10, 10); //Pupil (right)
g.drawOval (85, 100, 30, 30); //Nose
g.fillArc (60, 125, 80, 40, 180, 180); //Mouth
g.drawOval (25, 92, 15, 30); //Left ear
g.drawOval (160, 92, 15, 30); //Right ear
}
}

import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void paint (Graphics g)
{

g.setColor(Color.blue);
www.arihantinfo.com
g.drawLine (5, 5, 100,100);
g.drawRect (10, 10, 60, 75);
g.fillRect (100, 10, 60, 50);
g.drawRoundRect (190, 10, 60, 50, 15, 15);
g.fillRoundRect (70, 90, 140, 100, 30, 40);
}
}

www.arihantinfo.com
Unit 8
Programming the Abstract Windowing Toolkit (AWT)

8.1Introduction of AWT
8.2AWT Component Hierarchy
8.3How to Add a Component to a Container
8.4AWT Component
8.4.1 Labels
8.4.2 Buttons
8.4.3 Checkbox
8.4.4 TextFields
8.4.5 TextAreas
8.4.6 Choice lists
8.4.7 Scrolling Lists
8.5Event Handling
8.5.1 Introduction
2.5.2 Event Listener Interfaces
8.6How to implement event handlers:
8.6.1 Buttons
8.6.2 Canvases
8.6.3 Checkboxes
8.6.4 Choices
8.6.5 Lists
8.6.6 ScrollPanes
8.6.7 TextComponent
8.6.8 Menus
8.7AWT Containers
8.7.1 Frames
8.7.2 Panels
8.7.3 Dialogs
8.8Layouts
8.8.1 The FlowLayout Class
8.8.2 The BoderLayout Class
8.8.3 The GridLayout Class
8.8.4 The GridBagLayout Class
8.8.5 The CardLayout class
8.8.6 Combining Layouts with Nested Panels
8.9Using Adapters to Handle Events

8.1 Introduction of AWT

The Abstract Windowing Toolkit, also called as AWT is a set of classes, enabling the user to
create a user friendly, graphical user Interface (GUI). It will also facilitate receiving user
input from the mouse and keyboard.

8.2 AWT Component Hierarchy:

www.arihantinfo.com
AWT MenuComponent:

8.3 How to Add a Component to a Container


For any Component object except a Window to display itself onscreen, you must first add it to
a Container object.

The Container class defines three methods for adding components:

• add(Component comp) method simply requires that you specify the component to add.

• add(Component comp, int ind) method lets you add an argument specifying the integer
position at which the component should be added.

• add(String pos, Component comp) method has as first argument a layout manager-dependent
string that specifies the component's position to the layout manager.

The component can be removed by calling the remove method of the Container class.

void remove(Component obj)


The user interface consists of the following three.
• Component – Anything that can be put on the interface. This includes buttons,
check boxes, pop-up menus, text fields.

www.arihantinfo.com
• Containers – This is a component that can contain other components.
• Layout managers – These define how the components will be arrangesd in a
container.

The statement import java.awt.*; imports all the components, containers and layout
managers necessary for designing the user interface.

The AWT supplies the following components.


• Labels
• Buttons
• Checkboxes
• Choice
• Scrollbars
• Text editing

8.4 AWT Components


8.4.1 Labels
Labels display non editable text. To create a label use one of the following.
Label () – creates an empty label.
Label (string) – creates a label with the given string.
Label (string, int) – creates a label with the given string and right, left or center alignment.

8.4.2 Buttons

Clickable buttons can be created from the Button class. You can create a button by using
either of the following.
• Button () – Creates a button without any label. Use setLabel(string) to display a text
on the button.
• Button (string) – Creates a button with the given string as the label.

8.4.3 Checkboxe

They are labeled or unlabeled boxes that can be either checked off or empty. They are used
for selecting some option. Use one of the following to create them.
• Checkbox () – Creates a checkbox without any label.
• Checkbox (string) – Creates a labeled checkbox.

When many checkboxes are there any number of them can be checked or unchecked.
Checkboxes can be organized into groups so that only one of them can be checked at a time.
The following statement creates a checkbox group.

CheckboxGroup mygroup = new CheckboxGroup();


To create a checkbox, belonging to this group, use the following statement.
Checkbox c1 = new Checkbox (“Manipal”, mygroup, true);

This program creates label, checkbox and buttons.

import java.awt.*;
import java.applet.Applet;
www.arihantinfo.com
public class AddUserInterface extends Applet {
Label lb = new Label (“Choose one”, Label.CENTER);
Checkbox c1 = new Checkbox (“Delhi”);
Checkbox c2 = new Checkbox (“Mumbai”);
Button b1 = new Button (“Submit”);
Button b2 = new Button (“Cancel”);
public void init() {
add(lb);add(c1);
add(c2);add(b1);
add(b2);
}

8.4.4 TextFields

Textfield is an editable component. Text field can be created by using one of the following
• TextField () – Creates an empty text field.
• TextField (string) – Creates a text field with the specified string.
• TextField (string, int) – Creates a text field with specified string and specified width.
The TextField class has several useful methods.
• The getText() method returns the text in the field.
• The setText(string) method fills the field with the string.
• The setEditable (Boolean) method decides wheteher the field should be editable or not
depending upon the Boolean value.
• The isEditable () method returns a Boolean value indicating whether the filed is
editable or not.

8.4.5 TextAreas

These are editable text fields having more than one line of input. Use one of following to
create a text area.
• TextArea () – creates an empty text area.
• TextArea (rows, characters) – Creates a text area of rows specified and width to
accommodate the characters specified.
• TextArea (string)
• TextArea (string, rows, characters)

The methods available in case of Text field can also be used here. In addition to that the
following methods could be used.

• The insert(string, charindex) method inserts the indicated string at the position
indicated by the second argument.
• The replace(string, startpos, endpos) method replaces the text between the given
integer positions with the indicated string.
• The example below shows the use of TextField and Text Area.
//applet to show the use of text field and text area
import java.awt.*;
import java.applet.Applet;
public class UseText extends Applet {
Label l1 = new Label(“Enter name”,Label.CENTER);
TextField t1 = new TextField(10);
Label l2 = new Label(“Enter message”,Label.CENTER);
www.arihantinfo.com
TextArea t2 = new TextArea(5,10);
Button b1 = new Button (“Submit”);
public void init() {
add(l1);add(t1);
add(l2);add(t2);
add(b1);add(b2);
}

8.4.6 Choice lists

They are also called as pop up lists. They enable a single item to be chosen from a list of
items. Choice list is created and used as follows:
• Create an object of the class Choice.
• Add items to the list by using the method addItem(item) in the choice class.
• Add the list as you do with any other component using the add(component) method.
The choice class has the following methods available:
• getItem (index) – Returns text of the list item at the index position specified in the
argument.
• getItemCount () – Returns the number of items in the list.
• getSelectedItem () – Returns the index position of the currently selected item.
• getSelectedIndex () – Returns the index position of the currently selected item.
• select (pos) – Selects the item at the indicated index position.
• select (text) – Selects the first in the list with the given text.

8.4.7 Scrolling Lists

These are created from the list class. These are similar to choice lists. But here you can
choose more than one item at a time. Scrolling lists do not pop up. Multiple items are
displayed at the same time. The list is created by choosing one of the following:
• List() – Created an empty scrolling list enabling only one item to be selected at a time.
• List (item, Boolean) – Created a scrolling list with number of items equal to the first
argument. The Boolean argument allows multiple selection is set to true.
• AddItem () – method is used to add item to the list.

The example below shows the use of choice list and scrolling list.
import java.awt.*;
import java.applet.*;
public class UseList extends Applet {
Choice c = new Choice ();
List l = new List (3, true);
Button b1 = new Button(“Submit”);
Button b2 = new Button(“Cancel”);
public void init() {
c.addItem(“Sachin”);
c.addItem(“Lara”);
c.addItem(“Klusner”);
add(l); add(b1);add(b2);
}
}

www.arihantinfo.com
8.5 Event Handling

8.5.1 Introduction
The earlier version of Java, that is, JDK 1.0 used hierarchical event model, but later in JDK
1.1 version, the Java event model is entirely changed to event delegation model.

Basics of Event Handling


When you are working with the programs having GUIs, you have to know how to handle the
events generated by the components. To do this, there are mainly four steps to be followed:
1. Declare and instantiate event sources (or components) such as buttons, menus,
choices etc.
2. Implement an interface to provide the event handler that responds to event source
activity.
3. Register this event handler with the event source.
4. Add the event source to the container like applet, frame, panel etc.

Events
An event is the encapsulation of some user input delivered to the application
asynchronously.
The java.awt.AWTEvent is the root class of all AWT events.
From any AWTEvent you can get the object that was the event source by invoking
getSource() method.
AWTEvent is subclassed as : ActionEvent, WindowEvent, ItemEvent, KeyEvent, MouseEvent,
TextEvent, etc.

8.5.2 Event Listener Interfaces

Event handling is achieved through the use of listener interfaces, defined in the package
java.awt.event. In java we have a number of built in interfaces as listeners for different types
of event handling. The table below lists listener interfaces and the event sources which uses
them.

Interface Events Generated by


ActionListener Button, List, MenuItem, TextField.
AdjustmentListener Scrollbar
ItemListener Checkbox, CheckboxMenuItem, Choice, List.
TextListener TextComponent
ComponentListener Component
ContainerListener Component
FocusListener Container
KeyListener Component
MouseListener Component
MouseMotionListener Component
WindowListener Window
These interfaces declare one or more methods each of which handle a specific event Adapter
classes will be discussed later on .
Listener Interface Adapter Class Methods
ActionListener none actionPerformed

www.arihantinfo.com
AdjustmentListener none AdjustmentValueChanged

componentHidden
componentMoved
ComponentListener ComponentAdapter
componentResized
componentShown

componentAdded
ContainerListener ContainerAdapter
componentRemoved

focusGained
FocusListener FocusAdapter
focusLost
ItemListener none ItemStateChanged

keyPressed
KeyListener KeyAdapter keyReleased
keyTyped

mouseClicked
mouseEntered
MouseListener MouseAdapter mouseExited
mousePressed
mouseReleased

mouseDragged
MouseMotionListener MouseMotionAdapter
mouseMoved
TextListener none TextValueChanged

windowActivated
windowClosed
windowClosing
WindowListener WindowAdapter windowDeactivated
windowDeiconified
windowIconified
windowOpened

8.6 How to implement event handlers:

1. Code declaring that the class implements a listener interface :


public class MyClass implements ActionListener {
2. Code that registers an instance of the event handling class as a listener:
someComponent.addActionListener(instanceOfMyClass);
1. The implementation of the methods in the listener interface:

www.arihantinfo.com
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}

8.6.1 Buttons
The Button class provides a default button implementation. A button is a simple control
that generates an action event when the user clicks it.

Code Example:
b1 = new Button();
b1.setLabel("Disable middle button");
b1.setActionCommand(DISABLE);
b2 = new Button("Middle button");
b3 = new Button("Enable middle button");
b3.setEnabled(false);
b3.setActionCommand(ENABLE);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
String command= e.getActionCommand();
if (command==DISABLE) { //They clicked "Disable middle button"
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
}
if (command == ENABLE) { //They clicked "Enable middle button"
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
8.6.2 Canvases

The Canvas class exists to be subclassed. It does nothing on its own; it merely provides a
way for you to implement a custom Component.

Code Example:
class ImageCanvas extends Canvas {
Container pappy;
www.arihantinfo.com
Image image;
boolean trueSizeKnown = false;
Dimension minSize;

public ImageCanvas(Image image, Container parent, int w, int h) {


if (image == null) {
System.err.println("Canvas got invalid image object!");
return;
}
this.image = image;
pappy = parent;
minSize = new Dimension(w,h);
}

public Dimension getPreferredSize() {


return getMinimumSize();
}

public Dimension getMinimumSize() {


return minSize;
}

public void paint (Graphics g) {


if (image != null) {
if (!trueSizeKnown) {
int width= image.getWidth(this);
int height= image.getHeight(this)
if ((imageWidth > 0) && (imageHeight > 0)) {
trueSizeKnown = true;
// Component-initiated resizing.
minSize = new Dimension(width,height);
setSize(width, height);
pappy.validate();
}
}
g.drawRect(0, 0, minSize.width - 1, minSize.height - 1);
g.drawImage(image, 0, 0, this);
}
}
}

8.6.3 Checkboxes

Checkboxes are two-state buttons that can be either "on" or "off". When the user clicks a
checkbox, the checkbox state changes and it generates an action event.

www.arihantinfo.com
Code Example:
cb1 = new Checkbox(); //Default state is "off" (false).
cb1.setLabel("Checkbox 1");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true); //Set state to "on" (true).
cbg = new CheckboxGroup();
cb4 = new Checkbox("Checkbox 4", cbg, false); //initial state: off (false)
cb5 = new Checkbox("Checkbox 5", cbg, false); //initial state: off
cb6 = new Checkbox("Checkbox 6", cbg, false); //initial state: off

8.6.4 Choices

The Choice class provides a menu-like list of choices, accessed by a distinctive button. The
user presses the button to bring up a "menu", and then chooses one of the items.

Code Example:
choice = new Choice();
choice.addItem("ichi");
choice.addItem("ni");
choice.addItem("san");
choice.addItem("yon");
choice.addItemListener(this);
...

public void itemStateChanged(ItemEvent e) {


setLabelText(choice.getSelectedIndex(),
choice.getSelectedItem());
}

8.6.5 Lists

The List class provides a scrollable area containing selectable text items.

www.arihantinfo.com
Code Example:
//Build lists, which allows multiple selections.
spanish = new List(4, true); //prefer 4 items visible
spanish.add("uno");
...
spanish.add("siete");
spanish.addActionListener(this);
spanish.addItemListener(this);

italian = new List(); //Defaults to none visible, only one selectable


italian.add("uno");
...
italian.add("sette");
italian.addActionListener(this);
italian.addItemListener(this);
...
public void actionPerformed(ActionEvent e) {
List list= (List) e.getSource();
String language = (list == spanish) ? "Spanish" : "Italian";
output.append("Action event occurred on \""
+ list.getSelectedItem() + "\" in "
+ language + ".\n");
}

public void itemStateChanged(ItemEvent e) {


List list= (List) e.getItemSelectable();
String language = (list == spanish) ? "Spanish" : "Italian";

int index = ((Integer)(e.getItem())).intValue();


if (e.getStateChange() == ItemEvent.SELECTED) {
output.append("Select event occurred on item #"
+ index + " (\""
+ list.getItem(index) + "\") in "
+ language + "." + newline);
} else { //the item was deselected
output.append("Deselect event occurred on item #"
+ index + " (\""
+ list.getItem(index) + "\") in "
+ language + "." + newline);
}}
www.arihantinfo.com
8.6.6 ScrollPanes

A ScrollPane manages a single child component, displaying as much of the component as


space permits.

By default, a scroll pane's scrollbars are visible only when they're needed.

Code Example:
ScrollPane sp1 = new ScrollPane();
sp1.add(aComponent);

Scrollbar parameters:
SCROLLBARS_AS_NEEDED
The default value. Show each scrollbar only when it's needed.
SCROLLBARS_ALWAYS
Always show scrollbars.
SCROLLBARS_NEVER
Never show scrollbars. You might use this option if you don't want the user to directly
control what part of the child component is shown.
Example:
ScrollPane sp2 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);

8.6.7 TextComponent

The TextComponent derived classes, TextArea and TextField, display selectable text and,
optionally, allow the user to edit the text.

TextArea and TextField:


www.arihantinfo.com
From TextComponent this classes inherit methods that allow them to set and get the
current selection, enable and disable editing, get the currently selected text (or all the text),
and set the text.

Component
|
TextComponent
|
+--------------+
| |
TextArea TextField

Code Example:
//Where instance variables are defined:
TextField textField;
TextArea textArea;

public void init() {


textField = new TextField(20);
textField.addActionListener(this);
textArea = new TextArea(5, 20);
textArea.setEditable(false);

...//Add the two components to the panel.


}

public void actionPerformed(ActionEvent evt) {


String text = textField.getText();
textArea.append(text + "\n");
textField.selectAll();
}
8.6.8 Menus

The following applet shows many of the menu features you're likely to use

Note:

• Menus can exist only in menu bars, and menu bars can be attached only to windows
(specifically, to Frames).
www.arihantinfo.com
• Classes that provide menu functionality do not inherit from Component, since many
platforms place severe limits on menu capabilities.

MenuComponent subclasses:

MenuItem
Each item in a menu is represented by a MenuItem object.
CheckboxMenuItem
Each menu item that contains a checkbox is represented by a CheckboxMenuItem object.
Menu
Each menu is represented by a Menu object. Menu is a subclass of MenuItem so that you
can create a submenu by adding one menu to another.
Popupmenu
Represents a popup menu.
MenuBar
The MenuBar class represents the platform-dependent notion of a group of menus attached
to a window. MenuBars can not be bound to Panels.

MenuContainer Interface:
To be able to contain a MenuComponent, an object must adhere to the MenuContainer
interface (Frame, Menu, and MenuBar classes do).

Code Example:
public class MenuWindow extends Frame implements ActionListener,
ItemListener {
...
public MenuWindow() {

//Build the menu bar.


mb = new MenuBar();
setMenuBar(mb);

//Build first menu in the menu bar.


m1 = new Menu("Menu 1", true);
mb.add(m1);
mi1_1 = new MenuItem("Menu Item 1_1");
m1.add(mi1_1);
...

//Build help menu.


m5 = new Menu("Menu 5");
mb.add(m5); //just setting the help menu doesn't work; must add it
mb.setHelpMenu(m5);
mi5_1 = new MenuItem("Menu Item 5_1");
www.arihantinfo.com
mi5_1.setShortcut(new MenuShortcut(KeyEvent.VK_5));
m5.add(mi5_1);
...

//Build second menu in the menu bar.


m2 = new Menu("Menu 2");
mb.add(m2);
mi2_1 = new CheckboxMenuItem("Menu Item 2_1");
m2.add(mi2_1);

//Build third menu in the menu bar.


...
//Register as an ActionListener for all menu items.
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
...
//Register as ItemListener on checkbox menu item.
mi2_1.addItemListener(this);
}
...
public void actionPerformed(ActionEvent e) {
output.append("\"" + e.getActionCommand()
+ "\" action detected in menu labeled \""
+ ((MenuItem)(e.getSource())).getLabel() + "\".\n");
}

public void itemStateChanged(ItemEvent e) {


output.append("Item state change detected on item \""
+ e.getItem()
+ "\" (state is "
+ ((e.getStateChange() ==
ItemEvent.SELECTED)?
"selected)."
: "deselected).") + "\n");
}

8.7 AWT Containers

8.7.1 Frames

The Frame class provides windows for applets and applications. Every application needs at least one
Frame

Code Example:
public class MenuWindow extends Frame {
boolean inAnApplet = true;
TextArea output;

public MenuWindow() {
www.arihantinfo.com
//Calls the Frame constructor and adds components to the window
.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
dispose();
} else {
System.exit(0);
}
}
}

...

public static void main(String args[]) {


MenuWindow window = new MenuWindow();
window.inAnApplet = false;
window.setTitle("MenuWindow Application");
window.setSize(450, 200);
window.setVisible(true);
}
}

Other methods provided by Frame:


String getTitle() and void setTitle(String)
Returns or sets (respectively) the title of the frame's window.
Image getIconImage() and void setIconImage(Image)
Returns or sets (respectively) the image displayed when the window is iconified.
MenuBar getMenuBar() and void setMenuBar(MenuBar)
Returns or sets (respectively) the menu bar for this Frame.
void remove(MenuComponent)
Removes the specified menu bar from this Frame.

8.7.2 Panels

The Panel class is a general-purpose Container subclass. You can use it as-is to hold
Components, or you can define a subclass to perform special functionality, such as event
handling for the objects the Panel contains.

Note:

The Applet class is a Panel subclass with special hooks to run in a browser or other applet
viewer.

Code Examples:
Panel p1 = new Panel();
p1.add(new Button("Button 1"));
p1.add(new Button("Button 2"));
p1.add(new Button("Button 3"));
www.arihantinfo.com
A Panel subclass that draws a frame around its contents.

class FramedArea extends Panel {


public FramedArea(CoordinatesDemo controller) {
...//Set the layout manager.
//Add any Components this Panel contains...
}

//Ensure that no Component is placed on top of the frame.


//The inset values were determined by trail and error.
public Insets getInsets() {
return new Insets(4,4,5,5);
}

//Draw the frame at this Panel's edges.


public void paint(Graphics g) {
Dimension d = getSize();
Color bg = getBackground();

g.setColor(bg);
g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
}
}

8.7.3 Dialogs

The AWT provides support for dialogs -- windows that are dependent on other windows --
with the Dialog class. It provides a useful subclass, FileDialog,that provides dialogs to help
the user open and save files.

Code Example:
class SimpleDialog extends Dialog implements ActionListener {
TextField field;
DialogWindow parent;
www.arihantinfo.com
Button setButton;

SimpleDialog(Frame dw, String title) {


super(dw, title, false);
parent = (DialogWindow)dw;

...//Create and add components, such as the set button.

//Initialize this dialog to its preferred size.


pack();
}

public void actionPerformed(ActionEvent event) {


Object source= event.getSource();
if ( (source == setButton)
| (source == field)) {
parent.setText(field.getText());
}
field.selectAll();
setVisible(false);
}
}

// Here's the code that brings up the dialog:

if (dialog == null) {
dialog = new SimpleDialog(this, "A Simple Dialog");
}
dialog.setVisible(true);

8.8 Using Adapters to Handle Events

Most AWT listener interfaces contain more than one method.


For example, the MouseListener interface:

1. mousePressed,

2. mouseReleased,

3. mouseEntered,

4. mouseExited,

5. mouseClicked.

You may want to implement only one or two functions to handle the one or two events of
interest, but the XXXListener interface may specify half a dozen methods. The language
rules are such that you must implement all the methods in an interface even if you just give
them empty bodies. The AWT provides an adapter class for each listener interface with more

www.arihantinfo.com
than one method with null bodies, thus allowing you to override as few methods as you like.
For example, the MouseAdapter class implements the MouseListener interface.
/*
* An example of extending an adapter class instead of
* directly implementing a listener interface.
*/
public class MyClass extends MouseAdapter {
...
someObject.addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
...//Event handler implementation goes here...
}
}

Listener interface Methods in interface


w/ adapter
ActionListener actionPerformed(ActionEvent)
AdjustmentListener AdjustmentValueChanged(
AdjustmentEvent)
ComponentListener componentHidden(ComponentEvent)
ComponentAdapter componentShown(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
ContainerListener componentAdded(ContainerEvent)
ContainerAdapter componentRemoved(ContainerEvent)
FocusListener focusGained(FocusEvent)
FocusAdapter focusLost(FocusEvent)
KeyListener keyPressed(KeyEvent)
KeyAdapter keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseListener mouseClicked(MouseEvent)
MouseAdapter mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
MouseMotionAdapter mouseMoved(MouseEvent)
WindowListener windowOpened(WindowEvent)
WindowAdapter windowClosing(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
ItemListener itemStateChanged(ItemEvent)

www.arihantinfo.com
UNIT 9: JFC AND SWING COMPONENT

9.1Introduction
9.2Difference between AWT and Swing Components
9.3Overview of Jcomponent
9.4All about Controls (JComponents)
9.4.1 JApplet Example
9.4.2 Jframe
9.4.3 Changing the Look and Feel (LAF)
9.4.4 Jlabel
9.4.5 JButton
9.4.6 New Feature in JDK 1.2.2 Only: HTML in Button Label
9.4.7 JtoolTip
9.4.8 JtextField
9.4.9 JcheckBox
9.4.10 Jpanel
9.4.11 JSlider Basics

9.1 Introduction

JFC is short for Java Foundation classes, which encompasses a group of features to help
people build graphical user interfaces (GUIs). The JFC was first announced at the 1997
JavaOne developer conference, and is defined as containing the following features

1. The swing Components: Include everything from buttons to split panes to tables.
2. Pluggable Look & Feel Support: Gives any program that uses Swing components a
potentially wide choice of looks and feels, no matter what platform the program is
running on.
3. Accessibility API: Enables assistive technologies such as screen readers and Braille
displays to get information from the user interface.
4. Java 2D graphics, text, and images in Java applications and applets.
5. Drag and Drop Support (JDK 1.2 only): Provides the ability to drag and drop between
a Java application and a native application.

9.2 Difference between AWT and Swing Components

The biggest difference between the AWT components and Swing components is that the
Swing components are implemented with absolutely no native code. This means that the
Swing components can have more functionality than AWT components, since the Swing
components aren’t restricted to the least common denominator – the features that are
present on every platform. Having no native code also enables the Swing components to be
shipped as an add-on to JDK 1.1, instead of only being part of JDK1.2.

Even the simplest Swing components have capabilities far beyond what the AWT
components offer.
For example:
• Swing buttons and labels can display images instead of or in addition to text.
• You can easily add or change the borders drawn around most Swing components.
www.arihantinfo.com
For example, it’s easy to put a box around the outside of a container or label.
• You can easily change the behavior or appearance of a Swing component by either
invoking methods on it or creating a subclass of it.
• Swing components don’t have to be rectangular. For example, buttons can be round.
• Assistive technologies such as screen readers can easily get information from Swing
components. For example, a tool can easily get the text that’s displayed on a button
or label.

Another interesting Swing feature is that you can specify which look and feel your program’s
GUI uses. One of the standard look-and-feel options is a cross platform look and feel, the
java Look & Feel. By contrast, AWT components always have the look and feel of the native
platform.

Yet another interesting feature is that Swing components with state use models to keep the
state. For example, a JSider uses a BounedRangeModel object to hold its current value and
range of legal values. Models are set up automatically, so you don’t have to deal with them
unless you want to take advantage of the power they can give you.

When you convert AWT programs to Swing, you need to be aware of a few things:
• Programs should not, as a rule, use “heavyweight” components alongside Swing
components (such as Menu and ScrollPane) and all components that inherit from the
AWT Canvas and Panel classes. This restriction exists because when Swing
components (and all other “lightweight” components) overlap with heavyweight
components, the heavyweight component is always drawn on top.
• Swing components aren’t thread safe. If you modify a visible Swing component
invoking its setText method, for example – form anywhere but an event handler, then
you need to take special steps to make the modification execute on the event
dispatching thread. This isn’t an issue for many Swing programs, since component –
modifying code is typically in event handlers.
• The containment hierarchy for any window or applet that contains Swing components
must have a Swing top-level container at the root of the hierarchy. For example, a
main window should be implemented as a Jframe instance instead of as a Frame
instance.
• You don’t add components directly to a top- level container such as a JFrame.
Instead, you add components to a container (called the content pane) that is itself
contained by the JFrame.

9.3 Overview of JComponent


There is an abstract class called JComponent, which is the parent class for most things that
can appear on screen. The basic ingredients of a GUI are all subclasses of the class called
JComponent. JComponent is the super class that holds the common information about an
on-screen control and provides higher level features common to each control, such as:
• Size (preferred, minimize, maximum).
• Double buffering (a technique to make frequently changing components look
smoother with less flickering).
• Support for accessibility and internationalization.
• Tooltips (pop-up help when you linger on a JComponent).
• Support for operating the control with the keyboard instead of the mouse.
• Some help for debugging by slowing component rendering so you can see what’s
happening.
www.arihantinfo.com
• The thickness of any lines or insets around the edge of the Control.

The Swing lightweight controls can be divided up as shown in Table

GUI Category Control Swing Class Name


Basic Controls Button JButton, JCheckBox, JRadioButton
Combo box JComboBox
List JList
Menu JMenu, JMenuBar, JMenuItem
Slider JSlider
Toolbar JToolbar
TextField JTextField, JPasswordField, JTextArea
Uneditable Display Label JLabel
Tooltip JToolTip
Progress bar JProgressBar
Editable Display Table JTable
Text JTextPane, JTextArea, JEditorPane
Tree JTree
Color chooser JColorChooser
File chooser JFileChooser
Space-Saving Scroll pane JScrollPane, JScrollBar
Containers Split pane JSplitPane
Tabbed pane JTabbedPane
Top-Level Frame JFrame
Containers Applet JApplet
Dialog JDialog, JOptionPane
Other Containers Panel JPanel
Internal Frame JInternalFrame
Layered pane JLayeredPane
Root pane JRootPane

9.4 All about Controls (JComponents)

All swing components are the subclasses of the general class JComponent. These classes
are the controls or the building blocks from which you create your GUI. What you do with
all these components in the following:
1. Add them to the content pane of a container (often JFrame or the JApplet) with a call
like:
Container pane = MyJContainter.getContentPane ();
pane.add (myJComponent);
Or, in a single line as:
MyJContainer.getContentPane (). add (myJComponent);
2. Register your event-handler using the addSomeListener() method of the component.
This tells the window system which routine of yours should be called when the user
presses buttons or otherwise makes selections to process the event.

www.arihantinfo.com
Java.lang.Object

Java.awt.Compon
ent

Java.awt.Containe
r

Javax.swing.JCompone
nt JMenuItem JMenu
(abstract)

AbstractButton JToggleButto JRadioButto


(abstract) n n

JButton JCheckBox

Javax.swing. JEditorPane
JtextComponent
(abstact) JTextField

JLabel
JTextArea

JPanel

JToolTip

JOptionPane

JScrollPane

How to Display Components

Containers are the objects that are displayed directly on the screen. Controls must be added
to a container if you want to see them. The container in this example driver program is
called JFrame. JFrame will be the main window of most of your swing applications. Lets
create a JFrame, set its size, set it visible, tell it how to arrange JComponents that are
added, and add some event-handler code to exit the program when it detects that you have

www.arihantinfo.com
clicked on the JFrame to close it. We’ll split them off into a separate method. Make
everything static. In this way, we can use it from the main() method, and we get the
following.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class demo {
static JFrame jframe = new JFrame (“example”);
public static void setupJFrame() {
jframe.setSize (400,100);
jframe.setVisible (true);
jframe.getContentPane ().setLayout (new FlowLayout ());
WindowListener l = new WindowAdapter () {
public void windowClosing (WindowEvent e) {
System.exit (0);}
};
jframe.addWindowListener (l);
}

public static void main(String[] args) {


setupJFrame ();
Jbutton jb = new Jbutton(“Press Me”);
Jframe.getContentPane ().add(jb);
}}

The JButton Component that we are trying to demonstrate is printed in bold type. The line
that follows add the JComponents to the JFrame’s content pane. To cut down on the
extraneous codes in the pages ahead, I’ll show only the statement directly deal with
JComponent. That means I’ll show only the two bold statements in the example above. You
should supply all the missing code when you compile and run the examples.

9.4.1 JApplet Example


This simple example shows the steps required to get what you would have in the AWT if you
had a simple applet whose init method did nothing but drop three buttons into the window.

Most usage is the same as with Applet

• JApplet inherits from Applet

• init, start, stop, etc. unchanged

Main differences in use

 Components go in the "content pane", not directly in the frame. Changing other
properties (layout manager, background color, etc.) also apply to the content pane.
Access content pane via getContentPane, or if you want to replace it with your
container (e.g. a JPanel), use setContentPane.

www.arihantinfo.com
 Default layout manager is BorderLayout (like Frame and JFrame), not FlowLayout (like
Applet). This is really the layout manager of the content pane.

 You get Java (Metal) look by default, so you have to explicitly switch if you want
native look.

 Do drawing in paintComponent, not paint.

 Double buffering turned on by default.

JAppletExample.java
import java.awt.*;
import javax.swing.*;

public class JAppletExample extends JApplet {


public void init() {
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}
JApplet Example: Result

9.4.2 JFrame
Main differences in use compared to Frame:

 Components go in the "content pane", not directly in the frame. Changing other
properties (layout manager, background color, etc.) also apply to the content pane.
Access content pane via getContentPane, or if you want to replace the content pane
with your container (e.g. a JPanel), use setContentPane.

www.arihantinfo.com
 JFrames close automatically when you click on the close button (unlike AWT Frames).
However, closing the last JFrame does not result in your program exiting Java. So
your "main" JFrame still needs a WindowListener.

 You get Java (Metal) look by default, so you have to explicitly switch if you want
native look.

JFrame Example:
This shows the steps required to imitate what you would get in the AWT if you popped up a
simple Frame, set the layout manager to FlowLayout, and dropped three buttons into it.
JFrameExample.java
import java.awt.*;
import javax.swing.*;

public class JFrameExample {


public static void main(String[] args) {
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
f.addWindowListener(new ExitListener());
f.setVisible(true);
}
}
ExitListener.java
import java.awt.*;
import java.awt.event.*;

public class ExitListener extends WindowAdapter {


public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
JFrame Example: Result

www.arihantinfo.com
9.4.3 Changing the Look and Feel (LAF)
1. Default is "Java LAF" (or "Metal"), a custom look and feel similar to the Windows look.

2. Motif look available on all platforms. Windows and Mac looks are only available on their
native platforms.

 It is technically easy to work around this restriction, but it is not currently legal to
distribute/use applications that do this.

3. You can change look at runtime.

 Sounds cool, but rarely used in real life.

 Normal place to set look is in constructor of top-level JFrame (or main), or in init in a
JApplet.

4. You can get AWT behavior of using native look.

 Call the getSystemLookAndFeelClassName method of UIManager, and pass result to


UIManager.setLookAndFeel.

 Since setLookAndFeel throws an exception, this is a bit inconvenient, and you might
want to make a static method in a utility class called " setNativeLookAndFeel". See
example below in WindowUtilities.java.

5. Changing the Look and Feel: Examples


Here are some utility functions that set the LAF to native, Java (Metal), and Motif,
respectively. Since I think that most users will expect the native LAF, I almost always call
setNativeLookAndFeel at the beginning of Swing programs.

WindowUtilities.java
import javax.swing.*;
import java.awt.*;

class ExitListener extends WindowAdapter {


public void windowClosing(WindowEvent event) {
System.exit(0);
}
}

/** A few utilities that simplify using windows in Swing.


* 1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
*/

public class WindowUtilities {

/** Tell system to use native look and feel, as in previous


* releases. Metal (Java) LAF is the default otherwise.
*/

www.arihantinfo.com
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}

public static void setJavaLookAndFeel() {


try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}

public static void setMotifLookAndFeel() {


try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}

/** A simplified way to see a JPanel or other Container.


* Pops up a JFrame with specified Container as the content pane.
*/

public static JFrame openInJFrame(Container content,


int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new ExitListener());
frame.setVisible(true);
return(frame);
}

/** Uses Color.white as the background color. */

public static JFrame openInJFrame(Container content,


int width,
int height,
String title) {
return(openInJFrame(content, width, height, title, Color.white));
}

www.arihantinfo.com
/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/

public static JFrame openInJFrame(Container content,


int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
}

In order to implement this Look and Feel example what you have to do is to include a single
line in your previous examples after creating this WindowUtility and ExitListener classes as
given below.

JAppletExample.java
import java.awt.*;
import javax.swing.*;
public class JAppletExample extends JApplet {
public void init() {
WindowUtilities.setNativeLookAndFeel();
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}

JFrameExample.java
import java.awt.*;
import javax.swing.*;

public class JFrameExample {


public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
f.addWindowListener(new ExitListener());
f.setVisible(true);
www.arihantinfo.com
}
}

9.4.4 JLabel

JLabel is the simplest JComponent. It is just a string, image, or both that appears on
screen. The contents can be left-, right-, or center aligned according to an argument to the
constructor. The default is left aligned. JLabel is cheap, fast way to get a picture or text on
the screen.

The code to create it:


// remember, we are only showing relevant statements from main ()
ImageIcon icon = new ImageIcon(“star.gif”);
JLabel j1 = new JLabel(“you are a star”, icon, JLabel.Center);
Frame.getContentPane ().add (j1);
Frame.pack (); //size the JFrame to fit its contents.
Note the way we can bring in an image from a GIF or JPEG file by constructing an
ImageIcon with a pathname to a file. Labels do not generate any events in and of
themselves. It is possible, however, to get and set the text of a label. You might do that in
response to an event from a different component. The constructors for JLabel are :

public javax.swing. JLabel (java.lang.String);


public javax.swing. JLabel (java.lang.String,int);
public javax.swing. JLabel (java.lang.String,javax.swing.Icon,int);
public javax.swing. JLabel (javax.swing.Icon);
public javax.swing. JLabel (javax.swing.Icon,int);

The int parameter is a constant from the JLabel class specifying left-, right-, or center-
alignment in the area where the label is displayed.

JLabels are typically used to augment other controls with descriptions or instructions.

A JLabel has three major features that Label does not.


The first is the ability to display images, usually by supplying an ImageIcon eiher to the
constructor or via a call to setIcon.

The second new feature is the ability to place borders around the labels.

The third new feature, and the one I am focusing on here, is the ability to use HTML to
format the label. The idea is that, if the string for the label begins with "<html>", then the
string is interpreted as HTML rather than taken literally. This lets you make multi-line
labels, labels with mixed colors and fonts, and various other fancy effects. This capability
also applies to JButton. Although nice, this capabillity also has several significant
limitations:

• It only works in JDK 1.2.2 or later, or in Swing 1.1.1 or later. Since there is no
programmatic way to test if this capability is supported, this can cause significant
portability problems.

www.arihantinfo.com
• Label string must begin with "<html>", not "<HTML>". This is no problem once you
know, but if you are unaware this can cause no end of frustration. Sun has promised
to fix this in JDK 1.3 (Kestrel).

• Embedded images are not supported in the HTML. Thus, you have to use setIcon or
supply an ImageIcon to the JLabel constructor (as with the third label in the example
shown above); the HTML cannot have an IMG tag.

• JLabel fonts are ignored if HTML is used. If you use HTML, all font control must be
performed via the HTML. For example, one would think that the following would
result in large, bold Serif text, but it results in small bold SansSerif text instead:
• JLabel label = new JLabel("<html>Bold Text");
• label.setFont(new Font("Serif", Font.PLAIN, 36));
...
Sun says that this will probably not be fixed until after the first release of JDK 1.3.

• You must use <P>, not <BR> to force a line break. <BR> is totally ignored, and <P> in
a JLabel or JButton works like <BR> does in "real" HTML, starting a new line but not
leaving a blank line in between.

• Other HTML support is spotty. Be sure to test each HTML construct you use. Letting
the user enter HTML text at run-time is asking for trouble.

JLabels with HTML: Example

import java.awt.*;
import javax.swing.*;

/** Simple example illustrating the use of JLabel, especially


* the ability to use HTML text (Swing 1.1.1 and Java 1.2 and
* later only!).
* 1999 Marty Hall, http://www.apl.jhu.edu/~hall/java/
*/

public class JLabels extends JFrame {


public static void main(String[] args) {
new JLabels();
}

public JLabels() {
super("Using HTML in JLabels");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
Font font = new Font("Serif", Font.PLAIN, 30);
content.setFont(font);
String labelText =
"<html><FONT COLOR=RED>Red</FONT> and " +
"<FONT COLOR=BLUE>Blue</FONT> Text</html>";
JLabel coloredLabel =

www.arihantinfo.com
new JLabel(labelText, JLabel.CENTER);
coloredLabel.setBorder
(BorderFactory.createTitledBorder("Mixed Colors"));
content.add(coloredLabel, BorderLayout.NORTH);
labelText =
"<html><B>Bold</B> and <I>Italic</I> Text</html>";
JLabel boldLabel =
new JLabel(labelText, JLabel.CENTER);
boldLabel.setBorder
(BorderFactory.createTitledBorder("Mixed Fonts"));
content.add(boldLabel, BorderLayout.CENTER);
labelText =
"<html>The Applied Physics Laboratory is a division " +
"of the Johns Hopkins University." +
"<P>" +
"Major JHU divisions include:" +
"<UL>" +
" <LI>The Applied Physics Laboratory" +
" <LI>The Krieger School of Arts and Sciences" +
" <LI>The Whiting School of Engineering" +
" <LI>The School of Medicine" +
" <LI>The School of Public Health" +
" <LI>The School of Nursing" +
" <LI>The Peabody Institute" +
" <LI>The Nitze School of Advanced International Studies" +
"</UL>";
JLabel fancyLabel =
new JLabel(labelText,
new ImageIcon("images/JHUAPL.gif"),
JLabel.CENTER);
fancyLabel.setBorder
(BorderFactory.createTitledBorder("Multi-line HTML"));
content.add(fancyLabel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}

Note: also requires WindowUtilities.java and ExitListener.java, shown earlier, plus


JHUAPL.gif.

9.4.5 JButton

Simple uses of JButton are very similar to Button. You create a JButton with a String as a
label, and then drop it in a window. Events are normally handled just as with a Button: you
attach an ActionListener via the addActionListener method.
The code to create it:
JButton jb = new JButton (“Press Me”);
JFrame.getContentPane ().add(jb);
The code to handle events from it:

www.arihantinfo.com
jb.addActionListener ( new ActionListener () {
int i =1;
public void actionPerfomed(ActionEvent e)
{ System.out.println (“pressed “ + i++);}
});
When you press this button, the event handler will print out the number of times it has
been passed.

New Features: Icons, Alignment, and Mnemonics


The most obvious new feature is the ability to associate images with buttons. Swing
introduced a utility class called ImageIcon that lets you very easily specify an image file (jpeg
or GIF, including animated GIFs). Many Swing controls allow the inclusion of icons. The
simplest way to associate an image with a JButton is to pass the ImageIcon to the
constructor, either in place of the text or in addition to it. However, a JButton actually
allows seven associated images:
1. the main image (use setIcon to specify it if not supplied in the constructor),

2. the image to use when the button is pressed (setPressedIcon),

3. the image to use when the mouse is over it (setRolloverIcon, but you need to call
setRolloverEnabled(true) first),

4. the image to use when the button is selected and enabled (setSelectedIcon),

5. the image to use when the button is disabled (setDisabledIcon),

6. the image to use when it is selected but disabled (setDisabledSelectedIcon), and

7. the image to use when the mouse is over it while it is selected


(setRolloverSelectedIcon).

You can also change the alignment of the text or icon in the button (setHorizontalAlignment
and setVerticalAlignment; only valid if button is larger than preferred size), and change
where the text is relative to the icon (setHorizontalTextPosition, setVerticalTextPosition).
You can easily create buttons with images as well, like this:
Icon spIcon = new ImageIcon (“spam.jpg”);
JButton jb = new JButton (“press here for spam”, splcon);
You can add a keyboard accelerator to a button, and you can give it a symbolic for the text
string that it displays. This helps with internationalizing the code.
You can also easily set keyboard mnemonics via setMnemonic. This results in the specified
character being underlined on the button, and also results in ALT-char activating the
button.

9.4.6 New Feature in JDK 1.2.2


In JDK 1.2.2 and Swing 1.1.1 (and later), Sun added the ability to use HTML to describe the text in
JButtons and JLabels. This lets you easily have multi-line labels, mixed fonts and colors, and other
fancy features.

www.arihantinfo.com
JButton Example: Source Code
Here is an example of four similar buttons: one with plain text, one with just an image, one
with both and the default layout (image to the left, text to the right), and one with the image
and text positions reversed.
JButtons.java
import java.awt.*;
import javax.swing.*;

public class JButtons extends JFrame {


public static void main(String[] args) {
new JButtons();
}

public JButtons() {
super("Using JButton");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}
Note: also requires WindowUtilities.java and ExitListener.java, shown earlier, plus cup.gif.

JButton Example: Result

www.arihantinfo.com
9.4.7 JToolTip

This is a text string that acts as a hint or further explanation. You can set it for any
JComponent. It appears automatically when the mouse lingers on that component and it
disappears when you roll mouse away.

ToolTips don’t generate any events, so there is nothing to handle.


We’ll add a ToolTip to the JLabel that we showed earlier.

The code to create it:


JLabel j1 = new JLabel (“You are a star”, icon, JLabel.Center);
jl.setToolTipText (“you must practice to be a star!”);
Notice that you don’t directly create a JToolTip object. That is done for you behind the
scenes. You invoke the set ToolTipText () method of JComponent.

9.4.8 JTextField

This is an area of the screen where you can enter a line of text. There are a couple of
subclasses : JTextArea (several lines in size) and JPasswordField (which doesn’t echo what
you type in). you can set it to be editable or not-editable.

The Code to create it:


JLabel jl = new JLabel (“Enter your name : ”);
JTextField jtf = new JTextField (25); //field is 25 chars wide
The code to retrieve user input from it:
TextFields generate key events on each keystroke and an ActionEvent when the user presses
a carriage return. This makes it convenient to validate individual keystrokes as they are
typed (as in, ensuring that a field is wholly numeric) and to retrieve all the text when the
user has finished typing. The code to get the text look like this :
jft.addActionListener ( new ActionListener ()) {
public void actionPerformed (ActionEvent e)
{ System.out.println ( “you entered:” +e.getActionCommand () );}
});
Container c = jframe.getContentPane();
c.add(jl);
c.add(jtf);
In this example, running the program, typing a name, and hitting carriage return will cause
the name to be echoed on the Sytem.out. You should write some code to try implementing a
listener for each keystroke.

9.4.9 JCheckBox

A CheckBox screen object that represents a Boolean choice: pressed, not pressed, on, or off.
Usually some text explains the choice. For example, a “press for fries” JLabel would have a
JCheckBox “Button” allowing yes or no. You can also add an icon to the JCheckBox, just
the way you can with JButton.

The code to create it


JCheckBox jck1 = new JCheckBox (“Kannada”);
JCheckBox jck2 = new JCheckBox (“Tamil”);
JCheckBox jck3 = new JCheckBox (“Telugu”);
www.arihantinfo.com
JCheckBox jck4 = new JCheckBox (“Malayalam”);
Container c = jframe.getContentPane ();
c.add (jck1); c.add(jck2); //etc.
….
The code to retrieve user input from it
CheckBox generates bot ActionEvent and ItemEvent every time you change it. This seems to
be for backword compatibility with AWT. We already saw the code to handle ActionEvents
with button. The code to register an ItemListener looks like this.

Jck2.addItemListener (new ItemListener ()


{ // anonymous class
public void itemStateChanged (itemEvent e) {
if(e.getStateChange () == e.SELECTED)
System.out.print(“selected”);
else System.out.print (“de-selected”);
System.out.print(“Kannada \n”);
}
});

In this example, running the program and clicking the “Kannada” checkbox will cause the
output of selected Kannada in the system console.

Handlers in real programs will do more useful actions as necessary like assigning values
and creating objects. The ItemEvent contains fields and methods that specify which objects
generated the event and whether it was selected or deselected.

9.4.10 JPanel
1. JPanel Basics
In the simplest case, you use a JPanel exactly the same way as you would a Panel. Allocate
it, drop components in it, then add the JPanel to some Container. However, JPanel also acts
as a replacement for Canvas (Everyone expects there to be a Jcanvas replacing Canvas, just
as Jbutton replace Button, JFrame replaces Frame, and so on. There is no Jcanvas. The
swing version of Panel, Jpanel, does double duty. It replaces both Canvas and
Panel.). When using JPanel as a drawing area in lieu of a Canvas, there are two additional
steps you usually need to follow. First, you should set the preferred size via
setPreferredSize (recall that a Canvas' preferred size is just its current size, while a Panel
and JPanel determine their preferred size from the components they contain). Secondly, you
should use paintComponent for drawing, not paint. And since double-buffering is turned on
by default, the first thing you normally do in paintComponent is clear the off-screen bitmap
via super.paintComponent. E.g.:
public void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
Note that if you are using Swing in Java 1.2, you can cast the Graphics object to a
Graphics2D object and do all sorts of new stuff added in the Java2D package.
New Features: Borders
Aside from double buffering, the most obvious new feature is the ability to assign borders to
JPanels. Swing gives you seven basic border types: titled, etched, beveled (regular plus a
"softer" version), line, matte, compound, and empty. You can also create your own, of
www.arihantinfo.com
course. You assign a Border via the setBorder method, and create the Border either by
calling the constructors directly, or more often by using one of the following convenience
methods in BorderFactory: createTitledBorder, createEtchedBorder, createBevelBorder,
createRaisedBevelBorder, createLoweredBevelBorder, createLineBorder, createMatteBorder,
createCompoundBorder, and createEmptyBorder. These factory methods reuse existing
Border objects whenever possible.
As a convenience, JPanel lets you supply the LayoutManager to the constructor in addition to
specifying it later via setLayout as with Panel.

JPanel Example:
The following example allocates four bordered panels, set up to look like a simple drawing
program. The large one at the left uses a LineBorder, while the other three use
TitledBorder.
JPanels.java
import java.awt.*;
import javax.swing.*;

public class JPanels extends JFrame {


public static void main(String[] args) {
new JPanels();
}

public JPanels() {
super("Using JPanels with Borders");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.lightGray);
JPanel controlArea = new JPanel(new GridLayout(3, 1));
String[] colors = { "Red", "Green", "Blue",
"Black", "White", "Gray" };
controlArea.add(new SixChoicePanel("Color", colors));
String[] thicknesses = { "1", "2", "3", "4", "5", "6" };
controlArea.add(new SixChoicePanel("Line Thickness",
thicknesses));
String[] fontSizes = { "10", "12", "14", "18", "24", "36" };
controlArea.add(new SixChoicePanel("Font Size",
fontSizes));
content.add(controlArea, BorderLayout.EAST);
JPanel drawingArea = new JPanel();
// Preferred height is irrelevant, since using WEST region
drawingArea.setPreferredSize(new Dimension(400, 0));
drawingArea.setBorder(BorderFactory.createLineBorder (Color.blue, 2));
drawingArea.setBackground(Color.white);
content.add(drawingArea, BorderLayout.WEST);
pack();
setVisible(true);
}
}
Note: also requires WindowUtilities.java and ExitListener.java, shown earlier.
www.arihantinfo.com
SixChoicePanel.java
import java.awt.*;
import javax.swing.*;

public class SixChoicePanel extends JPanel {


public SixChoicePanel(String title, String[] buttonLabels) {
super(new GridLayout(3, 2));
setBackground(Color.lightGray);
setBorder(BorderFactory.createTitledBorder(title));
ButtonGroup group = new ButtonGroup();
JRadioButton option;
int halfLength = buttonLabels.length/2; // Assumes even length
for(int i=0; i<halfLength; i++) {
option = new JRadioButton(buttonLabels[i]);
group.add(option);
add(option);
option = new JRadioButton(buttonLabels[i+halfLength]);
group.add(option);
add(option);
}
}
}

JPanel Example: Result

9.4.11 JSlider Basics

www.arihantinfo.com
In the AWT, the Scrollbar class played double duty as a control for interactively selecting
numeric values and a widget used to control scrolling. This was inconvenient, and resulted
in poor looking sliders. Swing gives you a "real" slider: JSlider. You create a JSlider in a
similar manner to Scrollbar: the zero-argument constructor creates a horizontal slider with
a range from 0 to 100 and an initial value of 50. You can also supply the orientation (via
JSlider.HORIZONTAL or JSlider.VERTICAL) and the range and initial value to the constructor.
You handle events by attaching a ChangeListener. Its stateChanged method normally calls
getValue to look up the current JSlider value.
New Features: Tick Marks and Labels
Swing sliders can have major and minor tick marks. Turn them on via
setPaintTicks(true), then specify the tick spacing via setMajorTickSpacing and
setMinorTickSpacing. If you want users to only be able to choose values that are at the tick
marks, call setSnapToTicks(true). Turn on labels via setPaintLabels(true). This draws
labels for the major tick marks. You can also specify arbitrary labels (including ImageIcons
or other components) by creating a Dictionary with Integers as keys and Components as
values, then associating that with the slider via setLabelTable.
Other capabilities include: borders (as with all JComponents), sliders that go from high to
low instead of low to high (setInverted(true)), and the ability to determine that you are in the
middle of a drag (when getValueIsAdjusting() returns true) so that you can postpone action
until the drag finishes.

JSlider Example:
Following are three simple sliders. The first is a plain one, the second has tick marks, and
the third has both tick marks and labels.
JSliders.java
import java.awt.*;
import javax.swing.*;

public class JSliders extends JFrame {


public static void main(String[] args) {
new JSliders();
}

public JSliders() {
super("Using JSlider");
// Comment out next line for Java LAF
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);

JSlider slider1 = new JSlider();


slider1.setBorder(BorderFactory.createTitledBorder("JSlider without Tick Marks"));
content.add(slider1, BorderLayout.NORTH);

JSlider slider2 = new JSlider();


slider2.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks"));
slider2.setMajorTickSpacing(20);
slider2.setMinorTickSpacing(5);
www.arihantinfo.com
slider2.setPaintTicks(true);
content.add(slider2, BorderLayout.CENTER);

JSlider slider3 = new JSlider();


slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels"));
slider3.setMajorTickSpacing(20);
slider3.setMinorTickSpacing(5);
slider3.setPaintTicks(true);
slider3.setPaintLabels(true);
content.add(slider3, BorderLayout.SOUTH);

pack();
setVisible(true);
}
}
Note: also requires WindowUtilities.java and ExitListener.java, shown earlier.

4. JSlider Result: Windows LAF

5. JSlider Result: Java (Metal) LAF

www.arihantinfo.com
UNIT 10 : JAVA STREAMS

10.1What is Stream
10.2Byte Stream
10.2.1 File Stream
10.2.2 Data Stream
10.3 Character Streams
10.3.1 Text Reading Text Files
10.3.2 Writing Files

10.1 What is Stream?

A stream is a path traveled by data in a program. To bring in information, a program opens


a stream on an information source (a file, memory, a socket) and reads the information
serially, like this:

stream reads
Source Program

similarly, a program can send information to an external destination by opening a stream to


a destination and writing the information out serially, like this:

writes stream
Program Destination

the java.io package contains a collection of stream classes for doing this. These classes are
divided into two class hierarchies based on the data type on which they operate. They are
byte streams and character streams.

A stream is a flowing sequence of characters.

o A program can get input by reading characters from a stream attached to a


source.

o A program can produce output by writing characters to a stream attached to a


destination.

o Input and output sources can be anything that can contain data: a file, a
string, or memory

Predefined Streams

There are three predefined streams already open and ready to use in every
program. These stream are declared in the java.lang.System class, and they
are all byte streams.
www.arihantinfo.com
o standard input: InputStream System.in.

o standard output: PrintStream System.out.

o standard error: PrintStream System.err.

Using Standard Stream

Accepting input through keyboard:

The program shown below demonstrate the use of standard input and output stream for
reading data from the standard input device (keyboard) and displaying that at the standard
output device (monitor screen).

import java.io.*;

class StdInput{

public static void main(String args[]){

byte name = new byte[10];

System.out.println(“what is your name”);

try{

System.in.read(name);

System.out.write(“hello Mr.”+name);

catch(IOException e){

System.out.println(“IO Error”);

10.2 Byte Stream

Figure below shows the class hierarchies for the byte streams.

www.arihantinfo.com
OutputStream Class

These streams are typically used to read and write binary data such as images and sounds.

Simple Input and Output Streams

FileInputStream and FileOutputStream


Read data from or write data to a file on the native file system.

PipedInputStream and PipedOutputStream


Implement the input and output components of a pipe.

ByteArrayInputStream and ByteArrayOutputStream


Read data from or write data to a byte array in memory.

SequenceInputStream
Concatenate multiple input streams into one input stream.

StringBufferInputStream
Allow programs to read from a StringBuffer as if it were an input stream.

www.arihantinfo.com
10.2.1 File Streams

File Input Stream


A file input stream can be created with the FileInputStream(String) constructor. The string
argument should be the name of the file. After you create a file input stream, you can read
bytes from the stream by calling its read() method. This method returns an integer
containing the next byte in the stream. If the method returns –1, it signifies that the end of
the file stream has been reached.

File Output Stream


A file output stream can be created with the FileOutputStream(String) constructor. The
usage is the same as the FileInputStream(String) constructor. You have to be careful when
specifying the file to which to write an output stream. If it’s the same as an existing file, the
original will be wiped out when you start writing data to the stream.

You can create a file output stream that appends data after the end of an existing file with
the FileOutputStream(String,boolean) constructor. The string specifies the file and the
Boolean argument should equal true to append data instead of overwriting any existing
data.

The file output stream’s write(int) method is used to write bytes to the stream. After the last
byte has been written to the file, the stream’s close() method closes the stream.

import java.io.*;
public class ReadWriteBytes {
public static void main(String arg[]){
try {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
while ((c = fis.read()) != -1) {
fos.write(c);
System.out.println(“”+(char)c);}
}catch(IOException e){
System.err.println(“Error – “+e.toString());
fis.close();
fos.close();}}

10.2.2 Data Streams

Data Input Stream and Data Output Stream


If you need to work with data that is not represented as bytes or characters, you can use
data input and data output streams. These streams filter an existing byte stream so that

www.arihantinfo.com
each of the following primitive types can be read or written directly from the stream:
boolean, byte, double, float, int ,long and short.

A data input stream is created with the DataInputStream(InputStream) constructor. The


argument should be an existing input stream such as a buffered input stream or a file
input stream. Conversely, a data input stream requires the DataOutputStream
(OutputStream), which indicates the associated output stream.

The following list indicates the read and write methods that apply to data input and output
streams, respectively:
• readBoolean(), writeBoolean(boolean)
• readByte(),writeByte(int)
• readDouble(), writeDouble(double)
• readFloat(), writeFloat(float)
• readInt(), writeInt(int)
• readLong(), writeLong(long)
• readShort(), writeShort(int)

Each of the input methods returns the primitive data type indicated by the name of the
method. For example, the readFloat() method returns a float value.

In the example below, a data output stream is created with the constructor
DataOutputStream(file), whereas file is the file output stream connected to the file odd.dat.
Using the writeInt method, we write first 50 odd numbers to the file odd.dat. Since this file
is again a binary file, we cannot read this directly in a Notepad.

The example below shows the use of data output stream.

import java.io.*;
public class DOSOdd {
public static void main(String arg[]) {
try {
FileOutputStream file = new FileOutputStream(“odd.dat”);
DataOutputStream data = new DataOutputStream(file);
for(int i=0;i<50;i++) {
data.writeInt(i * 2);
data.close();}
catch(IOException e) {
System.out.println(“Error – “+e.toString());
}}}
The example below shows the use of data input stream.

import java.io.*;
public class DISOdd{
public static void main(String args[]){
try{
FileInputStream file = new FileInputStream(“odd.dat”);
DataInputStream data = new DataInputStream(file);
try{
while(true){
int in = data.readInt();
www.arihantinfo.com
System.out.print(in+””);}}
catch(EOFException eof) {
data.close();}
catch(IOException e) {
System.out.println(“Error – “+e.toString()); }}}

10.3 Character Streams


Character streams are used to work with any text that is represented by the ASCII character
set or Unicode. Examples of files you can work with through a character stream are plain
text files, HTML documents, and java source files. The classes used to read and write these
streams are all subclasses of Reader and Writer. These should be used for all text input
instead of dealing directly with byte streams.

10.3.1 Reading Text Files

FileReader Stream
FileReader is the main class used reading character streams from a file. This class inherits
from InputStreamReader, which reads a byte stream and converts the byte into interger
values that represent Unicode characters.

In the example given below, the FileReader character stream is nested with the
BufferedReader stream because, with character stream you only can read one character at a
time. but with buffered reader you can read a line of text at a time using its readLine()
method.

The example below reads its own source code and display it.
import java.io.*;
public class ReadSource{
public static void main(String arg[]){
try {
FileReader file =new FileReader(“ReadSource.java”);
BufferedReader buff=new BufferedReader(file);
boolean eof=false;
while(!eof)
String line=buff.readLine();
If(line = = null)
eof = true;
else
System.out.println(line);
}
catch(IOException e) {
System.out.println(“IO Error”);
}
}
}

10.3.2 Writing Text File

FileWriter Stream

www.arihantinfo.com
The FileWriter class is used to write a character stream to a file. It’s a subclass of
OutputStreamWriter, which has behavior to convert Unicode character codes to bytes.

There are two FileWriter constructors


FileWriter(String) and FileWriter(String,boolean).
The String indicates the name of the file that the character stream will be directed into,
which can include a folder path. The optional boolean argument should equal true if the file
is to be appended to an existing text file.

The following example copies data from one file to another file

import java.io.*;
public class Copy{
public static void main(String[] args) throws IOException {
File inputFile = new File(“mics.txt”);
File output = new File(“mahe.txt”);
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
//perform the loop till the end of file is reached.
while((c = in.read())!= -1)
out.write(c);
//close the streams
in.close();
out.close();
}}

A different program for copying file is shown below


//Another program to copy a file
import java.io.*;
public class CopyBytes{
public static void main(String arg[])throws IOException {
File inputFile = new File(“mics.txt”);
File output = new File(“mahe.txt”);
FileInputStream in = new FileInputStream (inputFile);
FileOutputStream out = new FileOutputStream (outputFile);
int c;
//perform the loop till the end of file is reached.
while((c = in.read())!= -1)
out.write(c);
//close the streams
in.close();
out.close();
}}

www.arihantinfo.com
UNIT 11: EXCEPTION HANDLING

11.1Introduction
11.2What are Exception
11.3Try/catch
11.4The finally clause
11.5The throws clause
11.6The throw clause
11.7User Define Exception

Exceptions

11.1 Introduction

Though it is the dream of every programmer to write error-free programs it is not so


normally. This is because the programmer has not anticipated all possible situations that
might occur while running the program. The errors might be due to a programming mistake,
bad input data, corrupt files or problems in physical devices. It is necessary to take care
about these situations. The possible remedies could be to

• notify the user of an error

• save the work environment

www.arihantinfo.com
• allowing to exit from the program without adversely affecting the other programs in
execution.

11.2 What are Exceptions

Definition:

An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. When such an event occurs within a java method, the method
creates an exception object and hands it off to the runtime system. The exception object
contains information about the exception, including its type and the state of the program
when the error occurred. The runtime system is then responsible for finding some code to
handle the error. In java terminology, creating an exception object and handing it to the
runtime system is called throwing an exception.

By using exception to manage errors, java programs have the following advantages over
traditional error management techniques:
1. It helps to separate the error handling code from the regular code.
2. The runtime system searches backwards through the call stack, beginning with the
method in which the error occurred, until it finds a method that contains an
appropriate exception handler. A java method further up the call stack to catch it.
Thus only the methods that care about errors have to worry about detecting errors.
3. Grouping or categorization of exception is possible.

Exceptions in java are actual objects. They are instances of classes that inherit from the
class called Throwable. An instance of this class is created when an exception is thrown.

11.3 Try/catch
The programmer encloses in a try block the code that may throw an exception. The try block
is immediately followed by one or more catch blocks. Each catch block specifies the type of
exception it can catch and handle. If no exceptions are thrown in the try block, the
exception handlers (catch) for that block are skipped and the program resumes execution
after the last catch block, after executing a finally block if one is provided.

try {
Statement 1;
Statement 2;
Statement 3;
}
catch (Exception e) {
exception handler statements;
}

there could be more than one catch block, each of them catching a specific type of
exception.

try {

www.arihantinfo.com
Statement 1;
Statement 2;
}
catch (Exception1 e1) {
exception handler statements;
}
catch (Exception2 e2) {
exception handler statements;
}
catch (Exception3 e3) {
exception handler statements;
}

11.4 The finally clause

The finally clause is an optional part of try/catch block. The statements within the finally
clause are executed irrespective of the fact that an exception is thrown or not. Typically the
statements within the finally clause do clean up process such as releasing resources,
closing file, save status of the process. Remember that the try must be accomplained by at
least one catch block or a finally block.

try {
Statement 1;
Statement 2;
Statement 3;
}
catch(Exception e1) {
exception handler statement;
}
finally {
Statement 1;
Statement 2;
Statement 3;
}

EXAMPLE
public class ArrayException
{
public static void main(String[] args)
{
System.out.println("Array Exception Handling!");
try {
int a[] = new int[2];
a[4] = 5;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“exception:- " + e.getMessage());
} //end catch
} //end main
}; //end class

www.arihantinfo.com
11.5 The throws Clause

An alternative way is to indicate that a method may possibly throw an exception. This is
done by adding the throws keyword after the signature of the method and followed by the
name of one or more exceptions.

public myMethod() throws AnException {


statements;
}

when multiple exceptions are to be thrown, they are all put in the throws clause separated
by commas.

public myMethod() throws Exception1,Exception2, Exception3 {


statement 1;
statement 1;
}

Adding the throws clause does not necessarily mean that the exceptions occur. It provides
additional information with the method definition about the possible exception that might
occur.
The example below adds the throws clause followed by the name of the exception.

import java.io.*;
import java.util.Vector;
public class WriteFile {
public void writeNum() throws IOException {
printWriter out = new PrintWriter(new FileWriter(“abc.txt”));
for(int j=0;j<10;j++)
out.println(j + “ “ +j*j);
out.close();
}
public static void main(String args[]) throws IOException{
WriteFile s = new WriteFile();
s.writeNum();
}
}

11.6 The throw clause

To throw an exception within the method, use the throw statement. In order to throw it, find
the appropriate exception class, create an object of that class (using new operator) and use
the throw statement.
throw new IOException;

www.arihantinfo.com
11.7 User Define Exception

Users can create their own exception classes and throw that exception. The user defined
exception classes must derive from the Exception class or any of its subclasses such as
IOException. It is customary to specity the default constructor as well as a constructor
containing a detailed message. The example below defined an exception class as
MyException.

//Demonstrate the use of user defined exception class


import java.io.*;
class MyException extends IOException {
public MyException() { }
public MyException(String s) {
super(s);
}
}

public class WriteFile {


public void writeNum() throws IOException {
PrintWriter out = new PrintWriter( new FileWriter(“abc.txt”));
for(int j = 1; j < 10; j++)
out.println(j + “ “ + j* j);
out.close();
}
public static void main(String args[]) throws IOException {
WriteFile s = new WriteFile();
s.writeNum();
throw new MyException ( “IO Error”);
}
}

www.arihantinfo.com
UNIT 12: JAVA DATABASE CONNECTIVITY

12.1 Getting started with JDBC


12.2 What is JDBC
12.3 JDBC Architecture
12.4 JDBC API Interface in a Nutshell
12.4.1 Driver Manager
12.4.2 Connection
12.4.3 Statement
12.4.4 Resultset
12.4.5 CallabelStatement
12.4.6 DatabaseMetaData
12.4.7 Driver
12.4.8 PreparedStatement
12.4.9 ResultSetMetaData
12.4.10 DriverPropertyInfo
12.4.11 Date
12.4.12 Time
12.4.13 TimeStamp
12.4.14 Types
12.4.15 Numeric
12.4.16 Driver Interface
12.5 Application Area
12.6 Getting to Work
12.6.1 How to configure ODBC Driver
12.6.2 Connecting to a database
12.6.3 Executing database Queries
12.7 The Statement clause
12.8 The ResultSet class
12.9 More Complex Uses of JDBC
12.9.1 The PreaparedStatement class
12.9.2 The CallableStatement class
12.10 Working with Multiple Database
12.10.1 “DNSLess” Connection with the JDBC-ODBC “Bridge” Driver
12.10.1.1 MS Access Example
12.10.1.2 ODBC Driver for Oracle(from Oracle)
12.10.1.3 ODBC Driver for Oracle(from Microsoft)
12.10.1.4 ODBC Driver for Excel

www.arihantinfo.com
12.1 Getting Started with JDBC

Database access, for many developers, is an essential part of the tools of software
development. If you're new to Java development, you might be wondering just how Java
applets and applications can connect to a database. In this article, I'll show you how to get
started with JDBC, a mechanism that allows Java to talk to databases.

Accessing a database in Java doesn't have to be a difficult task. Using Java Database
Connectivity (JDBC) you can easily access databases in your applications and applets via
special drivers.

12.2 What is JDBC?

Java Database Connectivity (JDBC) provides Java developers with a standard API that is
used to access databases, regardless of the driver and database product. To use JDBC,
you'll need at least JDK 1.1, a database, and a JDBC driver. Installing the first two should
be straightforward, but finding a JDBC driver requires a little more effort. JDBC presents a
uniform interface to databases - change vendors and your applications only need to change
their driver.

There are plenty of drivers now for JDBC that support popular databases. If you can use a
JDBC driver that works specifically for your database, then that's great! If not, don't worry -
Sun provides a driver that is compatible with ODBC, so you should be able to connect to
any ODBC compliant database. The JDBC to ODBC bridge comes installed as part of
JDK1.1, so if this is your target platform, the driver will already be installed. You'll need to
create an ODBC datasource for your database, before your Java applications can access it.

12.3 JDBC Architecture

12.4 JDBC API Interface in a Nutshell


The API interface is made up of 4 main interfaces:

• java.sql DriverManager

• java. sql .Connection

• java. sql. Statement

www.arihantinfo.com
• java.sql.Resultset

In addition to these, the following support interfaces are also available to the developer:

• java.sql.Callablestatement

• java. sql. DatabaseMetaData

• java.sql.Driver

• java. sql. PreparedStatement

• java. sql .ResultSetMetaData

• java. sql. DriverPropertymfo

• java.sql.Date

• java.sql.Time

• java. sql. Timestamp

• java.sql.Types

• java. sql. Numeric

12.4.1 DriverManager

This is a very important class. Its main purpose is to provide a means of managing the different types of
JDBC database driver On running an application, it is the DriverManager's responsibility to load all the
drivers found in the system property jdbc . drivers. For example, this is where the driver for the Oracle
database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at
runtime which is not included in jdbc.drivers. When opening a connection to a database it is the
DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.

12.4.2 Connection

When a connection is opened, this represents a single instance of a particular database session. As long
as the connection remains open, SQL queries may be executed and results obtained. More detail on
SQL can be found in later chapters and examples found in Appendix A. This interface can be used to
retneve information regarding the table descriptions, and any other information about the database to
which you are connected. By using Connection a commit is automatic after the execution of a
successful SQL statement, unless auto commit has been explicitly disabled. In this case a commit
command must follow each SQL statement, or changes will not be saved. An unnatural disconnection
from the database during an SQL statement will automatically result in the rollback of that query, and
everything else back to the last successful commit.

12.4.3 Statement

www.arihantinfo.com
The objective of the Statement interface is to pass to the database the SQL string for execution and to
retrieve any results from the database in the form of a ResultSet. Only one ResultSet can be open per
statement at any one time. For example, two ResultSets cannot be compared to each other if both
ResultSets stemmed from the same SQL statement. If an SQL statement is re-issued for any reason, the
old Resultset is automatically closed.

12.4.4 ResultSet

A ResultSet is the retrieved data from a currently executed SQL statement. The data from the query is
delivered in the form of a table. The rows of the table are returned to the program in sequence. Within
any one row, the multiple columns may be accessed in any order
A pointer known as a cursor holds the current retrieved record. When a ResUltSet is
returned, the cursor is positioned before the first record and the next command (equivalent
to the embedded SQL FETCH command) pulls back the first row. A ResultSet cannot go
backwards. In order to re-read a previously retrieved row, the program must close the
ResultSet and re-issue the SQL statement. Once the last row has been retrieved the
statement is considered closed, and this causes the Resu1~Set to be automatically closed.

12.4.5 CallableStatement

This interface is used to execute previously stored SQL procedures in a way which allows standard
statement issues over many relational DBMSs. Consider the SQL example:
SELECT cname FROM tnaine WHERE cname = var;

If this statement were to be stored, the program would need a way to pass the parameter var
into the callable procedure. Parameters passed into the call are referred to sequentially, by
number. When defining a variable type in JDBC the program must ensure that the type
corresponds with the database field type for IN and OUT parameters.

12.4.6 DatabaseMetaData

This interface supplies information about the database as a whole. MetaData refers to information held
about data. The information returned is in the form of ResultSet5. Normal ResultSet methods, as
explained previously, may be used in this instance. If metadata is not available for the particular request
then an SQLException will occur

12.4.7 Driver

For each database driver a class that implements the Driver interface must be provided. When such a
class is loaded it should register itself with the DriverManager, which will then allow it to be accessed
by a program.

www.arihantinfo.com
12.4.8 PreparedStatement

A PreparedStatement object is an SQL statement which is pre-compiled and stored. This object can
then be executed multiple times much more efficiently than preparing and issuing the same statement
each time it is needed. When defining a variable type in JDBC, the program must ensure that the type
corresponds with the database field type for IN and OUT parameters.

12.4.9 ResultSetMetaData

This interface allows a program to determine types and properties in any columns in a ResultSet. It may
be used to find out a data type for a particular field before assigning its variable type.

12.4.10 DriverPropertyinfo

This class is only of interest to advanced programmers. Its purpose is to interact with a particular driver
to determine any properties needed for connections.

12.4.11 Date

The purpose of the Date class is to supply a wrapper to the standard Java Date class which extends to
allow JDBC to recognise an SQL DATE.

12.4.12 Time

The purpose of the Time class is to supply a wrapper to the standard Java Time class which extends to
allow JDBC to recognise an SQL TIME.

12.4.13 Timestamp

The purpose of the Times tamp class is to supply a wrapper to the standard Java Date class which
extends to allow JDBC to recognise an SQL TIMESTAMP

12.4.14 Types

The Types class determines any constants that are used to identify SQL types.
12.4.15 Numeric

The object of the Numeric class is to provide high precision in numeric computations that require fixed
point resolution. Examples include monetary or encryption key applications. These equate to database
SQL NUMERIC or DECIMAL types.

www.arihantinfo.com
12.4.16 Driver Interface

The driver side of the JDBC layer is the part that interfaces to the actual database, and
therefore is generally written by database vendors. Most developers only need to know how
to install and use drivers. The JDBC Driver API defines a set of interfaces which have to be
implemented by a vendor

JDBC is based on Microsoft's Open Database Connectivity (ODBC) interface which many of
the mainstream databases have adopted. Therefore, a JDBCODBC bridge is supplied as part
of JDBC, which allows most databases to be accessed before the Java driver is released.
Although efficient and fast, it is recommended that the actual database JDBC driver is used
rather than going through another level of abstraction with ODBC.

Developers have the power to develop and test applications that use the JDBC-ODBC
bridge. If and when a proper driver becomes available they will be able to slot in the new
driver and have the applications utilise it instantly, without the need for rewriting. However,
do not assume the JDBC-ODBC bridge is a bad alternative. It is a small and very efficient
way of accessing databases.

12.5 Application Areas

JDBC has been designed and implemented for use in connecting to databases. Fortunately,
JDBC has made no restrictions, over and above the standard Java security mechanisms, for
complete systems. To this end, a number of overall system configurations are feasible for
accessing databases.

1. Java application which accesses local database

2. Java applet accesses server-based database

3. Database access from an applet via a stepping stone

12.6 Getting to Work.

12.6.1 How to Configure ODBC Driver?

DSN Configuration for MS Access Databases

To use the JDBC-ODBC bridge driver you'll need to configure an appropriate ODBC driver.
This is because the bridge driver doesn't communicate directly with a database but with a
native ODBC driver. (DSN less connections are also possible.)

Windows 2000/XP

Click Start, point to Settings, and then click Control Panel. Double click Administrative
Tools and then double click Data Sources (ODBC) to launch the ODBC Data Source
Administrator tabbed dialogue window.

www.arihantinfo.com
Windows 95/98/ME/NT

Click Start > Setttings > Control panel and then double click on the ODBC icon to launch
the ODBC Data Source Administrator tabbed dialogue window.

Windows 95/98/ME/NT/2000/XP

You will now need to select whether you want to configure the ODBC driver for use by a
single user or for use by every user on the computer.

The first tab, "User DSN" is for only a specific user and can only be used on your specific
computer. The second tab, "System DSN" is used to configure the ODBC driver for all users
on your computer. (If unsure which one to choose, for now select System.)

Click on Add to add a new data source Select Microsoft Access Driver from the listed
drivers, then click on Finish.

In the next window, type in the data source name in the Data source name text field (for
most of the examples, we'll use the sample Northwind database that's distributed with
Microsoft Access and Microsoft SQL Server, so a data source name of "northwind" seems
reasonable; for some examples, we may use the pubs database that's distributed with
Microsoft SQL Server Sybase SQL Server, Sybase ASA, and Sybase ASE).

Now you need to associate the database with the data source name you just chose, click on
the "Select ..." button. Use the Select Database window to choose the location of the .mdb
file that contains the database you're working with (again, mostly we'll use the Northwind
database; typically it's in C:\Program Files\Microsoft Office\Office\Samples -- if it's not
there, try searching for "Northwind.mdb").

Now click OK > OK > OK. Your ODBC data source is configured.

12.6.3 Connecting to a database

In order to connect to a database, you need to perform some initialization first. Your JDBC
driver has to be loaded by the Java Virtual Machine classloader, and your application needs
to check to see that the driver was successfully loaded. We'll be using the ODBC bridge
driver, but if your database vendor supplies a JDBC driver, feel free to use it instead.
// Attempt to load database driver
try
{
// Load Sun's jdbc-odbc driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
}
catch (ClassNotFoundException cnfe) // driver not found
{
www.arihantinfo.com
System.err.println ("Unable to load database driver");
System.err.println ("Details : " + cnfe);
System.exit(0);
}
We try to load the JdbcOdbcDriver class, and then catch the ClassNotFoundException if it
is thrown. This is important, because the application might be run on a non-Sun virtual
machine that doesn't include the ODBC bridge, such as Microsoft's JVM. If this occurs, the
driver won't be installed, and our application should exit gracefully.

Once our driver is loaded, we can connect to the database. We'll connect via the driver
manager class, which selects the appropriate driver for the database we specify. In this case,
we'll only be using an ODBC database, but in more complex applications, we might wish to
use different drivers to connect to multiple databases. We identify our database through a
URL. No, we're not doing anything on the web in this example - a URL just helps to identify
our database.

A JDBC URL starts with "jdbc:" This indicates the protocol (JDBC). We also specify our
database in the URL. As an example, here's the URL for an ODBC datasource called 'demo'.
Our final URL looks like this :

jdbc:odbc:demo

To connect to the database, we create a string representation of the database. We take the
name of the datasource from the command line, and attempt to connect as user "dba",
whose password is "sql".
// Create a URL that identifies database
String url = "jdbc:odbc:" + args[0];

// Now attempt to create a database connection


Connection db_connection =
DriverManager.getConnection (url, "dba", "sql");
As you can see, connecting to a database doesn't take much code.

12.6.4 Executing database queries

In JDBC, we use a statement object to execute queries. A statement object is responsible for
sending the SQL statement, and returning a set of results, if needed, from the query.
Statement objects support two main types of statements - an update statement that is
normally used for operations which don't generate a response, and a query statement that
returns data.
// Create a statement to send SQL
Statement db_statement = db_connection.createStatement();
Once you have an instance of a statement object, you can call its executeUpdate and
executeQuery methods. To illustrate the executeUpdate command, we'll create a table that
stores information about employees. We'll keep things simple and limit it to name and
employee ID.
// Create a simple table, which stores an employee ID and name
db_statement.executeUpdate
("create table employee { int id, char(50) name };");
www.arihantinfo.com
// Insert an employee, so the table contains data
db_statement.executeUpdate
("insert into employee values (1, 'John Doe');");
// Commit changes
db_connection.commit();
Now that there's data in the table, we can execute queries. The response to a query will be
returned by the executeQuery method as a ResultSet object. ResultSet objects store the last
response to a query for a given statement object. Instances of ResultSet have methods
following the pattern of getXX where XX is the name of a data type. Such data types include
numbers (bytes, ints, shorts, longs, doubles, big-decimals), as well as strings, booleans,
timestamps and binary data.
// Execute query
ResultSet result = db_statement.executeQuery
("select * from employee");

// While more rows exist, print them


while (result.next() )
{
// Use the getInt method to obtain emp. id
System.out.println ("ID : " + result.getInt("ID"));

// Use the getString method to obtain emp. name


System.out.println ("Name : " + result.getString("Name"));
System.out.println ();
}
Putting it all together

To show you just how JDBC applications work, I've put together a simple demonstration,
that allows users to insert new employees into the system, and to obtain a list. The
demonstration uses ODBC to connect to an Access database, which can be downloaded
along with the source code.

Running the sample application is quite straightforward. First, you'll need to create an
ODBC datasource for the access database. Next, using JDK1.1 or higher, run the
JDBCDemo application, and pass the datasource name as a parameter.
java JDBCDEMO demo
The demonstration application presents you with a menu, containing three options.
Choosing the first operation allows you to add a new employee, using the SQL insert
statement. Choosing the second option displays all employees in the system, using the SQL
select statement. Finally, the third option closes the database connection and exits.
Menu

1. Add new employee


2. Show all employees
3. Exit
Choice : 1
ID : 3
Name : Bill Gates
Menu

www.arihantinfo.com
1. Add new employee
2. Show all employees
3. Exit
Choice : 2
ID : 1
Name : David Reilly

ID : 2
Name : John Doe

ID : 3
Name : Bill Gates
Sample output from JDBCDemo

Listing The sample1 application using JDBC.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample1
{
public static void main(String arg[]) {
int id;
float amount;
Date dt;
String status;
String result;
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
// create Statement object
Statement stmt = con.createStatement();
String sqlselect = "Select company_id, order_dt, po_amount, status_cd"
+ " from dba.purchase_order";
// run query
ResultSet rs = stmt.executeQuery(sqlselect);
// process results
while(rs.next()) {
result = "";
id = rs.getInt(1);
amount = rs.getFloat(3);
dt = rs.getDate(2);
status = rs.getString(4);
result = result.valueOf(id) + " ";
result+= result.valueOf(amount) + " ";
result+= dt.toString() + " " + status;
System.out.println("Values are: " + result);
}

www.arihantinfo.com
//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
Once a connection is established to the database, it is used to create some kind of
statement using the Statement class or one of its extensions.

12.7 The Statement Class


A statement for simple querying of a database takes the following form:
// create Statement object
Statement stmt = con.createStatement();
This type of statement can be used for single-use updates or queries to the database that do
not return multiple result sets or update counts.

After the statement is created, it can be used to issue a simple query, as shown here:
String sqlselect = "Select company_id, order_dt, po_amount, status_cd"
+ " from dba.purchase_order";
// run query
ResultSet rs = stmt.executeQuery(sqlselect);
This example shows how a String object is used to hold the select statement, which is then
used in the executeQuery() method call. This method, in turn, generates a ResultSet object
containing the results of the query.

The preceding example shows a select statement that accesses all the data in a table.
Parameters passed to the Java application can be appended to the SQL statement for a
more dynamic query, as shown here:
String srch = arg[0];
String sqlselect = "Select company_id, order_dt, po_amount, status_cd"
+ " from dba.purchase_order where company_id = " + srch;
// run query
ResultSet rs = stmt.executeQuery(sqlselect);
In addition to searching for specific values, wildcard characters (also referred to as escape or
pattern match characters) can be used in a search. In Java, an underscore character (_) is
used to search for a single character, and a percent sign (%) is used to search for zero or
more characters, as shown in Listing 43.2.

Listing The sample2 application using escape characters.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample2
{
public static void main(String arg[]) {
www.arihantinfo.com
int id;
float amount;
Date dt;
String status;
String result;
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
// create Statement object
Statement stmt = con.createStatement();
String srch = arg[0];
String sqlselect = "Select company_id, order_dt, po_amount, status_cd"
+ " from dba.purchase_order where company_id = " + srch;
// run query
ResultSet rs = stmt.executeQuery(sqlselect);
// process results
while(rs.next()) {
result = "";
id = rs.getInt(1);
amount = rs.getFloat(3);
dt = rs.getDate(2);
status = rs.getString(4);
result = result.valueOf(id) + " ";
result+= result.valueOf(amount) + " ";
result+= dt.toString() + " " + status;
System.out.println("Values are: " + result);
}

//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
This code in the above Listing looks for any company name that contains the value specified
by the variable srch. Notice that the results are pulled from the row using the data type
specific to the column. These values are then converted to String values using the valueOf()
method. A more efficient method would have been to pull the values in directly as strings
using the getString() method, but the example does demonstrate some of the other ResultSet
get methods.

CAUTION: If you are using the escape characters, don't forget to include the surrounding
quotation marks (") for the pattern-match sequence. Pattern matching is for character-
based or like fields; if you forget the quotation marks, you will get an error.

www.arihantinfo.com
You can also run update statements with the JDBC. Instead of using executeQuery(), your
application must use executeUpdate().

The update statement can be any valid data modification statement: UPDATE, DELETE, or
INSERT. The result is the count of rows impacted by the change. The following Listing
shows an example of each of the different types of data manipulation statements.

Listing. The sample3 application demonstrating database updates.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample3
{
public static void main(String arg[]) {
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
con.setAutoCommit(false);

// create Statement object


Statement stmt = con.createStatement();
String updatestring = "INSERT INTO RETAIL_ITEM(item_nbr,item_desc, qty_per_pkg, "
+ "wholesale_cost, retail_cost, company_id, color, size) "
+ "VALUES(25,'some item', 1, 10.00, 15.00, 1, 'orange', 'M')";
// run query
int ct = stmt.executeUpdate(updatestring);
// process results
System.out.println("Insert row: " + updatestring.valueOf(ct));
updatestring = "UPDATE PERSON "
+ "set zip_cd = '97228' where "
+ "zip_cd = '97229'";
// run query
ct = stmt.executeUpdate(updatestring);
// process results
System.out.println("Updated rows: " + updatestring.valueOf(ct));
//back out modifications
updatestring = "DELETE FROM RETAIL_ITEM "
+ "where item_nbr = 25 and company_id = 1";
// run query
ct = stmt.executeUpdate(updatestring);
// process results
System.out.println("Delete row: " + updatestring.valueOf(ct));
updatestring = "UPDATE PERSON "
+ "set zip_cd = '97229' where "
+ "zip_cd = '97228'";
// run query
ct = stmt.executeUpdate(updatestring);

www.arihantinfo.com
// process results
System.out.println("Updated rows: " + updatestring.valueOf(ct));
//close connection
con.commit();
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
TIP: In the above Listing, note that autocommit is turned off for the set of transactions. If you
don't turn autocommit off, each of the transactions would be committed as soon as it
completed, rather than committing after all the transactions have completed. Because we
are backing changes out, we want all the transactions to succeed before issuing a commit;
otherwise all the transactions will roll back if an exception occurs (the database implements
this functionality by default).
The Statement object can also be used in a call to a database stored procedure if no
dynamic parameters are given. For procedures with IN, OUT, and INOUT parameters, the
CallableStatement class is used, as explained later in this chapter.

If the statement is a query, it always returns a ResultSet object unless an exception occurs.
The ResultSet object is demonstrated in more detail in the following section.

12.8 The ResultSet Class


A query returns a ResultSet object. This object contains the results of the query in a form
that can be accessed by the application. If the query has no results, the ResultSet object
contains no rows; otherwise, it contains rows of data matching the query (up to the limit
specified for the database). If the database supports doing so, you can set the maximum
number of rows using the Statement class method setMaxRows(). Once the result set is
returned, you can use methods to access and process individual columns as shown in the
following Listing.

Listing. The sample4 application with a result set.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample4
{
public static void main(String arg[]) {
int id;
String name;
String address;
String city;
String state;
String result;
www.arihantinfo.com
String srch = arg[0];
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
// create Statement object
Statement stmt = con.createStatement();
stmt. setMaxRows(10);
String sqlselect = "Select company_id, company_name, address_1, city, state_cd"
+ " from dba.company where company_name like '%" + srch + "%'";
// run query
ResultSet rs = stmt.executeQuery(sqlselect);
// process results
while(rs.next()) {
result = "";
id = rs.getInt(1);
name = rs.getString(2);
address = rs.getString(3);
city = rs.getString(4);
state = rs.getString(5);
result = result.valueOf(id) + " ";
result+= name + " " + address + " ";
result+= city + " " + state;
System.out.println("Values are: " + result);
}
//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
Individual data types have matching getXXX() methods to retrieve the value in the form the
application prefers. You pass to each method the number of the column representing the
position it holds in the original select statement, or a text string containing the name of the
column. The next() method maintains a cursor that points to the current row being
processed. Each call to the method moves the cursor to the next row. When no more rows
are found, the next() method returns a value of false.

You can access the columns even if you don't know the order in which the columns will be
returned. Using the findColumn() method, you can look for a column with the same name as
the one passed to the method; the method returns the column index. You can then use the
index used to access the value, as shown in the following Listing.

Listing. The sample5 application using the findColumn() method.


// run query
ResultSet rs = stmt.executeQuery(sqlselect);
www.arihantinfo.com
// process results
while(rs.next()) {
result = "";
id = rs.getInt(rs.findColumn("company_id"));
name = rs.getString(rs.findColumn("company_name"));
address = rs.getString(rs.findColumn("address_1"));
city = rs.getString(rs.findColumn("city"));
state = rs.getString(rs.findColumn("state_cd"));
result = result.valueOf(id) + " ";
result+= name + " " + address + " ";
result+= city + " " + state;
System.out.println("Values are: " + result);

}
This technique is a little convoluted because you can also use the get methods that accept a
string representing the column name and return the result. A partial listing of the results of
running the sample5 Java application are shown here:
java sample5
Values are: 1 Portland T-Shirt Company 18050 Industrial Blvd. Portland, OR
Values are: 2 Tri-State Stuffed Critter 923 Hawthorne Way Vancouver WA
Values are: 3 Tigard Candy Shop 1900 Mountain Rd Tigard OR
Values are: 4 LA T-Shirt Company 13090 SW 108th Ave SW Los Angeles CA
...
In addition, you can also check to see whether a column value is null by using the wasNull()
method after the getXXX() method call:
state = rs.getString("state_cd");
boolean b = rs.wasNull();
if (b) {
...
The examples in this section introduced and demonstrated the Connection, Statement, and
ResultSet classes. The next two sections demonstrate the use of some more complex
features of the JDBC and how to access multiple heterogeneous databases.

12.9 More Complex Uses of JDBC

Occasionally, a database developer has to program for more complex database access
situations. You may want to create a statement and then execute it many times, or call a
stored procedure that returns multiple result sets, or issue a dynamic SQL statement. This
section covers some techniques for handling these types of statements.

Two of the classes discussed, PreparedStatement and CallableStatement, are extended


classes: the former is an extension of Statement and the latter is an extension of
PreparedStatement.

In addition to the classes, the following sections also demonstrate and discuss the execute()
method of the Statement class.

www.arihantinfo.com
12.9.1 The PreparedStatement Class
The PreparedStatement class is used to create and compile a statement at the database,
and then invoke that statement multiple times. The statement usually has one or more IN
parameters that change each time the statement is executed.

Both the executeUpdate() and executeQuery() methods work with the PreparedStatement
class. The class is an extension of the standard Statement class; it has the additional
flexibility of being stored in a compiled form and run many times.

To create the PreparedStatement class statement, use a SQL string that contains references
to one or more unknown parameters:
String sqlselect =
"Select * from retail_item where company_id = ?";
// create Statement object
PreparedStatement stmt = con.prepareStatement(sqlselect);
Before executing the statement (in this example, it is a query), you must set the IN
parameter value:
stmt.setInt(1,i);
rs = stmt.executeQuery();
After executing the query or update, you can process the results in the same way you
process a regular statement:
int colcount = rsmd.getColumnCount();
// process results
while(rs.next()) {
result = "";
for (int k = 1; k <= colcount; k++) {
result+= rs.getString(k) + " ";
}
System.out.println("Values are: " + result);
}
The only difference between using the PreparedStatement class and the Statement class is
that the same statement would then be processed for the former with different parameters.

A full example of using this class is given in the following Listing.

Listing. The sample6 application using the PreparedStatement class.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample6
{
public static void main(String arg[]) {
String result;
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
www.arihantinfo.com
con.setAutoCommit(false);
String sqlselect =
"Select * from retail_item where company_id = ?";
// create Statement object
PreparedStatement stmt = con.prepareStatement(sqlselect);
ResultSet rs;
ResultSetMetaData rsmd;
for (int i = 1; i <= 3; i++) {
stmt.setInt(1,i);
rs = stmt.executeQuery();
rsmd = rs.getMetaData();
int colcount = rsmd.getColumnCount();
// process results
while(rs.next()) {
result = "";
for (int k = 1; k <= colcount; k++) {
result+= rs.getString(k) + " ";
}
System.out.println("Values are: " + result);
}
}

//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
Issuing an update instead of a query is no different except that the IN parameters are used
to modify data instead of to select it, and that the executeUpdate() method is used instead of
executeQuery():
String sqlselect =
"Update retail_item set company_id = ? where company_id = ?";
// create Statement object
PreparedStatement stmt = con.prepareStatement(sqlselect);
for (int i = 1; i <= 3; i++) {
stmt.setInt(1,i);
stmt.setInt(2, i + 1);
int count = stmt.executeUpdate();
...
The purpose of the PreparedStatement class is to compile the query ahead of time, which
cuts back on the time necessary to process each query or update. If you are not planning to
run the SQL statement multiple times, using the PreparedStatement class is not an effective
approach.

www.arihantinfo.com
PROBLEMS WITH PreparedStatement
The PreparedStatement class may not work if the database does not maintain an open
connection between transactions; if the database does not support the use of compiled
SQL; or if the JDBC drivers or the database drivers do not support this type of statement. If
you use the statement with a JDBC driver that doesn't support it, you get a class exception.
If you use the statement with a database or driver that does not support it, you get a
SQLException. In my experience, the PreparedStatement class did not work with the ODBC
driver for Sybase SQL Anywhere; it also did not work with the driver I had for Microsoft
Access at the time this chapter was written. Using the PreparedStatement class resulted in
the error Invalid Cursor State, as shown here:
java sample6
Values are: 1 Eagle T-Shirt 1 8.50 14.95 1 Black S null
Values are: 4 Wolf T-Shirt 1 8.50 14.95 1 Green S null
Values are: 5 Wolf T-Shirt 1 8.50 14.95 1 Green M null
Values are: 6 Wolf T-Shirt 1 8.50 14.95 1 Green L null
Values are: 19 Snake Shirt 1 13.50 22.00 1 Green S null
Values are: 20 Snake Shirt 1 13.50 22.00 1 Green M null
Values are: 21 Snake Shirt 1 13.50 22.00 1 Green L null
Values are: 22 Cat Shirt 1 8.00 13.00 1 Green XLG null
Values are: 2 Eagle T-Shirt 1 8.50 14.95 1 Black M null
Values are: 3 Eagle T-Shirt 1 8.50 14.95 1 Black L null
Values are: 7 Wolf T-Shirt 1 8.50 14.95 1 Blue L ADSDFS
Values are: 23 Get Wild Tie Dyed T-Shirt 1 10.50 20.95 1 null XL null
Values are: 24 Leopard T-Shirt 1 9.00 14.95 1 Brown L null
Values are: 30 Test 1 12.00 13.00 1 Orange S null
Values are: 40 Cats of the World T-Shirt 1 8.00 14.00 1 Black L null
[Sybase][ODBC Driver]Invalid cursor state

The execute() Method


The execute() method is defined for use with the Statement class, which also makes it
available for use with the PreparedStatement and CallableStatement classes. This method is
used to process an unknown statement, a statement that may return multiple result sets
and update counts, or both.

For example, you may have an ad-hoc SQL tool that allows the user to enter any valid SQL
statement and then process the statement. The user passes in the SQL statement with a
program call like this:
// create Statement object
Statement stmt = con.createStatement();
String sqlstmt = arg[0];
// run statement
boolean b = stmt.execute(sqlstmt);
The result returned from the execute() method is a boolean value: it is false if there are no
results or the statement contains an update; it is true if the statement returns at least one
result set and no update counts.

If your application cares only about processing result sets from a statement, you can
process the results as follows:
www.arihantinfo.com
// if true, result set
result = "";
if (b) {
// process results
ResultSet rs = stmt.getResultSet();
ResultSetMetaData rsmd = rs.getMetaData();
int colcount = rsmd.getColumnCount();
while(rs.next()) {
result = "";
for (int i=1; i <= colcount; i++) {
result+= rs.getString(i) + " ";
}
System.out.println("Values are: " + result);
}
}
...
Normally, however, your application wants to process all the return results--if only to
provide feedback to the user. The following Listing provides a complete example of using the
execute() method.

Listing. The sample7 application using the execute() method.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample7
{
public static void main(String arg[]) {
String result;
try {
//connect to ODBC database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
// create Statement object
Statement stmt = con.createStatement();
String sqlstmt = arg[0];
// run statement
boolean b = stmt.execute(sqlstmt);
// if true, result set
result = "";
if (b) {
// process results
ResultSet rs = stmt.getResultSet();
ResultSetMetaData rsmd = rs.getMetaData();
int colcount = rsmd.getColumnCount();
while(rs.next()) {
result = "";
for (int i=1; i <= colcount; i++) {
result+= rs.getString(i) + " ";
}
www.arihantinfo.com
System.out.println("Values are: " + result);
}
}
else {
int ct = stmt.getUpdateCount();
result = "Update count is " + result.valueOf(ct);
System.out.println(result);
}
//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
Running the example and passing in the string "Select * from retail_item" returns this result
(only the first few lines of the result are shown because the result is fairly lengthy):
java sample7 "select * from retail_item"
Values are: 1 Eagle T-Shirt 1 8.50 14.95 1 Black S null
Values are: 2 Chocolate Tigers 5 1.00 1.50 3 null M null
Values are: 3 Stuffed Panda 1 13.50 21.00 2 null L null
Values are: 4 Wolf T-Shirt 1 8.50 14.95 1 Green S null
Values are: 5 Wolf T-Shirt 1 8.50 14.95 1 Green M null
Values are: 6 Wolf T-Shirt 1 8.50 14.95 1 Green L null
Values are: 3 Keychain Zoo Pen 1 .52 1.95 8 null null null
Values are: 8 Taffy Pulls 3 .75 1.25 3 null null null
Values are: 9 Chocolate Pandas 5 1.00 1.50 3 null null null
Values are: 10 Stuffed Giraffe 1 9.95 16.95 2 null null null
An application rarely wants to process an unknown statement, but you may want to run a
stored procedure that has multiple result sets. This type of procedure is demonstrated in
the next section.

PROBLEMS WITH Using Cursors

The execute() method requires the database to support cursors, which enable processing of
multiple result sets. The execute() method also requires the database and database driver to
support maintaining an open connection after a transaction. If the database does not
support these features, the execute() method can result in an error such as invalid cursor state
(as happened when I ran the sample7 application with both the Sybase SQL Anywhere ODBC
driver and the Microsoft Access ODBC driver). Before spending time coding for something
that may not work, test your JDBC and database drivers with the sample7 code in the above
Listing.

www.arihantinfo.com
12.9.2 The CallableStatement Class
The CallableStatement class is used to accept several parameters for a stored procedure
call. The parameters can be defined as input only, output only, or both.

CallableStatement is an extension of PreparedStatement, which is itself an extension of


Statement. The CallableStatement class adds methods to register and access output
parameters.

To create a CallableStatement object, issue the procedure call with question marks (?) in
place of parameters:

String scall = "call new_po(?,?,?,?,?,?,?,?,?,?)";


// create Statement object
CallableStatement stmt = con.prepareCall(scall);

You must first set the IN parameters using the appropriate setXXX() methods:
stmt.setInt(1, 1);
stmt.setDate(2, dt);
stmt.setInt(3,1);
stmt.setDouble(4, 10.00);
stmt.setString(5,"OP");
stmt.setInt(6,1);
stmt.setInt(7,1);
stmt.setDouble(8, 10.00);
stmt.setInt(9,61);
The last parameter is not set because it is an OUT parameter only. It must be registered
using one of the RegisterOutParameter() methods:

stmt.registerOutParameter(10,java.sql.Types.INTEGER);

Because the new_po() procedure contains two INSERT commands and multiple result sets,
in addition to the one output parameter, the execution method to use for this statement is
execute():
stmt.registerOutParameter(10,java.sql.Types.INTEGER);
// run statement
stmt.execute();
The result sets and update counts are then processed. In the following Listing shows all the
code that demonstrates the use of CallableStatement with two insert commands.

Listing. The sample8 application using the CallableStatement class.


import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;
public class sample8
{
public static void main(String arg[]) {
String result;
Date dt = new Date(97, 12,1);
try {
//connect to ODBC database
www.arihantinfo.com
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";
// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");
String scall = "call new_po(?,?,?,?,?,?,?,?,?,?)";
// create Statement object
CallableStatement stmt = con.prepareCall(scall);
stmt.setInt(1, 1);
stmt.setDate(2, dt);
stmt.setInt(3,1);
stmt.setDouble(4, 10.00);
stmt.setString(5,"OP");
stmt.setInt(6,1);
stmt.setInt(7,1);
stmt.setDouble(8, 10.00);
stmt.setInt(9,61);
stmt.registerOutParameter(10,java.sql.Types.INTEGER);
// run statement
stmt.execute();
// get update counts
boolean cont = true;
while(cont) {
int colcount = stmt.getUpdateCount();
if (colcount > 0) {
System.out.println("Updated rows are: " + colcount);
stmt.getMoreResults();
}
else {
cont = false;
}
}
cont =true;
result="";
while(cont) {
ResultSet rs = stmt.getResultSet();
ResultSetMetaData rsms = rs.getMetaData();
int colcount = rsms.getColumnCount();
for (int i = 1; i <= colcount; i++) {
result+=rs.getString(i) + " ";
}
System.out.println("results are " + result);
result="";
cont = stmt.getMoreResults();
}
int po_count = stmt.getInt(10);
System.out.println("Number of POS is " + po_count);
//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());

www.arihantinfo.com
}
}

}
Unfortunately, when I use this code with the JDBC-ODBC bridge to access a Sybase SQL
Anywhere database, I get the Function Sequence Error error:
java sample8
Updated rows are: 1
[Microsoft] [ODBC Driver Manager] Function sequence error
This ODBC DriverManager error occurs because an asynchronously executing function is
called when the function is still running from the first call. According to the ODBC
documentation, this error occurs when a procedure call or SQL execution statement occurs
while a previous call still requires data to be passed in from parameters. After examining the
data in the tables, however, I did find that the updates had occurred.

As a workaround to this problem, I modified the code (the modified example is in


sample8b.java) to call a stored procedure that contains only the two updates and not the
multiple result sets, as shown in following Listing.

Listing. The sample8b.java application containing the stored procedure call with two
updates.
import java.lang.*;
import java.sql.*;
import sun.jdbc.odbc.*;

public class sample8b


{

public static void main(String arg[]) {


String result;

Date dt = new Date(97, 12,1);

try {

//connect to ODBC database


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Zoo";

// connect
Connection con = DriverManager.getConnection(url,"dba", "sql");

String scall = "call new_po_copy(?,?,?,?,?,?,?,?,?,?)";

// create Statement object


CallableStatement stmt = con.prepareCall(scall);

stmt.setInt(1, 1);
stmt.setDate(2, dt);
stmt.setInt(3,1);
www.arihantinfo.com
stmt.setDouble(4, 10.00);
stmt.setString(5,"OP");
stmt.setInt(6,1);
stmt.setInt(7,1);
stmt.setDouble(8, 10.00);
stmt.setInt(9,62);

stmt.registerOutParameter(10,java.sql.Types.INTEGER);

// run statement
stmt.executeUpdate();

int po_count = stmt.getInt(10);


System.out.println("Number of POS is " + po_count);

//close connection
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}

}
This procedure is then used in an executeUpdate() call. The output parameter is printed
after the update occurs.

This version of the application worked without error and printed the number of purchase
orders in the database, as returned in the OUT parameter.

12.10 Working with Multiple Databases

The last Java application created in this chapter is one that refreshes a table in an mSQL
database with the contents of a table in a Microsoft Access database. This example
demonstrates the ease with which you can open and maintain multiple database
connections at the same time.

The first part of the code loads the mSQL-JDBC driver classes and opens a connection to
the mSQL database:

//connect to mSQL database


Class.forName("imaginary.sql.iMsqlDriver");
String url = "jdbc:msql://yasd.com:1112/yasd";
// mSQL connection
Connection con = DriverManager.getConnection(url);
// mSQL statement
Statement stmt = con.createStatement();
www.arihantinfo.com
Next, an update is issued to delete the contents from the table being refreshed, in this case,
the company table:

// clean out existing data


stmt.executeUpdate("DELETE from company");

The Access database connection and statement is created next. Note that the mSQL
database is remote and that the Access database is local to the application:
//connect to Access database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
url = "jdbc:odbc:cityzoo";
// Access Connection
Connection con2 = DriverManager.getConnection(url,"Admin","sql");
// Access Statement
Statement stmt2 = con2.createStatement();
ResultSet rs = stmt2.executeQuery("Select company_id,"
+ "company_name, address_1, address_2, address_3,"
+ "city, state_cd, country_cd, postal_cd, phone_nbr "
+ "from company");
The data is pulled from the Access database as strings, which are then concatenated in to
an insert string for the mSQL database, as shown in the following Listing.

Listing. The code for sample9, which accesses two different databases at the same time.
import java.sql.*;
import sun.jdbc.odbc.*;
import java.io.*;
public class sample9
{
public static void main(String arg[]) {
String invalue;
String outvalue;
String id, name, add1, add2, add3,city,state,country,post,phone;
int pos, endpos;
try {
System.out.println("Refreshing company...");
//connect to mSQL database
Class.forName("imaginary.sql.iMsqlDriver");
String url = "jdbc:msql://yasd.com:1112/yasd";
// mSQL connection
Connection con = DriverManager.getConnection(url);
// mSQL statement
Statement stmt = con.createStatement();
// clean out existing data
stmt.executeUpdate("DELETE from company");
//connect to Access database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
url = "jdbc:odbc:cityzoo";
// Access Connection
Connection con2 = DriverManager.getConnection(url,"Admin","sql");
// Access Statement
Statement stmt2 = con2.createStatement();
www.arihantinfo.com
ResultSet rs = stmt2.executeQuery("Select company_id,"
+ "company_name, address_1, address_2, address_3,"
+ "city, state_cd, country_cd, postal_cd, phone_nbr "
+ "from company");
// for each line, enter into database
while (rs.next()) {
// get id
id = rs.getString(1);
name = rs.getString(2);
add1= rs.getString(3);
add2=rs.getString(4);
add3=rs.getString(5);
city=rs.getString(6);
state=rs.getString(7);
country=rs.getString(8);
post=rs.getString(9);
phone=rs.getString(10);
// create and execute insert statement
stmt.executeUpdate("insert into company (company_id, company_name,"
+ "address_1,address_2,address_3, "
+ "city,state_cd,country_cd,postal_cd,phone_nbr) values("
+ id + ",'" + name + "','" + add1 + "','"
+ add2 + "','"
+ add3 + "','" + city + "','" + state + "','"
+ country + "','" + post +
"','" + phone + "')");
}
stmt.close();
stmt2.close();
rs.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

}
The PreparedStatement class would have been ideal for this type of operation, but the mSQL
database does not support cursors, and the drivers for Microsoft Access do not maintain an
open connection between transactions. However, the technique that was used works very
well--and works fairly quickly, considering that the transactions occurred over a modem.

As a reminder, if you are working with multiple databases at the same time, you must
create separate connections and statements for each of the different databases.

12.11 "DSNLess" Connections with the JDBC-ODBC "Bridge" Driver

12.11.1 MS Access Example


String driverInfo = "DRIVER={Microsoft Access Driver (*.mdb)};"

www.arihantinfo.com
+ "DBQ=C:\\mydbs\\mydb.mdb";
Connection conn = DriverManager.getConnection(driverInfo);

12.11.2 ODBC Driver for Oracle (from Oracle)


String driverInfo = "Driver={Oracle ODBC Driver};" & _
"Dbq=myDBName;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
Where: The DBQ name must be defined in the tnsnames.ora file

12.11.3 ODBC Driver for Oracle (from Microsoft)

For the current Oracle ODBC Driver from Microsoft


String driverInfo = "Driver={Microsoft ODBC for Oracle};" & _
"Server=OracleServer.world;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
For the older Oracle ODBC Driver from Microsoft
String driverInfo = "Driver={Microsoft ODBC Driver for Oracle};" & _
"ConnectString=OracleServer.world;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"

12.11.4 ODBC Driver for Excel


String driverInfo = "Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=c:\somepath\mySpreadsheet.xls;" & _

"DefaultDir=c:\somepath"

www.arihantinfo.com
UNIT 13: MULTITHREADED APPLICATION

13.1Introduction of Multithreading
13.2What is a Thread
13.3Creating New Threads
13.3.1 Subclassing the Thread class
13.4Implementing the Runnable Interface
13.5Thread States
13.6The Thread API
13.7Scheduling and Priority
13.7.1 Setting Thread Priority
13.7.2 Waking up a Thread
13.7.3 Suspending and Resuming Thread Execution
13.7.4 Putting a Thread to Sleep

13.1 Introduction of Multithreading


One of the characteristics that makes Java a powerful programming language is its support
for multithreaded programming as an integrated part of the language. This provision is
unique because most modern programming languages either do not offer multithreading or
provide multithreading as a nonintegrated package. Java, however, offers a single,
integrated view of multithreading.
Multithreaded programming is an essential aspect of programming in Java. To master the
Java programming language, you should first become familiar with the concepts of
multithreaded programming. Then you should learn how multithreaded and concurrent
programming are done in Java.

13.2 What Is a Thread?


In the early days of computing, computers were single tasking--that is, they ran a single job
at a time. The big, lumbering machine would start one job, run that job to completion, then
start the next job, and so on. When engineers became overly frustrated with these batch-
oriented systems, they rewrote the programs that ran the machines and thus was born the
modern multitasking operating system.

Multitasking refers to a computer's capability to perform multiple jobs concurrently. For the
most part, modern operating systems like Windows 95 or Solaris can run two or more
programs at the same time. While you are using Netscape to download a big file, you can be
running Solitaire in a different window; both programs are running at the same time.
Multithreading is an extension of the multitasking paradigm. But rather than multiple
programs, multithreading involves multiple threads of control within a single program. Not
only is the operating system running multiple programs, each program can run multiple
threads of control--think of threads as subprograms--within the program. For example,
using a Web browser, you can print one Web page, download another, and fill out a form in
a third--all at the same time.
A thread is a single sequence of execution within a program. Until now, you have probably
used Java to write single-threaded applications, something like this:
class MainIsRunInAThread {
public static void main(String[] args) {
www.arihantinfo.com
// main() is run in a single thread
System.out.println(Thread.currentThread());
for (int i=0; i<1000; i++) {
System.out.println("i == " + i);
}
}

This example is simplistic, but it demonstrates the use of a single Java thread. When a Java
application begins, the virtual machine (VM) runs the main() method inside a Java thread.
(You have already used Java threads and didn't even know it!) Within this single thread, this
simple application's main() method counts from 0 to 999, printing out each value as it is
counted.

Programming within a single sequence of control can limit your ability to produce usable
Java software. (Imagine using an operating system that could execute only one program at a
time, or a Web browser that could load only a single page at a time.) When you write a
program, you often want the program to do multiple things at the same time. For example,
you may want the program to retrieve an image over the network at the same time it is
requesting an updated stock report and also running several animations--and you want all
this to occur concurrently. This is the kind of situation in which Java threads become
useful.

Java threads allow you to write programs that do many things at once. Each thread
represents an independently executing sequence of control. One thread can write a file out
to disk while a different thread responds to user keystroke events.

Before jumping into the details about Java threads, let's take a peek at what a
multithreaded application looks like. The Following Listing modifies the preceding single-
threaded application to take advantage of threads. Instead of counting from 0 to 999 in one
thread, this application uses five different threads to count from 0 to 999--each thread
counts 200 numbers: 0 to 199, 200 to 399, and so on. Don't worry if you don't understand
the details of this example yet; it is presented only to introduce you to threads.

Listing. A simple multithreaded application.


class CountThreadTest extends Thread {
int from, to;
public CountThreadTest(int from, int to) {
this.from = from;
this.to = to;
}
// the run() method is like main() for a thread
public void run() {
for (int i=from; i<to; i++) {
System.out.println("i == " + i);
}
}
public static void main(String[] args) {
// spawn 5 threads, each of wich counts 200 numbers
for (int i=0; i<5; i++) {

www.arihantinfo.com
CountThreadTest t = new CountThreadTest(i*200, (i+1)*200);
// starting a thread will launch a separate sequence
// of control and execute the run() method of the thread
t.start();
}
}
}
When this application starts, the VM invokes the main() method in its own thread. main()
then starts five separate threads to perform the counting operations.

13.3 Creating New Threads


The first thing you need to know about threads is how to create and run a thread. This
process involves two steps: writing the code that is executed in the thread and writing the
code that starts the thread.

As discussed earlier, you are already familiar with how to write single-threaded programs.
When you write a main() function, that method is executed in a single thread. The Java
virtual machine provides a multithreaded environment, but it starts user applications by
calling main() in a single thread.

An application's main() method provides the central logic for the main thread of the
application. Writing the code for a thread is similar to writing main(). You must provide a
method that implements the main logic of the thread. This method is always named run()
and has the following signature:
public void run();

Notice that the run() method is not a static method as main() is. The main() method is static
because an application starts with only one main() method. But an application may have
many threads, so the main logic for a thread is associated with an object--the Thread object.
You can provide an implementation for the run() method in two ways. Java supports the
run() method in subclasses of the Thread class. Java also supports run() through the
Runnable interface. Both methods for providing a run() method implementation are
described in the following sections.

13.3.1 Subclassing the Thread Class


This section discusses how to create a new thread by subclassing java.lang.Thread.
Let's start with a plausible situation in which a thread might be useful. Suppose that you
are building an application; in one part of this application, a file must be copied from one
directory to a different directory. But when you run the application, you find that if the file
is large, the application stalls during the time that the file is being copied. You determine
that the cause of the stall is this: When the application is copying the file, it is unable to
respond to user-interface events.
To improve this situation, you decide that the file-copy operation should be performed
concurrently, in a separate thread. To move this logic to a thread, you provide a subclass of
the Thread class that contains this logic, implemented in the run() method. The
FileCopyThread class shown in the following Listing contains this logic.

Listing. The file-copy logic in FileCopyThread.


// subclass from Thread to provide your own kind of Thread
class FileCopyThread extends Thread {
private File from;
www.arihantinfo.com
private File to;
public FileCopyThread(File from, File to) {
this.from = from;
this.to = to;
}
// implement the main logic of the thread in the run()
// method [run() is equivalent to an application's main()]
public void run() {
FileInputStream in = null;
FileOutputStream out = null;
byte[] buffer = new byte[512];
int size = 0;
try {
// open the input and output streams
in = new FileInputStream(from);
out = new FileOutputStream(to);
// copy 512 bytes at a time until EOF
while ((size = in.read(buffer)) != -1) {
out.write(buffer, 0, size);
}
} catch(IOException ex) {
ex.printStackTrace();
} finally {
// close the input and output streams
try {
if (in != null) { in.close(); }
if (out != null) { out.close(); }
} catch (IOException ex) {
}
}
}

}
Let's analyze the FileCopyThread class. Note that the FileCopyThread subclasses from
Thread. By subclassing from Thread, FileCopyThread inherits all the state and behavior of a
Thread--the property of "being a thread."
The FileCopyThread class implements the main logic of the thread in the run() method.
(Remember that the run() method is the initial method for a Java thread, just as the main()
method is the initial method for a Java application.) Within run(), the input file is copied to
the output file in 512-byte chunks. When a FileCopyThread instance is created and started,
the entire run() method is executed in one separate sequence of control (you'll see how this
is done soon).

Now that you are familiar with how to write a Thread subclass, you have to learn how to use
that class as a separate control sequence within a program. To use a thread, you must start
the concurrent execution of the thread by calling the Thread object's start() method. The
following code demonstrates how to launch a file-copy operation as a separate thread:
File from = getCopyFrom();
File to = getCopyTo();
// create an instance of the thread class
Thread t = new FileCopyThread(from, to);

www.arihantinfo.com
// call start() to activate the thread asynchronously
t.start();
Invoking the start() method of a FileCopyThread object begins the concurrent execution of
that thread. When the thread starts running, its run() method is called. In this case, the file
copy begins its execution concurrently with the original thread. When the file copy is
finished, the run() method returns (and the concurrent execution of the thread ends).

13.4 Implementing the Runnable Interface


There are situations in which it is not convenient to create a Thread subclass. For example,
you may want to add a run() method to a preexisting class that does not inherit from
Thread. The Java Runnable interface makes this possible.
The Java threading API supports the notion of a thread-like entity that is an interface:
java.lang.Runnable. Runnable is a simple interface, with only one method:
public interface Runnable {
public void run();
}
This interface should look familiar. In the previous section, we covered the Thread class,
which also supported the run() method. To subclass Thread, we redefined the Thread run()
method. To use the Runnable interface, you must write a run() method and add the text
implements Runnable to the class. Reimplementing the FileCopyThread (of the previous
example) as a Runnable interface requires few changes:
// implementing Runnable is a different way to use threads
class FileCopyRunnable implements Runnable {
// the rest of the class remains mostly the same
...
}
To use a Runnable interface as a separate control sequence requires the cooperation of a
Thread object. Although the Runnable object contains the main logic, Thread is the only
class that encapsulates the mechanism of launching and controlling a thread. To support
Runnable, a separate Runnable parameter was added to several of the Thread class
constructors. A thread that has been initialized with a Runnable object will call that object's
run() method when the thread begins executing.
Here is an example of how to start a thread using FileCopyRunnable:
File from = new File("file.1");
File to = new File("file.2");
// create an instance of the Runnable
Runnable r = new FileCopyRunnable(from, to);
// create an instance of Thread, passing it the Runnable
Thread t = new Thread(r);
// start the thread
t.start();

13.5 Thread States


Although you have learned a few things about threads, we have not yet discussed one
aspect that is critical to your understanding of how threads work in Java--thread states. A
Java thread, represented by a Thread object, traverses a fixed set of states during its lifetime
Thread states
.
When a Thread object is first created, it is in the NEW state. At this point, the thread is not
executing. When you invoke the Thread's start() method, the thread changes to the
RUNNABLE state.
www.arihantinfo.com
When a Java thread is RUNNABLE, it is eligible for execution. However, a thread that is
RUNNABLE is not necessarily running. RUNNABLE implies that the thread is alive and that
it can be allocated CPU time by the system when the CPU is available--but the CPU may not
always be available. On single-processor systems, Java threads must share the single CPU;
additionally, the Java virtual machine task (or process) must also share the CPU with other
tasks running on the system. How a thread is allocated CPU time is covered in greater depth
in "Scheduling and Priority," later in the chapter.

When certain events happen to a RUNNABLE thread, the thread may enter the NOT
RUNNABLE state. When a thread is NOT RUNNABLE, it is still alive, but it is not eligible for
execution. The thread is not allocated time on the CPU. Some of the events that may cause a
thread to become NOT RUNNABLE include the following:

The thread is waiting for an I/O operation to complete

The thread has been put to sleep for a certain period of time (using the sleep() method)
The wait() method has been called (as discussed in "Synchronization," later in this chapter)
The thread has been suspended (using the suspend() method)

A NOT RUNNABLE thread becomes RUNNABLE again when the condition that caused the
thread to become NOT RUNNABLE ends (I/O has completed, the thread has ended its
sleep() period, and so on). During the lifetime of a thread, the thread may frequently move
between the RUNNABLE and NOT RUNNABLE states.

When a thread terminates, it is said to be DEAD. Threads can become DEAD in a variety of
ways. Usually, a thread dies when its run() method returns. A thread may also die when its
stop() or destroy() method is called. A thread that is DEAD is permanently DEAD--there is
no way to resurrect a DEAD thread.
NOTE: When a thread dies, all the resources consumed by the thread--including the Thread
object itself--become eligible for reclamation by the garbage collector (if, of course, they are
not referenced elsewhere). Programmers are responsible for cleaning up system resources
(closing open files, disposing of graphics contexts, and so on) while a thread is terminating,
but no cleanup is required after a thread dies.

13.6 The Thread API


The following sections present a detailed analysis of the Java Thread API.

Constructors
The Thread class has seven different constructors:
public Thread();
public Thread(Runnable target);
public Thread(Runnable target, String name);
public Thread(String name);
public Thread(ThreadGroup group, Runnable target);
public Thread(ThreadGroup group, Runnable target, String name);
public Thread(ThreadGroup group, String name);
These constructors represent most of the combinations of three different parameters: thread
name, thread group, and a Runnable target object. To understand the constructors, you
must understand the three parameters:

www.arihantinfo.com
name is the (string) name to be assigned to the thread. If you fail to specify a name, the
system generates a unique name of the form Thread-N, where N is a unique integer.
target is the Runnable instance whose run() method is executed as the main method of the
thread.
group is the ThreadGroup to which this thread will be added. (The ThreadGroup class is
discussed in detail later in this chapter.)
Constructing a new thread does not begin the execution of that thread. To launch the
Thread object, you must invoke its start() method.
When creating a thread, the priority and daemon status of the new thread are set to the
same values as the thread from which the new thread was created.
CAUTION: Although it is possible to allocate a thread using new Thread(), it is not useful to
do so. When constructing a thread directly (without subclassing), the Thread object requires
a target Runnable object because the Thread class itself does not contain your application's
logic.

Naming
public final String getName();
public final void setName(String name);
Every Java thread has a name. The name can be set during construction or with the
setName() method. If you fail to specify a name during construction, the system generates a
unique name of the form Thread-N, where N is a unique integer; the name can be changed
later using setName().
The name of a thread can be retrieved using the getName() method.
Thread names are important because they provide the programmer with a useful way to
identify particular threads during debugging. You should name a thread in such a way that
you (or others) will find the name helpful in identifying the purpose or function of the thread
during debugging.

Starting and Stopping


To start and stop threads once you have created them, you need the following methods:
public void start();
public final void stop();
public final void stop(Throwable obj);
public void destroy();
To begin a new thread, create a new Thread object and call its start() method. An exception
is thrown if start() is called more than once on the same thread.

As discussed in "Thread States," earlier in this chapter, there are two main ways a thread
can terminate: The thread can return from its run() method, ending gracefully. Or the
thread can be terminated by the stop() or destroy() method.

When invoked on a thread, the stop() method causes that thread to terminate by throwing
an exception to the thread (a ThreadDeath exception). Calling stop() on a thread has the
same behavior as executing throw new ThreadDeath() within the thread, except that stop()
can also be called from other threads (whereas the throw statement affects only the current
thread).

To understand why stop() is implemented this way, consider what it means to stop a
running thread. Active threads are part of a running program, and each runnable thread is
in the middle of doing something. It is likely that each thread is consuming system
resources: file descriptors, graphics contexts, monitors (to be discussed later), and so on. If
www.arihantinfo.com
stopping a thread caused all activity on the thread to cease immediately, these resources
might not be cleaned up properly. The thread would not have a chance to close its open files
or release the monitors it has locked. If a thread were stopped at the wrong moment, it
would be unable to free these resources; this leads to potential problems for the virtual
machine (running out of open file descriptors, for example).

To provide for clean thread shutdown, the thread to be stopped is given an opportunity to
clean up its resources. A ThreadDeath exception is thrown to the thread, which percolates
up the thread's stack and through the exception handlers that are currently on the stack
(including finally blocks). Monitors are also released by this stack-unwinding process.
The following Listing shows how calling stop() on a running thread generates a ThreadDeath
exception.

Listing. Generating a ThreadDeath exception with stop().


class DyingThread extends Thread {
// main(), this class is an application
public static void main(String[] args) {
Thread t = new DyingThread(); // create the thread
t.start(); // start the thread
// wait for a while
try { Thread.sleep(100); } catch (InterruptedException e) { }
t.stop(); // now stop the thread
}
// run(), this class is also a Thread
public void run() {
int n = 0;
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream("big.txt"));
while (true) { // forever
ps.println("n == " + n++);
try { Thread.sleep(5); } catch (InterruptedException e) { }
}
} catch (ThreadDeath td) { // watch for the stop()
System.out.println("Cleaning up.");
ps.close(); // close the open file
// it is very important to rethrow the ThreadDeath
throw td;
} catch (IOException e) {
}
}
}
The DyingThread class has two parts. The main() method spawns a new DyingThread, waits
for a period of time, and then sends a stop() to the thread. The DyingThread run() method,
which is executed in the spawned thread, opens a file and periodically writes output to that
file. When the thread receives the stop(), it catches the ThreadDeath exception and closes
the open file. It then rethrows the ThreadDeath exception.
When you run the code shown in Listing 6.3, you see the following output:
Cleaning up.

www.arihantinfo.com
NOTE: Java provides a convenient mechanism for programmers to write "cleanup" code--
code that is executed when errors occur or when a program or thread terminates. (Cleanup
involves closing open files, disposing of graphics contexts, hiding windows, and so on.)
Exception handler catch and finally blocks are good locations for cleanup code.

Programmers use a variety of styles to write cleanup code. Some programmers place
cleanup code in catch(ThreadDeath td) exception handlers (as was done in the above
Listing). Others prefer to use catch(Throwable t) exception handlers. Both these methods are
good, but writing cleanup code in a finally block is the best solution for most situations. A
finally block is executed unconditionally, whether the exception handler exited because of a
thrown exception or not. If an exception was thrown, it is automatically rethrown after the
finally block has completed.
Although the ThreadDeath solution allows the application a high degree of flexibility, there
are problems. By catching the ThreadDeath exception, a thread can actually prevent stop()
from having the desired effect. The code to do this is trivial:
// prevent stop() from working
catch (ThreadDeath td) {
System.err.println("Just try to stop me. I'm invincible.");
// oh no, I've failed to rethrow td
}
Calling stop() is not sufficient to guarantee that a thread will end. This is a serious problem
for Java-enabled Web browsers; there is no guarantee that an applet will terminate when
stop() is invoked on a thread belonging to the applet.
The destroy() method is stronger than the stop() method. The destroy() method is designed to
terminate the thread without resorting to the ThreadDeath mechanism. The destroy()
method stops the thread immediately, without cleanup; any resources held by the thread
are not released.
CAUTION: The destroy() method is not implemented in the Java Development Kit, in all
versions up to and including 1.1. Calling this method results in a NoSuchMethodError
exception. Although there has been no comment about when this method will be
implemented, it is likely that it will not become available until JavaSoft can implement it in
a way that cleans up the dying thread's environment (locked monitors, pending I/O, and so
on).

13.7 Scheduling and Priority


Thread scheduling is defined as the mechanism used to determine how RUNNABLE threads
are allocated CPU time (that is, when they actually get to execute for a period of time on the
computer's CPU). In general, scheduling is a complex subject that uses terms such as pre-
emptive, round-robin scheduling, priority-based scheduling, time-sliced, and so on.

A thread-scheduling mechanism is either preemptive or nonpreemptive. With preemptive


scheduling, the thread scheduler preempts (pauses) a running thread to allow different
threads to execute. A nonpreemptive scheduler never interrupts a running thread; instead,
the nonpreemptive scheduler relies on the running thread to yield control of the CPU so that
other threads can execute. Under nonpreemptive scheduling, other threads may starve
(never get CPU time) if the running thread fails to yield.

Among thread schedulers classified as preemptive, there is a further classification. A pre-


emptive scheduler can be either time-sliced or nontime-sliced. With time-sliced scheduling,
the scheduler allocates a period of time for which each thread can use the CPU; when that
amount of time has elapsed, the scheduler preempts the thread and switches to a different
www.arihantinfo.com
thread. A nontime-sliced scheduler does not use elapsed time to determine when to preempt
a thread; it uses other criteria such as priority or I/O status.

Different operating systems and thread packages implement a variety of scheduling policies.
But Java is intended to be platform independent. The correctness of a Java program should
not depend on what platform the program is running on, so the designers of Java decided to
isolate the programmer from most platform dependencies by providing a single guarantee
about thread scheduling: The highest priority RUNNABLE thread is always selected for
execution above lower priority threads. (When multiple threads have equally high priorities,
only one of those threads is guaranteed to be executing.)

Java threads are guaranteed to be preemptive, but not time sliced. If a higher priority thread
(higher than the current thread) becomes RUNNABLE, the scheduler preempts the current
thread. However, if an equal or lower priority thread becomes RUNNABLE, there is no
guarantee that the new thread will ever be allocated CPU time until it becomes the highest
priority RUNNABLE thread.

NOTE: The current implementation of the Java VM uses different thread packages on
different platforms; thus, the behavior of the Java thread scheduler varies slightly from
platform to platform. It is best to check with your Java VM supplier to determine whether
the VM uses native threads and whether the platform's native threads are time sliced (some
native threading packages, most notably Solaris threads, are not time sliced).
Even though Java threads are not guaranteed to be time sliced, this should not be a
problem for the majority of Java applications and applets. Java threads release control of
the CPU when they become NOT RUNNABLE. If a thread is waiting for I/O, is sleeping, or is
waiting to enter a monitor, the thread scheduler will select a different thread for execution.
Generally, only threads that perform intensive numerical analysis (without I/O) will be a
problem. A thread would have to be coded like the following example to prevent other
threads from running (and such a thread would starve other threads only on some
platforms--on Windows NT, for example, other threads would still be allowed to run):
int i = 0;
while (true) {
i++;
}
There are a variety of techniques you can implement to prevent one thread from consuming
too much CPU time:
Don't write code such as while (true) { }. It is acceptable to have infinite loops--as long as
what takes place inside the loop involves I/O, sleep(), or interthread coordination (using the
wait() and notify() methods, discussed later in this chapter).
Occasionally call Thread.yield() when performing operations that are CPU intensive. The
yield() method allows the scheduler to spend time executing other threads.
Lower the priority of CPU-intensive threads. Threads with a lower priority run only when the
higher priority threads have nothing to do. For example, the Java garbage collector thread is
a low priority thread. Garbage collection takes place when there are no higher priority
threads that need the CPU; this way, garbage collection does not needlessly stall the system.
By using these techniques, your applications and applets will be well behaved on any Java
platform.

www.arihantinfo.com
13.7.1 Setting Thread Priority
public final static int MAX_PRIORITY = 10;
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final int getPriority();
public final void setPriority(int newPriority);

Every thread has a priority. When a thread is created, it inherits the priority of the thread
that created it. The priority can be adjusted subsequently using the setPriority() method.
The priority of a thread can be obtained using getPriority().
There are three symbolic constants defined in the Thread class that represent the range of
priority values: MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY. The priority values
range from 1 to 10, in increasing priority. An exception is thrown if you attempt to set
priority values outside this range.

13.7.2 Waking Up a Thread


public void interrupt();
public static boolean interrupted();
public boolean isInterrupted();
To send a wake-up message to a thread, call interrupt() on its Thread object. Calling
interrupt() causes an InterruptedException to be thrown in the thread and sets a flag that
can be checked by the running thread using the interrupted() or isInterrupted() method.
Calling Thread.interrupted() checks the interrupt status of the current thread and resets the
interrupt status to false (in versions before 1.1, the interrupt status is not reset). Calling
isInterrupted() on a Thread object (which can be other than the current thread) checks the
interrupt status of that thread but does not change the status.
The interrupt() method is useful in waking a thread from a blocking operation such as I/O,
wait(), or an attempt to enter a synchronized method.
CAUTION: The interrupt() method is not fully implemented in the JDK 1.0.x. Calling interrupt()
on a thread sets the interrupted flag but does not throw an InterruptedException or end a
blocking operation in the target thread; threads must check interrupted() to determine
whether the thread has been interrupted.
The interrupt() method is fully implemented in the Java virtual machine, version 1.1.

13.7.3 Suspending and Resuming Thread Execution


public final void suspend();
public final void resume();
Sometimes, it is necessary to pause a running thread. You can do so using the suspend()
method. Calling the suspend() method ensures that a thread will not be run. The resume()
method reverses the suspend() operation.
A call to suspend() puts the thread in the NOT RUNNABLE state. However, calling resume()
does not guarantee that the target thread will become RUNNABLE; other events may have
caused the thread to be NOT RUNNABLE (or DEAD).

4.7.4 Putting a Thread to Sleep


public static void sleep(long millisecond);
www.arihantinfo.com
public static void sleep(long millisecond, int nanosecond);
To pause the current thread for a specified period of time, call one of the varieties of the
sleep() method. For example, Thread.sleep(500) pauses the current thread for half a second,
during which time the thread is in the NOT RUNNABLE state. When the specified time
expires, the current thread again becomes RUNNABLE.
CAUTION: In the JDK versions 1.0.x and 1.1, the sleep(int millisecond, int nanosecond)
method uses the nanosecond parameter to round the millisecond parameter to the
nearest millisecond. Sleeping is not yet supported in nanosecond granularity.

www.arihantinfo.com
UNIT 14 : THE JAVA.UTIL PACKAGE

14.1Introduction
14.2The Java collection Advantage: An Overview
14.3A good API
14.4Other Capabilities
14.5Sorting a Collection
14.6Unmodifiable collection
14.7Synchronized Collection

14.1Introduction

JDK 1.2 introduces a new framework for collections of objects, called the Java Collections
Framework. "Oh no," you groan, "not another API, not another framework to learn!" But
wait, before you turn away, hear me out: the Collections framework is worth your effort and
will benefit your programming in many ways. Three big benefits come immediately to mind:

It dramatically increases the readability of your collections by providing a standard set of


interfaces to be used by many programmers in many applications.

It makes your code more flexible by allowing you to pass and return interfaces instead of
concrete classes, generalizing your code rather than locking it down.

It offers many specific implementations of the interfaces, allowing you to choose the
collection that is most fitting and offers the highest performance for your needs.

And that's just for starters.

Our tour of the framework will begin with an overview of the advantages it provides for
storing sets of objects. As you'll soon discover, because your old workhorse friends
Hashtable and Vector support the new API, your programs will be uniform and concise --
something you and the developers accessing your code will certainly cheer about.

After our preliminary discussion, we'll dig deeper into the details.

14.2 The Java Collections advantage: An overview

Before Collections made its most welcome debut, the standard methods for grouping Java
objects were via the Array, the Vector, and the Hashtable. All three of these collections have
different methods and syntax for accessing members: Arrays use the square bracket ([])
symbols, Vector uses the elementAt method, and Hashtable uses get and put methods.
These differences have long led programmers down the path to inconsistency in
implementing their own collections -- some emulate the Vector access methods and some
emulate the Enumeration interface.

To further complicate matters, most of the Vector methods are marked as final; that is, you
cannot extend the Vector class to implement a similar sort of collection. We could create a

www.arihantinfo.com
collection class that looked like a Vector and acted like a Vector, but it couldn't be passed to
a method that takes a Vector as a parameter.

Finally, none of the collections (Array, Vector or Hashtable) implements a standard member
access interface. As programmers developed algorithms (like sorts) to manipulate
collections, a heated discourse erupted on what object to pass to the algorithm. Should you
pass an Array or a Vector? Should you implement both interfaces? Talk about duplication
and confusion.

Thankfully, the Java Collections Framework remedies these problems and offers a number
of advantages over using no framework or using the Vector and Hashtable:

• A usable set of collection interfaces

By implementing one of the basic interfaces -- Collection, Set, List, or Map -- you ensure
your class conforms to a common API and becomes more regular and easily understood. So,
whether you are implementing an SQL database, a color swatch matcher, or a remote chat
application, if you implement the Collection interface, the operations on your collection of
objects are well-known to your users. The standard interfaces also simplify the passing and
returning of collections to and from class methods and allow the methods to work on a
wider variety of collections.

• A basic set of collection implementations

In addition to the trusty Hashtable and Vector, which have been updated to implement the
Collection interfaces, new collection implementations have been added, including HashSet
and TreeSet, ArrayList and LinkedList, and HashMap and Map. Using an existing, common
implementation makes your code shorter and quicker to download. Also, using existing Core
Java code core ensures that any improvements to the base code will also improve the
performance of your code.

• Other useful enhancements

Each collection now returns an Iterator, an improved type of Enumeration that allows
element operations such as insertion and deletion. The Iterator is "fail-fast," which means
you get an exception if the list you're iterating is changed by another user. Also, list-based
collections such as Vector return a ListIterator that allow bi-directional iteration and
updating.

Several collections (TreeSet and TreeMap) implicitly support ordering. Use these classes to
maintain a sorted list with no effort. You can find the smallest and largest elements or
perform a binary search to improve the performance of large lists. You can sort other
collections by providing a collection-compare method (a Comparator object) or an object-
compare method (the Comparable interface).

Finally, a static class Collections provides unmodifiable (read-only) and synchronized


versions of existing collections. The unmodifiable classes are helpful to prevent unwanted
changes to a collection. The synchronized version of a collection is a necessity for
multithreaded programs.

The Java Collections Framework is part of Core Java and is contained in the
java.util.collections package of JDK 1.2. The framework is also available as a package for
JDK 1.1.

www.arihantinfo.com
Let us now look more closely at these advantages by exercising the Java Collections
Framework with some code of our own.

14.3 A good API

The first advantage of the Java Collections Framework is a consistent and regular API. The
API is codified in a basic set of interfaces, Collection, Set, List, or Map. The Collection
interface contains basic collection operations such as adding, removing, and tests for
membership (containment). Any implementation of a collection, whether it is one provided
by the Java Collections Framework or one of your own creations, will support one of these
interfaces. Because the Collections framework is regular and consistent, you will learn a
large portion of the frameworks simply by learning these interfaces.

Both Set and List implement the Collection interface. The Set interface is identical to the
Collection interface except for an additional method, toArray, which converts a Set to an
Object array. The List interface also implements the Collection interface, but provides many
accessors that use an integer index into the list. For instance, get, remove, and set all take
an integer that affects the indexed element in the list. The Map interface is not derived from
collection, but provides an interface similar to the methods in java.util.Hashtable. Keys are
used to put and get values. Each of these interfaces are described in following code
examples.

The following code segment demonstrates how to perform many Collection operations on
HashSet, a basic collection that implements the Set interface. A HashSet is simply a set that
doesn't allow duplicate elements and doesn't order or position its elements. The code shows
how you create a basic collection and add, remove, and test for elements. Because Vector
now supports the Collection interface, you can also execute this code on a vector, which you
can test by changing the HashSet declaration and constructor to a Vector.

import java.util.collections.*;
public class CollectionTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection Test" );

// Create a collection
HashSet collection = new HashSet();

// Adding
String dog1 = "Max", dog2 = "Bailey", dog3 = "Harriet";
collection.add( dog1 );
collection.add( dog2 );
collection.add( dog3 );

// Sizing
System.out.println( "Collection created" +
", size=" + collection.size() +
", isEmpty=" + collection.isEmpty() );

www.arihantinfo.com
// Containment
System.out.println( "Collection contains " + dog3 +
": " + collection.contains( dog3 ) );

// Iteration. Iterator supports hasNext, next, remove


System.out.println( "Collection iteration (unsorted):" );
Iterator iterator = collection.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );

// Removing
collection.remove( dog1 );
collection.clear();
}
}
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects
are stored in sorted, ascending order. Access and retrieval times are quite fast. Here is an
example that demonstrate a TreeSet.

import java.util.*;

class TreeSetDemo {

public static void main(String args[]) {

// Create a tree set

TreeSet ts = new TreeSet();

// Add elements to the tree set

ts.add("C");

ts.add("A");

ts.add("B");

ts.add("E");

ts.add("F");

ts.add("D");

System.out.println(ts);

Let's now build on our basic knowledge of collections and look at other interfaces and
implementations in the Java Collections Framework.

www.arihantinfo.com
Good concrete implementations

We have exercised the Collection interface on a concrete collection, the HashSet. Let's now
look at the complete set of concrete collection implementations provided in the Java Collections
framework.
Implementations
Hash Table Resizable Array Balanced Tree (Sorted) Linked List Legacy
Set HashSet * TreeSet * *
Interfaces List * ArrayList * LinkedList Vector
Map HashMap * TreeMap * Hashtable
Implementations marked with an asterix (*) make no sense or provide no compelling reason
to implement. For instance, providing a List interface to a Hash Table makes no sense
because there is no notion of order in a Hash Table. Similarly, there is no Map interface for
a Linked List because a list has no notion of table lookup.

Let's now exercise the List interface by operating on concrete implementations that
implement the List interface, the ArrayList, and the LinkedList. The code below is similar to
the previous example, but it performs many List operations.

import java.util.collections.*;
public class ListTest {
// Statics
public static void main( String [] args ) {
System.out.println( "List Test" );

// Create a collection
ArrayList list = new ArrayList();

// Adding
String [] toys = { "Shoe", "Ball", "Frisbee" };
list.addAll( Arrays.toList( toys ) );

// Sizing
System.out.println( "List created" +
", size=" + list.size() +
", isEmpty=" + list.isEmpty() );

// Iteration using indexes.


System.out.println( "List iteration (unsorted):" );
for ( int i = 0; i < list.size(); i++ )
System.out.println( " " + list.get( i ) );

// Reverse Iteration using ListIterator


System.out.println( "List iteration (reverse):" );
ListIterator iterator = list.listIterator( list.size() );
while ( iterator.hasPrevious() )
System.out.println( " " + iterator.previous() );

// Removing

www.arihantinfo.com
list.remove( 0 );
list.clear();
}
}

As with the first example, it's simple to swap out one implementation for another. You can
use a LinkedList instead of an ArrayList simply by changing the line with the ArrayList
constructor. Similarly, you can use a Vector, which now supports the List interface.

When deciding between these two implementations, you should consider whether the list is
volatile (grows and shrinks often) and whether access is random or ordered. My own tests
have shown that the ArrayList generally outperforms the LinkedList and the new Vector.

Notice how we add elements to the list: we use the addAll method and the static method
Arrays.toList. This static method is one of the most useful utility methods in the Collections
framework because it allows any array to be viewed as a List. Now an array may be used
anywhere a Collection is needed.

Notice that I iterate through the list via an indexed accessor, get, and the ListIterator class.
In addition to reverse iteration, the ListIterator class allows you to add, remove, and set any
element in the list at the point addressed by the ListIterator. This approach is quite useful
for filtering or updating a list on an element-by-element basis.

Take one more example of LinkedList.

import java.util.*;

class LinkedListDemo {

public static void main(String args[]) {

// create a linked list

LinkedList ll = new LinkedList();

// add elements to the linked list

ll.add("F");

ll.add("B");

ll.add("D");

ll.add("E");

ll.add("C");

ll.addLast("Z");

ll.addFirst("A");

ll.add(1, "A2");

www.arihantinfo.com
System.out.println("Original contents of ll: " + ll);

// remove elements from the linked list

ll.remove("F");

ll.remove(2);

System.out.println("Contents of ll after deletion: "+ ll);

// remove first and last elements

ll.removeFirst();

ll.removeLast();

System.out.println("ll after deleting first and last: "+ ll);

// get and set a value

Object val = ll.get(2);

ll.set(2, (String) val + " Changed");

System.out.println("ll after change: " + ll);

The last basic interface in the Java Collections Framework is the Map. This interface is
implemented with two new concrete implementations, the TreeMap and the HashMap. The
TreeMap is a balanced tree implementation that sorts elements by the key.

Let's illustrate the use of the Map interface with a simple example that shows how to add,
query, and clear a collection. This example, which uses the HashMap class, is not much
different from how we used the Hashtable prior to the debut of the Collections framework.
Now, with the update of Hashtable to support the Map interface, you can swap out the line
that instantiates the HashMap and replace it with an instantiation of the Hashtable.
import com.sun.java.util.collections.*;
public class HashMapTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection HashMap Test" );

HashMap collection1 = new HashMap();

// Test the Collection interface


System.out.println( "Collection 1 created, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );

// Adding
collection1.put( new String( "Harriet" ), new String( "Bone" ) );
collection1.put( new String( "Bailey" ), new String( "Big Chair" ) );
collection1.put( new String( "Max" ), new String( "Tennis Ball" ) );
www.arihantinfo.com
System.out.println( "Collection 1 populated, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );

// Test Containment/Access
String key = new String( "Harriet" );
if ( collection1.containsKey( key ) )
System.out.println( "Collection 1 access, key=" + key + ", value=" +
(String) collection1.get( key ) );

// Test iteration of keys and values


Set keys = collection1.keySet();
System.out.println( "Collection 1 iteration (unsorted), collection contains keys:" );
Iterator iterator = keys.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );

collection1.clear();
System.out.println( "Collection 1 cleared, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );
}
}

One more example of HashMap class is

import java.util.*;

class HashMapDemo {

public static void main(String args[]) {

// Create a hash map

HashMap hm = new HashMap();

// Put elements to the map

hm.put("John Doe", new Double(3434.34));

hm.put("Tom Smith", new Double(123.22));

hm.put("Jane Baker", new Double(1378.00));

hm.put("Tod Hall", new Double(99.22));

hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries

Set set = hm.entrySet();

// Get an iterator

Iterator i = set.iterator();
www.arihantinfo.com
// Display elements

while(i.hasNext()) {

Map.Entry me = (Map.Entry)i.next();

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

System.out.println();

// Deposit 1000 into John Doe's account

double balance = ((Double)hm.get("John Doe")).doubleValue();

hm.put("John Doe", new Double(balance + 1000));

System.out.println("John Doe's new balance: " +

hm.get("John Doe"));

Output from this program is shown here

Todd Hall: 99.22

Ralph Smith: -19.08

John Doe: 3434.34

Jane Baker: 1378.0

Tom Smith: 123.22

John Doe’s current balance: 4434.34

The TreeMap Class

The TreeMap class implements the Map interface by using a tree. A TreeMap provides an
efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You
should note that, unlike a hash map, a tree map guarantees that ist elements will be sorted
in ascending key order.

The following program reworks the preceding example so that it uses TreeMap.

import java.util.*;
www.arihantinfo.com
class TreeMapDemo {

public static void main(String args[]) {

// Create a tree map

TreeMap tm = new TreeMap();

// Put elements to the map

tm.put("John Doe", new Double(3434.34));

tm.put("Tom Smith", new Double(123.22));

tm.put("Jane Baker", new Double(1378.00));

tm.put("Tod Hall", new Double(99.22));

tm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries

Set set = tm.entrySet();

// Get an iterator

Iterator i = set.iterator();

// Display elements

while(i.hasNext()) {

Map.Entry me = (Map.Entry)i.next();

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

System.out.println();

// Deposit 1000 into John Doe's account

double balance = ((Double)tm.get("John Doe")).doubleValue();

tm.put("John Doe", new Double(balance + 1000));

System.out.println("John Doe's new balance: " +

tm.get("John Doe"));

The following is the from this program:

www.arihantinfo.com
Jane Baker: 1378.0

John Doe: 3434.34

Ralph Smith: -19.08

Todd Hall: 99.22

Tom Smith: 123.22

John Doe’s current balance: 4434.34

We've covered most of the interfaces and implementations in the Java Collections
framework, and we're ready to check out some of the additional capabilities Collections
offers us.

14.4 Other capabilities

Many of the additional features such as sorting and synchronization are encapsulated in the
Collections and Arrays classes. These classes, which will appear throughout the following
discussion, provide static methods for acting on collections.

14.5 Sorting a collection

We'll begin by exploring sorting. Two of the concrete implementations in the Java
Collections Framework provide easy means to maintain a sorted collection: TreeSet and
TreeMap. In fact, these two classes implement the SortedSet and SortedMap interfaces,
which are similar to their unsorted counterparts except that they provide methods to access
first and last elements and portions of the sorted collections.

There are two basic techniques for maintaining a sorted collection. The first uses one of the
sorted collection classes and provides the collection with an object that implements a
comparison via the Comparator interface. For example, going back to our first code example,
we can sort our collection by creating a StringComparator and adding it to the end of the
code, as shown here:

// This class sorts two String objects.


class StringComparator implements Comparator {
public int compare( Object object1, Object object2 ) {
return ((String) object1).compareTo( (String) object2 );
}
}
Next, we need to change the collection from a HashSet (unsorted) to a HashMap (sorted with
our StringComparator by using the following constructor:

TreeSet collection = new TreeSet( new StringComparator() );

www.arihantinfo.com
Rerun the example and you should see that the iteration is performed in sorted order.
Because the collection is ordered, you should now be able to find the min and the max
elements using the static class Collections.

The second technique is to implement natural ordering of a class by making the class
implement the Comparable interface. This technique adds a single compareTo method to a
class, which then returns 0 for equal objects, less than 0 if the first parameter is less than
the second, or greater than 0 of the first parameter is greater than the second. In Java 1.2,
the String class (but not StringBuffer) implements the Comparable interface. Any
comparable object can be placed in a sorted collection, and the collection order is
maintained automatically by the collection.

You can also sort Lists by handing them to the Collections class. One static sort method
takes a single List parameter that specifies a naturally ordered class (one that implements
the Comparable interface). A second static sort method takes a Comparator object for other
classes that do not implement the Comparable interface.

14.6 Unmodifiable collections

The Collections class provides many static factory methods (like


Collection.unmodifiableCollection and Collection.unmodifiableSet) for providing
unmodifiable or immutable collections. In fact, there is one method for each of the basic
collection interfaces. These methods are extremely useful to ensure that no one modifies
your collection. For instance, if you want to allow others to see your list but not change it,
you may implement a method that returns an unmodifiable view of your collection. Here's
an example:

List getUnmodifieableView() {
return Collections.unmodifableList( this );
}
This code will throw an UnsupportedOperationException, one of the RuntimeExceptions, if
someone tries to add or remove an element from the list.

Unfortunately, the unmodifiable views of a collection are of the same type as the original
collection, which hinders compile-time type checking. Although you may pass an
unmodifiable list to a method, by virtue of its type, the compiler has no way of ensuring the
collection is unchanged by the method. The unmodifiable collection is checked at runtime
for changes, but this is not quite as strong as compile-time checking and does not aid the
compiler in code optimization. Perhaps it's time for Java to emulate C++'s const and add
another modifier signifying immutability of any method, class, or object.

14.7 Synchronized collections

Finally, note that none of the concrete methods mentioned thus far support multithreaded
access in the manner that the Vectors and Hashtable did. In other words, none of the
methods on the concrete implementations are synchronized and none of the
implementations are thread-safe. You must support thread safety yourself.

www.arihantinfo.com
This may seem like a major omission, but in actuality it's not really a big problem. The
Collections class provides a synchronized version of each of the collection implementations.
You ensure thread safety by using the synchronized version of a collection and
synchronizing on the returned object. For example, we can ensure thread safety on a List by
using the following construct:

List dogs = synchronized List( new ArrayList() );


synchronized( list ) {
Iterator iterator = list.iterator(); // Must be in synchronized block
while ( iterator.hasNext() )
nonAtomicOperation( iterator.next() );
}
Many programmers are already using these types of synchronized blocks around Vectors
and Hashtables, so the new considerations aren't too significant.

www.arihantinfo.com

You might also like