Vous êtes sur la page 1sur 141

Lesson 1: Object-Oriented Programming Concepts

If you've never used an object-oriented programming language before, you'll need to learn a few basic
concepts before you can begin writing any code. This lesson will introduce you to objects, classes,
inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world,
while simultaneously providing an introduction to the syntax of the Java programming language.
Object-Oriented Programming Concepts:
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find many
examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color,
breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current
pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of objectoriented programming.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior.
An object stores its state in fields (variables in some programming languages) and exposes its behavior
through methods (functions in some programming languages). Methods operate on an object's internal state
and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring
all interaction to be performed through an object's methods is known as data encapsulation a fundamental
principle of object-oriented programming.
Consider a bicycle, for example:
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for
changing that state, the object remains in control of how the outside world is allowed to use it. For example, if
the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than
6.
Bundling code into individual software objects provides a number of benefits, including:
1.
Modularity: The source code for an object can be written and maintained independently of the source
code for other objects. Once created, an object can be easily passed around inside the system.
2.
Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
3.
Code re-use: If an object already exists (perhaps written by another software developer), you can use
that object in your program. This allows specialists to implement/test/debug complex, task-specific objects,
which you can then trust to run in your own code.

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

4.
Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply
remove it from your application and plug in a different object as its replacement. This is analogous to fixing
mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of
other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of
blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is
an instance of the class of objects known as bicycles. A class is the collection of individual objects.
What Is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain bikes,
road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed,
current pedal cadence, current gear). Yet each also defines additional features that make them
different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop
handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior
from other classes. In this example, Bicycle now becomes the superclass of MountainBike,
RoadBike, and TandemBike. In the Java programming language, each class is allowed to have
one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A hierarchy of bicycle classes.


The syntax for creating a subclass is simple. At the beginning of your class declaration, use
the extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle
{
// new fields and methods defining a mountain bike would go
here
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code
to focus exclusively on the features that make it unique. This makes code for your subclasses
easy to read. However, you must take care to properly document the state and behavior that
each superclass defines, since that code will not appear in the source file of each subclass.
What Is Data Abstraction and Encapsulation?
The wrapping up of data and function 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 functions, which are wrapped in the class, can access it. These functions provide the interface between
the objects data and the program. This insulation of the data from direct access by the program is called data
hiding or information hiding.
Abstraction refers to the act of representing essential features without including the background details or
explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,
weight and cost and functions to operate on these attributes. They encapsulate all the essential properties of

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

the objects that are to be created. The attributes are sometimes called data members because they hold
information. The functions that operate on these data are sometimes called methods or member functions.
Since the classes use the concept of data abstraction, they are known as abstract data types (ADT).
What Is Polymorphism?
Polymorphism is another important OOP concept. Polymorphism, a Greek term, and means the ability to take
more than one form. An operation may exhibit different behaviors in different instances. 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 strings, then the operation would produce a
third string by concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Polymorphism plays an important role in allowing objects having different internal structures to share the
same external interface. This means that a general class of operations may be accessed in the same manner
even thought specific actions associated with each operation may differ. Polymorphism is extensively used in
implementing inheritance.
What Is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic
binding (also known as late binding) means that the code associated with a given procedure call is not known
until the time of the call at run-time. It is associated with polymorphism and inheritance. A function call
associated with a polymorphic reference depends on the dynamic type of that reference.
Every object will have this procedure. Its algorithm is, however, unique to each object and so the draw
procedure will be redefined in each class that defines the object. At run-time, the code matching the object
under current reference will be called.
What Is Message passing?
An object-oriented program consists of set of objects that communicate with each other, The process of
programming in an object-oriented language, therefore, involves the following basic steps:
1. Creating classes that define objects and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people pass messages to one another. The concept of message passing makes it easier to talk about building
systems that directly model or simulate their real-world counterparts.
A message for an object is a request for execution of a procedure, and therefore will invoke a function
(procedure) in the receiving object that generates the desired result. Message passing involves specifying the
name of the object, the name of the function (message) and the information to be sent.
Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible
as long as it is alive.
What Is an Interface?
As you've already learned, objects define their interaction with the outside world through the methods that
they expose. Methods form the object's interface with the outside world; the buttons on the front of your
television set, for example, are the interface between you and the electrical wiring on the other side of its
plastic casing. You press the "power" button to turn the television on and off.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's
behavior, if specified as an interface, might appear as follows:

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to ACMEBicycle, for
example), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle
{
// remainder of this class implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide.
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time
by the compiler. If your class claims to implement an interface, all methods defined by that interface must
appear in its source code before the class will successfully compile.
Note: To actually compile the ACMEBicycle class, you'll need to add the public keyword to the
beginning of the implemented interface methods. You'll learn the reasons for this later in the lessons on
Classes and Objects and Interfaces and Inheritance.
What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of
packages as being similar to different folders on your computer. You might keep HTML pages in one folder,
images in another, and scripts or applications in yet another. Because software written in the Java
programming language can be composed of hundreds or thousands of individual classes, it makes sense to
keep things organized by placing related classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable for use in your own
applications. This library is known as the "Application Programming Interface", or "API" for short. Its
packages represent the tasks most commonly associated with general-purpose programming. For example, a
String object contains state and behavior for character strings; a File object allows a programmer to
easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the
creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else
related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you,
the programmer, to focus on the design of your particular application, rather than the infrastructure required to
make it work.
The Java Platform API Specification contains the complete listing for all packages, interfaces, classes,
fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and
bookmark it. As a programmer, it will become your single most important piece of reference
documentation.
Questions and Exercises:
1.
A software object's state is stored in ___.
2.
A software object's behavior is exposed through ___.
3.
Hiding internal data from the outside world and accessing it only through publicly exposed
methods is known as data ___.
4.
A blueprint for a software object is called a ___.

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

5.
Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.
6.
A collection of methods with no implementation is called an ___.
7.
A namespace that organizes classes and interfaces by functionality is called a ___.
8.
The term API stands for ___?
Exercises:
1.
Create new classes for each real-world object that you observed at the beginning of this trail.
Refer to the Bicycle class if you forget the required syntax.
2.
For each new class that you've created above, create an interface that defines its behavior, and
then require your class to implement it. Omit one or two methods and try compiling. What does the
error look like?
Lesson 2: Java Evolution
Java Features
The inventors of java wanted to design a language which could offer solutions to some of the problems
encountered in modern programming. They wanted the language to be not only reliable, portable and
distributed but also simple, compact and interactive. Sun Microsystems officially describes java with the
following attributes:
Java 2 features
Compiled and interpreted
Platform independent and portable
Object-Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High Performance
Dynamic and extensible

Additional features of J2SE 5.0


Ease of development
Scalability and performance
Monitoring and Manageability
Desktop Client
Core XML Support
Supplementary character support
JDBC Row set

Although the above appears to be a list of buzzwords, they aptly describe the full potential of the language,
these features have made java the first application language of the world wide web, java will also become the
premier language for general purpose stand- alone applications.
Complied and Interpreted
Usually a computer language is either compiled or interpreted. Java combines both these approaches thus
making java a two stage system. First, java compiler translates source code into what is known byte code
instructions. Byte codes are not machine instructions and therefore, in the second stage, java interpreter
generates machine code that can be directly executed by the machine that is running the java program. We can
thus say that java is both a compiled and an interpreted language.
Platform-Independent and Portable
The most significant contribution of java over other languages is its protability. Java programs can be easily
moved from one computer system to another, anywhere, and anytime. Chages and upgrades in operating
systems, processors and system resources will not force any changes in java programs. This is the reason why
java has become a popular language for programming on internet which is interconnects different kinds of
5

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

systems worldwide. We can download a java applet form a remote computer onto our local system via
internet and execute it locally. This makes the internet and extension of the users basic system providing
practically unlimited number of accessible applets and applications.
Java ensures portability in two ways, first, java compiler generates bytecode instructions that can be
implemented on any machine. Secondly, the size of the primitive data types are machine independent.
Object Oriented
Java is a true object oriented language. Almost everything in java is an object. All program code and data
reside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that we
can use in our programs by inheritance. The object model in java is simple and easy to extend.
Robust and Secure
Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and
run time checking for data types. It is designed as garbage collected language relieving the programmers
virtually all memory management problems. Java also incorporates the concept of exception handling which
captures series errors and eliminates any risk of crashing the system. Security becomes an important issue for
a language that is used for programming on internet. Threat of viruses and abuse of resources are everywhere.
Java systems not only verify all memory access but also ensure that no viruses are communicated with an
applet. The absence of pointers in java ensures that programs cannot gain access to memory locations without
proper authorization.
Distributed
Java is designed as distributed language for creating applications on networks. It has the ability to share both
data and programs. Java applications can open and access remote objects on internet as easily as they can do
in a local system. This enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
Simple, Small and Familiar
Java is a small and simple languae. Many features of C and C++ that are either redundant or sources of
unreliable code are not part of java for example, java does not use pointers, preprocessor header files, goto
statement and many others. It also eliminates operator overloading and multiple inheritance for more detailed
comparison of java with C and C++ , refer to sections 2.3
Familiarity is another striking features of java. To make the language look familiar to the exisiting
programmers, it was modeled on C and C++ languages. Java uses many constructs of C and C++ and
therefore, java code look like a C++ code. In fact, java is a simplified version of C++.
Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously.java supports multithreaded programs. This
means that we need not wait for the application to finish one task before beginning another, for example, we
can listen to an audio clip while scrolling a page and at the same time download and applet from a distant
computer. This feature greatly improves the interactive performance of graphics applications.
The Java runtime comes with tools that support multiprocess synchronization and construct smoothly
running interactive systems.
High Performance

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode,
according to sun, java speed is comparable to the native C/C++. Java architecture is also designed to reduce
overheads during runtime, further, the incorporation of multireading enhances the overall execution speed of
java programs.
Dynamic and Extensible
Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and
objects. Java can also determine the type of class through a query, making it possible to either dynamically
link or abort the program, depending on the response.
Java programs support functions written in other languages such as C and C++. These functions are known
as native methods, This facility enables the programmers to use the efficient functions available in these
languages. Native methods are linked dynamically at runtime.
Ease of Development
Java 2 standard Edition (j2se) 5.0 supports features, such as Generics, Enhanced for Loop, Autoboxing or
unboxing, typesafe enums, Varargs, Static import and Annotation. These features reduce the work of the
programmer by shifting the responsibility of creating the reusable code to the compiler. The resulting source
code is free bugs because the errors made by the compiler are less when compared to those made by
programmers. Thus, each of the linguistic features is designed to develop java programs in an easier way.
Scalability and Performance
J2SE 5.0 assures a significant increase in scalability and performance by improving the startup time and
reducing the amount of memory used in java 2 runtime environment. For example, the introduction of the
class, data sharing in the Hotspot java virtual Machine (JVM) improves the startup time by loading the core
classes from the jar files into a shared archive. Memory utilization is reduced by sharing data in the shared
archive among multiple JVM processes. In the earlier versions, the data was replicated in each JVM instance.
Monitoring and Manageability
Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Mangament platform
Extension, Monitoring and Mangement interface, and Java management Extension (JMX) to monitor and
mange java application. For example, java provides JVM Monitoring and Mangement API to track the
information at the application level and JVM level when deploying a large application. Java provides tools,
such as jconsole, jps, jstat, and jstatd to make use of monitoring and management facilities. For example, GUI
based tool called jconsole is used ot monitor the JVM.
Desktop Client
J2SE 5.0 provides enhanced features ot meet the requirements and challenges of the java desktop users. It
provides an improved swing look and feel called ocean. This feature is mainly used for developing graphics
applications that require open GL hardware acceleration.
Miscellaneous Features
In addition to the above features, J2SE 5.0 supports the features such as:
Core XML Support

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

J2SE 5.0 adds a powerful XML feature to the java platform. Java contains some special packages for
interface, to instantiate simple API for XML (SAX) and document object model (DOM) parsers to parse and
XML document, transform the content of an XML document, and validate and XML document against the
schema.
Supplementary Character Support
Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support. The supplementary
characters are encoded with UTF -16 values to generate a different character called,surrogate codepoint.

JDBC Rowset
Java supports JDBC rowset to send data in a tabular format between the remote components of a distributed
enterprise application. JDBC Rowset contains chacherowset and webrowset objects. The cached row set
object is a JavaBeans component which acts like a container. This object contains a number of rows of data,
which are retrieved from the database. The data stored in the cachedrowset can be directly accessed without
connecting to the database or any other data source/. The rows of data that are retrieved from the database can
be synchronized later. The webrowset object can operate without being connected to the database or data
source. The webrowset object uses XML format to read and write the rowset.
How Java Differs from C and C++
Although java was modeled after C and C++ languages, it differs from C and C++ in many ways. Java does
not incorporate a number of features available in C and C++. For the benefit of C and C++ programmers, we
point out here a few major differences between C/C++ and java languages.
Java and C
Java is a lot like C but the major difference between java and C is that java is an object oriented language and
has mechanism to define classes and objects. In an effort to build a simple and safe language, the java team
did not include some of the C features in java.

Java does not include the C unique statement keywords sizeof, and typedef.
Java does not contain the dat types struct and union.
Java does not define the ytpe modifiers keywords auto,e extern, register, signed, and unsigned .
Java does not support and explicit pointer type.
Java does not have a preprocessor and therefore we cannot use # define, #include and #ifder
statements.
Java requires that the functions with no arguments must be declared with empty parenthesis and not
with the void keyword as done in C.
Java adds new operators such as instance of and >>>.
Java adds labeled break and continue statements.
Java adds many features required for object oriented programming.

Java and C++

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Java is a ture object oriented language while C++ is basically C with object oriented extension, that is what
exactly the increment operator ++ indicates. C++ has maintained backward compatibility with C. it is
therefore possible to write and old style C program and run it successfully under C++. Java appear to be
similar to C++ when we consider only the extension part of C++. However, some object oriented features
of C++ make the C++ code exteremely difficult to follow and maintain.
Listed below are some major C++ features that were intentionally omitted from java or significant modified.

Java does not support operator overloading.


Java does not have tamplate classes as in C++.
Java does not support multiple inheritance of classes. This is accomplished using a new features
called interface.
Java does not support global variables. Every variable and method is declared withing a class and
forms part of that class.
Java does not use pointers.
Java has replaced the destructor functions with a finalize ( ) function.
There are no header files in java.

Java also adds some new features. While C++ is a superset of C, java is neither a superset nor a subset of C or
C++.

C++
C

Java

Overlapping of C, C++ and Java


Java and internet
Java is strongly associated with the internet because of the fact that the first application program written in
java was HotJava, a web browser to run applets on internet. Internet users can use java to create applet
programs and run them locally using a java-enabled browser such as HotJava. They can also use a javaenabled browser to download an applet located on a computer anywhere in the internet and run it on his local
computer. In fact, java applets have made the internet a true extension of the storage system of the local
computer.
Internet users can also set up their web sites containing Java applets that could be used by other remote users
of Internet. The ability of java applets to hitch a ride on the Information Superhighway has made Java a
unique programming language for the Internet. In fact, due to this, Java is popularly known as Internet
Language.
Java and World Wide Web

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

World Wide Web (WWW) is an open ended information retrieval system designed to be used in the
internets distributed environment. This system contains what are known as web pages that provide both
information and controls. Unlike a menu driven system where we are guided through a particular direction
using a decision tree structure, the web system is open ended and we can navigate to a new document in any
direction as shown in figure. This is made possible with the help of a language called hypertext markup
language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display
documents worldwide.

Web structure of information search


Java was meant to be used in distributed environments such as internet. Since, both the web and java share the
same philosophy; java could be easily incorporated into the web system. Before, java, the World Wide Web
was limited to the display of still images and texts. However, the incorporation of java into WebPages has
made it capable of unsporting animation, graphics, game, and a wide range of special effects. With the
support of java, the web has become more interactive and dynamic. on the other hand, with the support of
web, we can run a java program on someone elses computer across the internet.
Java communicates with a web page through a special tag called <APPLET>. Figure illustrates this process.
The figure shows the following communication steps:
1. The users send a request for and HTML document to the remote computers web server. The web
server is a program that accepts a request, processes the request and sends the required document.
2. The HTML document is returned to the users browser. The document contains the APPLET tag,
which identifies the applet.
3. The corresponding applet byutecode is transferred to the users computer. This bytecode had been
previously created by the java compiler using the java source code file for that applet.
4. The java enabled browser on the users computer interprets the bytecodes and provides output.
5. The users may have further interaction with the applet but with nor further downloading form the
providers web server. This is because the bytecode contains all the information necessary to interpret
the applet.
Web Browsers
As pointed out earlier, the internet is a vast sea of information represented in many formats and soared on
many computers. A large portion of the internet is organized as the World Wide Web which uses hypertext.
Web browsers are used to navigate through the information found on the net. They allow su to retrieved the

10

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

information spread across the internet and display it using the hypertext markup language (HTML). Examples
of web browsers, among others, include:
Hot java
Netscape navigator
Internet explorer
HTML documents and <APPLET> tags are discussed in detail inch:14.

Hot Java
Hot java is the web browser form sun Microsystems that enables the display of interactive content on the web,
using the java language. Hot java is written entirely in java and demonstrates the capabilities of the java
programming language.
When the java language was first developed and parted to the internet, no browsers were available that could
run java applets. Although we can view a web page that includes java applets with a regular browser, we will
not gain any of javas benefits. Hotjava is currently available for the SPARC/ Solaris platform as well as
Windows 95, windows NT and Windows XP. So far as being a web browser goes, it is nothing special and
does not offer anything special that most other web browsers dont offer. Its biggest draw is that it was the
first web browser to provide support for the java language, thus making the web more dynamic and
interactive.
Netscape Navigator
Netscape navigator, form Netscape Communications Corporation, is general purpose browser that can run
java applets. With versions available for window 95,NT, Solaris and apple macintosh, Netscape navigator is
one of the most widely used browsers today.
Internet Explorer
Internet explorer is another popular browser developed by Microsoft for windows 95, NT and XP
workstations. Both the navigator and explorer use tool bars, icons, menus and dialog boxes for easy
navigation. Explorer uses a just in time (JIT) compiler which greatly increases the speed of executions.
Hardware and Software Requirements
Java is cureently supported on windows 95, Windows NT, Window XP, Sun Solaris, Machintosh, and UNIX
machines. Though the programs and examples in this book were tested under windows 95, the most popular
operating system today, they can be implemented on any of the above systems. The minimum hardware and
software requirements for windows 95 version of java are as follows:
IBM compatible 486 system
Minimum of 8 MB memory
Windows 95 software
A windows compatible sound card, if necessary
A hard drive
A CD Rom Drive
A micorsoft compatible mouse
Java Support Systems

11

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

it is clear from the discussion we had up to now that the operation of java and java enabled browsers on the
internet requires a variety of support systems. Table list the systems necessary to supports java for delivering
information on the internet.
Table Java Support Systems
Support Systems
Internet connection
Web Server
Web Browser
HTML
APPLET Tag
Java Code
Bytecode

Description
Local computer should be connected to the internet.
A program that accepts requests for information and sends the required
documents.
A program that provides access to WWW and runs java applets.
A language for creating hypertext for the web
For placing java applets in HTML document
Java code is used for defining java applets
Complied java code that is referred to in the APPLET tag and transferred to the
user computer

Java Environment
Java environment includes a large number of development tools and hundreds of classes and methods. The
development tools are part of the system known as java development kit (JDK) and the classes and methods
are part of the java Standard Library (JSL) also known as the application programming interface (API)
Java Development
The java development kit comes with a collection of tools that are used for developing and running java
Programs. They include:
applet viewer (for Viewing Java applets)
Java C (java compiler)
Java (Java interpreter)
Java p ( java disassemble)
Java h (for C header files)
Java doc (for Creating HTML documents)
Jdb ( Java debugger)
Table lists these tools and their descriptions.
Table Java Development Tools
Tools
Description
Appletviewer
Enables us to run Java applets (without actually using a java compatible browser).
Java
Java interpreter, which runs applets and applications by reading and interpreating
bytecode files.
Javac
The java compiler which translate java sourcecode to bytecode files that the interpreter
can understand.
Java doc
Creates HTML format documentation from java source code files
Javah
Produces header files for use with native methods
Javap
Java disaaembler, which enables us to convert bytecode files into a program description.
Jdb
Java debugger, which helps us to find errors in our programs.

12

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The way these tools are applied to build and run application programs is illustrated in figure. To create a Java
program, we need to create a source code file using a text editor. The source code is then complied using the
java Compiler Javac and executed using the java interpreter java. The java debugger jdb is used to find errors,
if any, in the source code. a Compiled java program can be converted into a source code with the help of java
disassemble javap.
Text Editor

Java
Source
Code

javadoc

HTML
Files

javac

Java
Class
File

java

javah

Header
Files

jdb

Java
Program
Output

Process of building and running Java application programs

13

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 3 :Over view of Java Language


Introduction
Java is a general purpose, object oriented programming language. We can develop two types of java
programs:
Stand alone applications
Web applets
They are implemented as shown in figure. Stand alone applications are programs written in java to carry out
certain tasks on a stand alone local computer. In fact, java can be used to develop programs for all kinds of
applications, which earlier, were developed using languages like C and C++. As pointed out earlier, Hot java
itself is a java application program. Executing a stand alone java program involves two steps:
1. Compiling source code into bytecode using javac compiler.
2. Executing the bytecode program using java interpreter.
Applets are small java programs developed for internet applications. An applet located on a distant computer
(server) can be downloaded via internet and executed on a local computer (Client) using a java capable
browser. We can develop applets for doing everything from simple animated graphics to complex games and
utilities. Since applets are embedded in an HTML (Hypertext Markup Language) document and run inside a
web page, creating and running applets are more complex than creating and application.
Stand alone programs can read and write files and perform certain operations that applets cannot do. An
applet can only run within a Web browser.
Java
Source
Code

Java
Compiler

Applet
Type

Application
Type

Java enabled
Web Browser

Java
Interpreter

Output

Output

In this chapter, we shall consider some simple applications programs, which would demonstrate the
general structure of Java application programs. We shall also discuss here the general structure of java
application programs. We shall also discuss here the basic elements of java language and steps involved in
executing a java application program. Creation of applets will be discussed later in chapter 14.

14

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Simple Java Program


The best way to learn a new language is to write a few simple example programs and executed them. We
begin with a very simple program that prints a line of text as output.
class SampleOne
}
Public static viod main (String args[ ])
{
System.out.println ( Java is better than C++.);
}
}
Program 3.1 is perhaps the simplest of all java programs. Nevertheless, it brings out some salient features of
the language. Let us therefore discuss the program line by line and understand the unique features that
constitute a java program.
Class Declaration
The first line
class SampleOne
Declares a class, which is an object oriented construct. As statee earlier, java is a true object oriented language
and therefore, everything must be placed inside a class. Class is a keyword and declares that a new class
definition follows. SampleOne is a java identifier that specifies the name of the class to be defined.
Opening Brace
Every class definition in Java begins with an opening brace { and ends with a matching closing brace },
appearing in the last line in the example. This is similar to C++ class construct. (Note that a class definition in
C++ ends with a semicolon.)
The Main Line
The third line
public static void main (String args [ ] )
Defines a method named main. Conceptually, this is similar to the main ( ) function in C/C++. Every Java
application program must include the main ( ) method. This is the starting point for the interpreter to begin the
execution of the program. A Java application can have any number of classes but only one of them must
include a main method to initiate to initiate the execution. (Note that java applets will not use the main
method at all.)
The line contains a number of keywords, public, static and void.
public:

static:

15

The keyword Public is an access specified that declares the main method as
Unprotected and therefore making it accessible to all other classes. This is similar to the C++
Public modifier.
Next appears the keyword static. Which declares this method as one that belongs to the entire
class and not a part of any objects of the class. The main must always be declared as static

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

since the interpreter uses this method before any objects are created. More about static
methods and variables will be discussed later chapter 8.
The type modifier void states that the main method does not return any value (but simply
prints some text to the screen.)

void:

All parameters to a method are declared inside a pair of parentheses.here, String args
declares a parameter named args, which contains an arrays of objects of the class type String.
The Output Line
The only executable statement in the program is
System. Out. println( Java is better than C++.);
This is similar to the printf( ) statement of C or cout << construct of C++. Since java is a true object oriented
language, every method must be part of an object. The println method is a member of the out object, which is
a static data member of System class. This line prints the string
Java is better than C++.
To the screen. The method println always appends a new line character to the end of the string. This means
that any sunssequent output will start on a new line. Note the semicolon at the end of the statement. Every
java statement must end with a semicolon. ( Saving, compling, and executing a java program are discussed in
section 3.8).
More of Java
Assume that we would like to compute and print the square root of a number. A java program to aaaomplish
this is shown in program. This is a slightly complex program. This program when complied and run produces
the output.
Y = 2.23607
Program 3.2 A Java program with multiple statements
/*
*More Java statements
* This code comptes square root
*/
Import java.lang.Math:
class SquareRoot
{
public static void main (String args [ ])
{
double x = 5 ; // Declaration and initialization
double y :
// Simple declaration
Y = Math. Sqrt (x) ;
System.out.println ( y = + y );
}
}

16

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The structure of the program is similar to the previous one except that it has more number of statements. The
statement
double x = 5;
Declares a variable x and initializes it to the value 5 and the statement
double y;
Merely declares a variable y. note that both of them have been declared as double type variables. (double is a
data type used to represent a floating point number. Data type are discussed in the next chatper.)
The statement
Y = Math.sqrt (x) ;
Invokes the method sqrt of the Math class, computes square root of x and then assigns the result to the
variable y. the output statement
System.out.println( y = + y);
Displays the result on the screen as
Y = 2.23607
Note the use of + symbol, here, the + acts as the concatenation operator of two strings. The value of y is
converted into a string representation before concatenation.
Use of Math Functions
Note that the first statement in the program is
Import java.lang.Math:
The purpose of this statement is to instruct the interpreter to load the Math class from the pacakage lang.
(This statement is similar to # include statement in C.) Remember, Math clas contains the sqrt method
required in the program.
Comments
Java permits both the single line comments and multi line comments available in C++. The single line
comments begin with // and end at the end of the line as shown on the lines declaring x and y. For longer
comments, we can create long multi line comments by starting with a/* and ending with a */ as shows at the
beginning of the program.
An Application with Two Classes
Both the examples discussed above use only one class that contains the main method. A real life application
will generally require multiple classes. Program illustrates a java application with two classes.
class Room
{
float length;
float breadth;
void getdata (float a. float b)
{
17

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

length = a;
breadth = b;
}
}
class RoomArea
{
public static void main (String args [ ])
{
float area ;
room room1 = new Room ( ); // Creates an object room1
room1.getdata (14.10); // Assigns values to length and breadth
area = room1.length * room1. Breadth;
system.out.println (Area = + area);
}
}
Program defines two classes Room and RoomArea. The Room class defines two variables and one method
to assign values to these variables. The class RoomArea contains the main method that initiates the
execution.
The main method declares a local variable area and a Room type object room1 and then assigns values to
the data members of Room class by using the getdata method. Finally, it calculates the area and prints the
results. Note the use of dot operator to accesss the variables and methods of Room class. Classes and methods
are discussed in chapter 8. The use of the keyword new is explained later in this chatper.
Java Program Structure
As we have seen in the previous examples, a java program many contain many classes of which only one
class defines a main method. Classes contain data members and methods that operate on the data members of
the class. Methods may contain data type declarations and executable statements. To write a java program, we
first define classes and then put them together. A java program may contain one or more sections as shown in

18

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Documentation Section

Suggested

Package Statement

Optional

Import Statements

Optional

Interface Statements

Optional

Class Definitions

Main Method Class


{
Main Method Definition
}

Optional

Essential

Documentation Section
The documentation section comprises asset of comment lines giving the name of the program, the author and
other details, which the programmer would like to refer to at a later stage. Comments must explain why and
what of classes and how of algorithms. This would greatly help in maintain the program. In addition to the
two styles of comments discussed earlier, java also uses a third style of comment /** ..*/ known as
documentation comment. This form of comment is used for generation documentation automatically.
Package Statement
The first statement allowed in a java file is a package statement. This statement declares a package name and
informs the compiler that the classes defined here belong to this package. Example:
package student ;
The package statement is optional. That is, our classes do not have to be part of package. More about
packages will be discussed later on.
Import Statements
The next thing after a package statement (but before any class definitions) may be number of import
statements. This is similar to the #include statement in C. Example:
import student. Test;
This statement instructs the interpreter to load the test class contained in the package student using import
statements; we can have access to classes that are part of other named packages. More on import statements
later on.

19

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Interface Statement
An interface is like a class but includes a group of method declarations. This is also an optional section and is
used only when we wish to implement the multiple inheritance feature in the program. Interface is a new
concept in java and is discussed in detail later on.
Class Definitions
A java program may contain multiple class definitions. Classes are the primary and essential elements of java
program. These classes are used to map the objects of real world problems. The number of classes used
depends on the complexity of the problem.
Main Method Class
Since every java stand alone program requires a main method as its starting point, this class is the essential
part of a java program. A simple java program may contain only this part. The main method creates objects of
various classes and establishes communications between them. On reaching the end of main, the program
terminates and the control passes back to the operating system.
Java Token
A Java program is basically a collection of classes. A class is defined by a set of declaration statements and
methods containing executable statements (see figure). Most statements contain expressions, which describe
the actions carried out on data. Smallest individual units in a program are known tokens. The compiler
recognizes them for building up expressions and statements.
In simple terms, a java program is a collection of tokens, comments and white spaces. Java language
includes five types of tokens. They are:
Reserved Keywords
Identifiers
Literals
Operators
Separators
Java Character Set
The smallest units of java language are the characters used to write java tokens. These characters are defined
by the Unicode character set, an emerging standard that tires to create characters for a large number of scripts
worldwide.
The Unicode, is a 16-bit character coding system and currently supports more than 34000 defined characters
derived from 24 languages from America, Europe, Middle East, Africa and Asia (including India). However,
most of us use only the basic ASCII characters, which include letters, digits and punctuation marks,used in
normal English. We, therefore, have used only ASCII character set (a subset of UNICODE character set) in
developing the programs in this book.
Keywords
Keywords are an essential part of a language definition. They implement specific features of the language.
Java language has reserved 50 words as keywords. Table 3.1 lists these keywords. These keywords, combined
with operators and separators according to a syntax, form definition of the java language. Understanding the
meaning of all these words is important for java programmers.

20

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Since keywords have specific meaning in Java, we cannot use them as names of variables,classes,
methods and so on. All keywords are to be written in lower case letters. Since java is case sensitive one can
use these words as identifiers by changing one or more letters to upper case. However, it is a bad practice and
should be avoided.
Java Keywords
abstract assert
byte
class
do
Extendsfinal
for
import
long
private
short
switch
throws
volatile

case
const
double
goto
instance of
native
protected
static
synchronized
transient
while

Boolean
break
catch
continue
else
finally
float
if
int
new
public
strctfp
this
try

char
default
enum
implements
interface
package
return
super
throw
void

Note: We should also not attempt to use the Boolean values true and false or null as names in our programs.
Identifilers
Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects,
labels, packages and interfaces in a program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be descriptive
and easily read. Java developers have followed some naming converntions.
Names of all public methods and instance variables start with a leading lowercase letter.
Examples:
average
sum
When more than one words are used in a name,the second and subsequent words are marked with a
leading uppercase letters. Examples:
dayTemperature
firstDayOfMonth
totalMarks
All private and local variables use only lowercase letters combined with underscores. Examples:
length
batch_strength
21

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

All classes and interfaces start with a leading uppercase letter (and each subsequent word
Student
HelloJava
Vehicle
motoCycle
Variables that represent constant values use all uppercase letters and underscores between words,
Examples:
TOTAL
F_MAX
PRINCIPAL_AMOUNT
They are like symbolic constants in C.
It should be remembered that all these are conventions and not rules. We may follow our own conventions as
long as we do not break the basic rules of naming identifiers.
Literals
Literals 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:
Interger literals
Floating_Point literals
Character literals
String literals
Boolean literals
Each of them has a type associated with it. The type describes how the values behave and how they are
stored. We will discuss these in detail when we deal with data types and constants.
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.operators
are of many types and are considered in detail in chapter5.
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. Table 3.2 lists separators and their functions.
Table 3.2 Java Separators
Name
What it is used for
parentheses( )
Used to enclose parameters in method definition and invocation, also used for defining
precedence in expressions, containing expressions for flow control, and surrounding
cast types.
braces { }
Used to contain the values of automatically initialized arrays and to define a block of
code for classes, methods and local scopes
brackets [ ]
Used to declare array types and for dereferencing array values
semicolon;
Used to separate statements
comma,
Used to separate consecutive identifiers in a variable declaration, also used to chain
statement together inside a for statement
period.
Used to separate package names from sub-packages and classes; also used to separate a
variable or method from a reference variable.

22

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Compiling the Program


The compile the program, we must run the java Compiler javac, with the name of the source file on the
command line as shown below:
javac Test.java
If everything is OK, the javac compiler creates a file called Test.class containing the bytecodes of the
program. note that the compiler automatically names he bytecode file as
<classname> .class
Source Code

Java Compiler

Byte Code

Windows
Interpreter

ABC
Interpreter

Macintosh
Interpreter

Machine
Code

Machine
Code

Machine
Code

Window
Computer

ABC
Computer

Macintosh
Computer

Implementation of Java Program


Running the program
We need to use the java interpreter to run a stand alone program. At the command prompt, type
java
Test
Now, the interpreter looks for the main method in the program and begins execution form there. When
executed, our program displays the following:
Hello!
Welcome to the world of Java.
Let us learn Java.
Note that we simply type Test at the command line and not Test.class or Test.java
Machine Netural
The compiler converts the source code files into bytecode files. These codes are machine- independent and
therefore can be run on any machine. That is, a program compiled on an IBM machine will run on a
Machintosh machine.
Java interpreter reads the bytecode files and translates them into machine code for the specified
machine on which the java program is running. The interpreter is therefore specially written for each type of
machine. Figure illustrates this concept.

23

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Java Virtual Machine


All language compilers translate source code into machine code for a specific computer. Java compiler also
does the same thing. Then, how does java achieve architecture neutrality? The answer is that the java
compiler produces and intermedia code known as bytecode for a machine that does not exist. This machine is
called the java Virtual Machine and it exists only inside the computer memory. It is a simulated computer
within the computer and does all major functions of a real computer. Figure illustrates the process of
compiling a java program into bytecode which is also referred to as virtual machine code.

Java
Program

Java
Compiler

Virtual
Machine

Process of compilation
The virtual machine code is not machine specific. The machine specific code (known as machine code) is
generated by the java interpreter by acting as an intermediary between the virtual machine and the real
machine as show fig.3.7 .Remember that the interpreter is different for different machines.

Bytecode

Java
Interpreter

Machine
Code

Process of converting bytecode into machine code


Figure illustrates how java works on a typical computer. The java object framework (JavaAPI) acts as the
intermediary between the user programs and the virtual machine which in turn acts as the intermediary
between the operating system and the java object framework.
Command Line Arguments
There may be occasions when we may like our program to act in a particular way depending on the input
provided at the time of execution. This is achieved in java programs by using what are known as command
line arguments. Command line arguments are parameters that are supplied to the application program at the
time of invoking it for execution. It may be recalled that program 3.4 was invoked for execution of the
command line as follows:
java Test
Here, we have not supplied any command line arguments. Even if we supply arguments, the program does not
known what to do with them.
We can write Java programs that can receive and use the arguments provided in the command line. Recall
the signature of the main( ) method used in our earlier example programs:
Public static void main (String args[ ])
As pointed out earlier, args is declared as an array of strings (known as string objects). Any arguents
provided in the command line (at the time of execution) are passed to the array args as its elements. We can
simply access the array elements and use them in the program as we wish. For example, consider the
command line
java Test BASIC FORTRAN C++ java
This command line contains four arguments. These are assigned to the array args as follows:
BASIC
24

args [0]

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

FORTRAN
args [1]
C++
args [2]
JAVA
args [3]
The individual elements of an array are accessed by using an index or subscript like args[i]. The value of I
denotes the position of the elements inside the array. For example, args[2] denotes the third element and
represents C++. Note that Java subscripts begin with 0 and not 1.
Use of command line arguments
/*
*this program uses command line
* arguments as input .
*/
class ComLineTest
{
public static void main (string args [ ])
{
int count. i =0;
String string;
count = args.length;
System.out.println (Number of arguments = + count );
while (i < count)
{
String = args[ i ];
i= i + 1;
System.out.println(i+ : + Java is + string+ !);
}
}
}
Program illustrates the use of command line arguments. Compile and run the program with the command line
as follows:
java ComLineTest Simple Object_Oriented Distributed Robust
Secure Portable Multithreaded Dynamic
Upon execution, the command line arguments simple, object_Oriented, etc. are passed to the program through
the array args as discussed earlier. That is the element args[0] contains simple, args[1] contains
Object_Oriented, and so on. These elements are accessed using the loop variable i as and index like
name = args[i]
The index i is incremented using a while loop until all the arguments are accessed. The number of arguments
is obtained by statement
count = args.length ;
The output of the program would be as follows:
Number of arguents =8
1 : Java is simple!
2 : Java is Object_Oriented!
25

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

3
4
5
6
7
8

:
:
:
:
:
:

Java is Distributed!
Java is Robust!
Java is Secure!
Java is Portable!
Java is Multithreaded!
Java is Dynamic!

Note how the output statement concatenates the strings while printing.
Programming Style
Java is a freeform language. We need not have to indent any lines to make the program work properly. Java
system does not care where on the line e begin typing. While this may be a license for bad programming. We
should try to use this fact to our advantage for producing readable programs. Although several alternate styles
are possible, we should select one and try to use it with total consistency.
For example, the statement
System.out.println (Java is Wonderful!)
Can be written as
System.out.println
(Java is Wonderful!);
Or, even as
System
.
out.
println
(
Java is Wonderful!
);

26

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 4: Language Basics


Variables
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that
remain unchanged during the execution of a program, a variable may take different values at different times
during the execution of the program.
The Java programming language defines the following kinds of variables:
Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in
"non-static fields", that is, fields declared without the static keyword. Non-static fields are also
known as instance variables because their values are unique to each instance of a class (to each
object, in other words); the currentSpeed of one bicycle is independent from the
currentSpeed of another.
Class Variables (Static Fields) A class variable is any field declared with the static modifier;
this tells the compiler that there is exactly one copy of this variable in existence, regardless of how
many times the class has been instantiated. A field defining the number of gears for a particular kind
of bicycle could be marked as static since conceptually the same number of gears will apply to all
instances. The code static int numGears = 6; would create such a static field.
Additionally, the keyword final could be added to indicate that the number of gears will never
change.
Local Variables Similar to how an object stores its state in fields, a method will often store its
temporary state in local variables. The syntax for declaring a local variable is similar to declaring a
field (for example, int count = 0;). There is no special keyword designating a variable as local;
that determination comes entirely from the location in which the variable is declared which is
between the opening and closing braces of a method. As such, local variables are only visible to the
methods in which they are declared; they are not accessible from the rest of the class.
Parameters You've already seen examples of parameters, both in the Bicycle class and in the
main method of the "Hello World!" application. Recall that the signature for the main method is
public static void main(String[] args). Here, the args variable is the parameter to
this method. The important thing to remember is that parameters are always classified as "variables"
not "fields".
Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields
and variables. If we are talking about "fields in general" (excluding local variables and parameters), we may
simply say "fields". If the discussion applies to "all of the above", we may simply say "variables". If the
context calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate.
You may also occasionally see the term "member" used as well. A type's fields, methods, and nested types
are collectively called its members.
Naming
Every programming language has its own set of rules and conventions for the kinds of names that you're
allowed to use, and the Java programming language is no different. The rules and conventions for naming
your variables can be summarized as follows:
Variable names are case-sensitive. A variable's name can be any legal identifier an unlimitedlength sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the
underscore character "_". The convention, however, is to always begin your variable names with a
letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You
may find some situations where auto-generated names will contain the dollar sign, but your variable
names should always avoid using it. A similar convention exists for the underscore character; while
it's technically legal to begin your variable's name with "_", this practice is discouraged. White space
is not permitted.

27

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and

common sense) apply to this rule as well. When choosing a name for your variables, use full words
instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many
cases it will also make your code self-documenting; fields named cadence, speed, and gear, for
example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind
that the name you choose must not be a keyword or reserved word.
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists
of more than one word, capitalize the first letter of each subsequent word. The names gearRatio
and currentGear are prime examples of this convention. If your variable stores a constant value,
such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing
every letter and separating subsequent words with the underscore character. By convention, the
underscore character is never used elsewhere.
Primitive Data Types
The Java programming language is staticaly-typed, which means that all variables must first be declared
before they can be used. This involves stating the variable's type and name, as you've already seen:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of
"1". A variable's data type determines the values it may contain, plus the operations that may be performed on
it. In addition to int, the Java programming language supports seven other primitive data types. A primitive
type is predefined by the language and is named by a reserved keyword. Primitive values do not share state
with other primitive values. The eight primitive data types supported by the Java programming language are:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of 128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory
in large arrays, where the memory savings actually matters. They can also be used in place of int
where their limits help to clarify your code; the fact that a variable's range is limited can serve as a
form of documentation.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of 32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you
can use a short to save memory in large arrays, in situations where the memory savings actually
matters.
int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type
is generally the default choice unless there is a reason (like the above) to choose something else. This
data type will most likely be large enough for the numbers your program will use, but if you need a
wider range of values, use long instead.
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of 9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this
data type when you need a range of values wider than those provided by int.
float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is
beyond the scope of this discussion. As with the recommendations for byte and short, use a
float (instead of double) if you need to save memory in large arrays of floating point numbers
double: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal
values, this data type is generally the default choice. As mentioned above, this data type should never
be used for precise values, such as currency.
boolean: The boolean data type has only two possible values: true and false. Use this data
type for simple flags that track true/false conditions. This data type represents one bit of information,
but its "size" isn't something that's precisely defined.
char: The char data type is a single 16-bit Unicode character.
28

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In addition to the eight primitive data types listed above, the Java programming language also provides
special support for character strings via the java.lang.String class. Enclosing your character string within
double quotes will automatically create a new String object; for example, String s = "this is a
string";. String objects are immutable, which means that once created, their values cannot be changed.
The String class is not technically a primitive data type, but considering the special support given to it by
the language, you'll probably tend to think of it as such. You'll learn more about the String class later on.
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized
will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null,
depending on the data type. Relying on such default values, however, is generally considered bad
programming style.
The following chart summarizes the default values for the above data types.
Data Type

Default Value (for fields)

byte

short

int

long

0L

float

0.0f

double

0.0d

char

'\u0000'

String (or any object) null


boolean
false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local
variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before
you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Declaration of Variables:
After designing suitable variable names, we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration decides the scope of the variable.
A variable must be declared before it is used in the program. The declaration statement defines the type of
variable. The general form of declaration of a variable is:
type variable1, variable2, . variable;
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid
declarations are:
int count;
float x , y;
Giving values to variables:
A variable must be given a valid after it has been declared but before it is used in an expression. This can be
achieved in two ways:
1. By using an assignment statement
2. By using a read statement

29

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

A simple method of giving value to a variable is through the assignment statement as follows:
VariableName = value;
For example:
initialValue = 0;
yes = x;
x = y = z = 0;
It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
type variableName = value;
For example,
int finalvalue = 100;
char yes=x;
Literals
You may have noticed that the new keyword isn't used when initializing a variable of a primitive type.
Primitive types are special data types built into the language; they are not objects created from a class. A
literal is the source code representation of a fixed value; literals are represented directly in your code without
requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal
number systems. Decimal is the number system you already use every day; it's based on 10 digits, numbered 0
through 9. The octal number system is base 8, consisting of the digits 0 through 7. The hexadecimal system is
base 16, whose digits are the numbers 0 through 9 and the letters A through F. For general-purpose
programming, the decimal system is likely to be the only number system you'll ever use. However, if you
need octal or hexadecimal, the following example shows the correct syntax. The prefix 0 indicates octal,
whereas 0x indicates hexadecimal.
int decVal = 26;
// The number 26, in decimal
int octVal = 032;
// The number 26, in octal
int hexVal = 0x1a;
// The number 26, in hexadecimal
The floating point types (float and double) can also be expressed using E or e (for scientific notation), F
or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;
Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file
system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape"
such as '\u0108' (capital C with circumflex), or "S\u00ED se\u00F1or" (S Seor in Spanish).
Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape
sequences may be used elsewhere in a program (such as in field names, for example), not just in char or
String literals.
The Java programming language also supports a few special escape sequences for char and String literals:
\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single
quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be assigned
to any variable, except variables of primitive types. There's little you can do with a null value beyond

30

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is
unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending
".class"; for example, String.class. This refers to the object (of type Class) that represents the type
itself.
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed. You've seen an example of arrays
already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of ten
elements
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in
the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at
index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each
value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray;
// declares an array of integers
anArray = new int[10];
anArray[0]
anArray[1]
anArray[2]
anArray[3]
anArray[4]
anArray[5]
anArray[6]
anArray[7]
anArray[8]
anArray[9]

=
=
=
=
=
=
=
=
=
=

100; // initialize first element


200; // initialize second element
300; // etc.
400;
500;
600;
700;
800;
900;
1000;

System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
31

// allocates memory for 10 integers

at
at
at
at
at
at
at

index
index
index
index
index
index
index

0:
1:
2:
3:
4:
5:
6:

"
"
"
"
"
"
"

+
+
+
+
+
+
+

anArray[0]);
anArray[1]);
anArray[2]);
anArray[3]);
anArray[4]);
anArray[5]);
anArray[6]);

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("Element at index 7: " + anArray[7]);


System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
}
}
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate
through each element of the array, rather than write each line individually as shown above. However, this
example clearly illustrates the array syntax. You'll learn about the various looping constructs (for, while,
and do-while) in the Control Flow section.
Declaring a Variable to Refer to an Array
The above program declares an Array with the following line of code:
int[] anArray;
// declares an array of integers
or
int anArray[];
Like declarations for variables of other types, an array declaration has two components: the array's type and
the array's name. An array's type is written as type[], where type is the data type of the contained
elements; the square brackets are special symbols indicating that this variable holds an array. The size of the
array is not part of its type (which is why the brackets are empty). An array's name can be anything you want,
provided that it follows the rules and conventions as previously discussed in the naming section. As with
variables of other types, the declaration does not actually create an array it simply tells the compiler that
this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
float anArrayOfFloats[]; // this form is discouraged
However, convention discourages this form; the brackets identify the array type and should appear with the
type designation.
Creating, Initializing, and Accessing an Array

32

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

One way to create an array is with the new operator. The next statement in the ArrayDemo program
allocates an array with enough memory for ten integer elements and assigns the array to the anArray
variable.
anArray = new int[10]; // create an array of integers
If this statement were missing, the compiler would print an error like the following, and compilation would
fail:
ArrayDemo.java:4: Variable anArray may not have been initialized.
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of
square brackets, such as String[][] names. Each element, therefore, must be accessed by a
corresponding number of index values.
In the Java programming language, a multidimensional array is simply an array whose components are
themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to
vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}
The output from this program is:
Mr. Smith
Ms. Jones
Finally, you can use the built-in length property to determine the size of any array. The code
System.out.println(anArray.length);
will print the array's size to standard output.
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into
another:
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int
arguments specify the starting position in the source array, the starting position in the destination array, and
the number of array elements to copy.

33

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word
"decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
The output from this program is:
Caffeine
Questions
1. The term "instance variable" is another name for ___.
2. The term "class variable" is another name for ___.
3. A local variable stores temporary state; it is declared inside a ___.
4. A variable declared within the opening and closing parenthesis of a method signature is called a ____.
5. What are the eight primitive data types supported by the Java programming language?
6. Character strings are represented by the class ___.
7. An ___ is a container object that holds a fixed number of values of a single type.
Exercises
1. Create a small program that defines some fields. Try creating some illegal field names and see what
kind of error the compiler produces. Use the naming rules and conventions as a guide.
2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values.
Try the same with a local variable and see what kind of compiler errors you can produce. Becoming
familiar with common compiler errors will make it easier to recognize bugs in your code.
Lesson 5: Operators
Now that you've learned how to declare and initialize variables, you probably want to know how to do
something with them. Learning the operators of the Java programming language is a good place to start.
Operators are special symbols that perform specific operations on one, two, or three operands, and then
return a result.
As we explore the operators of the Java programming language, it may be helpful for you to know ahead of
time which operators have the highest precedence. The operators in the following table are listed according
to precedence order. The closer to the top of the table an operator appears, the higher its precedence.
Operators with higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence appear in the same
expression, a rule must govern which is evaluated first. All binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right to left.
Operator Precedence
Operators

34

Precedence

postfix

expr++ expr--

unary

++expr --expr +expr -expr ~ !

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

multiplicative

* / %

additive

+ -

shift

<< >> >>>

relational

< > <= >= instanceof

equality

== !=

bitwise AND

&

bitwise exclusive OR ^
bitwise inclusive OR

logical AND

&&

logical OR

||

ternary

? :

assignment

= += -= *= /= %= &= ^= |= <<= >>= >>>=

In general-purpose programming, certain operators tend to appear more frequently than others; for example,
the assignment operator "=" is far more common than the unsigned right shift operator ">>>". With that in
mind, the following discussion focuses first on the operators that you're most likely to use on a regular
basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code
that you can compile and run. Studying its output will help reinforce what you've just learned.
Types of Operators
1. The Assignment Operator
One of the most common operators that you'll encounter is the simple assignment operator "=".
You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
2. The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their counterparts in
basic mathematics. The only symbol that might look new to you is "%", which divides one operand
by another and returns the remainder as its result.
+
addition operator (also used for String concatenation)
subtraction operator
*
multiplication operator
/
division operator
%
remainder operator
The following program, ArithmeticDemo, tests the arithmetic operators.

35

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

class ArithmeticDemo
{
public static void main (String[] args)
{
int result = 1 + 2; // result is now 3
System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4
System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}
You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated
string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
By the end of this program, the variable thirdString contains "This is a concatenated string.",
which gets printed to standard output.
3.
The Unary Operators
The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value of a
boolean.
+
Unary plus operator; indicates positive value (numbers are
positive without this, however)
Unary minus operator; negates an expression
++
Increment operator; increments a value by 1
-Decrement operator; decrements a value by 1
!
Logical complement operator; inverts the value
of a boolean
The following program, UnaryDemo, tests the unary operators:
class UnaryDemo
36

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
public static void main(String[] args)
{
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.
The code result++; and ++result; will both end in result being incremented by one.
The only difference is that the prefix version (++result) evaluates to the incremented value,
whereas the postfix version (result++) evaluates to the original value. If you are just
performing a simple increment/decrement, it doesn't really matter which version you choose. But
if you use this operator in part of a larger expression, the one that you choose may make a
significant difference.
The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo {
public static void main(String[] args)
{
int i = 3;
i++;
System.out.println(i);
// "4"
++i;
System.out.println(i);
// "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i);
// "7"
}
}
4.
The Relational Operators
The equality and relational operators determine if one operand is greater than, less than, equal to,
or not equal to another operand. The majority of these operators will probably look familiar to you
as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are
equal.
== equal to
!= not equal to
>
greater than
>= greater than or equal to
<
less than
<= less than or equal to
37

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The following program, ComparisonDemo, tests the comparison operators:


class ComparisonDemo
{
public static void main(String[] args)
{
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 ==
value2");
if(value1 != value2) System.out.println("value1 !=
value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <=
value2");
}
}
Output:
value1 != value2
value1 < value2
value1 <= value2
5.
The Logical Operators
The && and || operators perform Logical-AND and Logical-OR operations on two boolean
expressions. These operators exhibit "short-circuiting" behavior, which means that the second
operand is evaluated only if needed.
&& AND
|| OR
! NOT
The following program, ConditionalDemo1, tests these operators:
class ConditionalDemo1
{
public static void main(String args[])
{
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}
6. The Conditional Operator
The conditional operator is ?:, which can be thought of as shorthand for an if-then-else
statement (discussed in the Control Flow Statements section). This operator is also known as the
ternary operator because it uses three operands. In the following example, this operator should be
read as: "If some Condition is true, assign the value of value1 to result. Otherwise,
assign the value of value2 to result."
Syntax:
38

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Exp1 ? exp2 : exp3;


If the Exp1 is true then it evaluates exp2 otherwise exp3.
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2
{
public static void main(String[] args)
{
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Because someCondition is true, this program prints "1" to the screen. Use the ?: operator
instead of an if-then-else statement if it makes your code more readable; for example, when
the expressions are compact and without side-effects.
7. The Type Comparison Operator instanceof
The instanceof operator compares an object to a specified type. You can use it to test if an
object is an instance of a class, an instance of a subclass, or an instance of a class that implements
a particular interface.
The following program, InstanceofDemo, defines a parent class (named Parent), a simple
interface (named MyInterface), and a child class (named Child) that inherits from the parent
and implements the interface.
class InstanceofDemo
{
public static void main(String[] args)
{
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: " + (obj1
instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1
instanceof Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1
instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2
instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2
instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2
instanceof MyInterface));
}
}
class Parent{}
class Child extends Parent implements MyInterface{}
39

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

interface MyInterface{}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
When using the instanceof operator, keep in mind that null is not an instance of anything.
8. Bitwise and Bit Shift Operators
The Java programming language also provides operators that perform bitwise and bit shift
operations on integral types. The operators discussed in this section are less commonly used.
Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the
integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits;
applying this operator to a value whose bit pattern is "00000000" would change its pattern to
"11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the
number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>"
shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign
extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to
standard output.
class BitDemo
{
public static void main(String[] args)
{
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
Summary of Operators
The following quick reference summarizes the operators supported by the Java programming
language.
Simple Assignment Operator
=
Simple assignment operator
Arithmetic Operators
+
Addition operator (also used for String concatenation)
Subtraction operator
*
Multiplication operator
/
Division operator
%
Remainder operator

40

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Unary Operators
+
Unary plus operator; indicates positive value (numbers are
positive without this, however)
Unary minus operator; negates an expression
++
Increment operator; increments a value by 1
-Decrement operator; decrements a value by 1
!
Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
==
Equal to
!=
Not equal to
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
Conditional Operators
?:
Ternary (shorthand for if-then-else statement)
Logical Operators
&&
AND
||
OR
!
NOT
Type Comparison Operator
instanceof
Compares an object to a specified type
Bitwise and Bit Shift Operators
~
Unary bitwise complement
<<
Signed left shift
>>
Signed right shift
>>>
Unsigned right shift
&
Bitwise AND
^
Bitwise exclusive OR
|
Bitwise inclusive OR
Questions and Exercises
Questions
1. Consider the following code snippet.
arrayOfInts[j] > arrayOfInts[j+1]
Which operators does the code contain?
2. Consider the following code snippet.
int i = 10;
int n = i++%5;
a. What are the values of i and n after the code is executed?
b. What are the final values of i and n if instead of using the postfix increment operator (i++), you
use the prefix version (++i))?
3. To invert the value of a boolean, which operator would you use?
4. Which operator is used to compare two values, = or == ?
5. Explain the following code sample: result = someCondition ? value1 : value2;
Exercises
Change the following program to use compound assignments:
class ArithmeticDemo
{
public static void main (String[] args){

41

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

int result = 1 + 2; // result is now 3


System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4
System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}
In the following program, explain why the value "6" is printed twice in a row:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i);
// "4"
++i;
System.out.println(i);
// "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i);
// "7"
}
}

Expressions, Statements, and Blocks


Now that you understand variables and operators, it's time to learn about expressions, statements, and blocks.
Operators may be used in building expressions, which compute values; expressions are the core components
of statements; statements may be grouped into blocks.
Expressions
An expression is a construct made up of variables, operators, and method invocations, which are constructed
according to the syntax of the language, that evaluates to a single value. You've already seen examples of
expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if(value1 == value2) System.out.println("value1 == value2");
The data type of the value returned by an expression depends on the elements used in the expression. The
expression cadence = 0 returns an int because the assignment operator returns a value of the same data
type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an
expression can return other types of values as well, such as boolean or String.
The Java programming language allows you to construct compound expressions from various smaller
expressions as long as the data type required by one part of the expression matches the data type of the other.
Here's an example of a compound expression:
1 * 2 * 3
42

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In this particular example, the order in which the expression is evaluated is unimportant because the result of
multiplication is independent of order; the outcome is always the same, no matter in which order you apply
the multiplications. However, this is not true of all expressions. For example, the following expression gives
different results, depending on whether you perform the addition or the division operation first:
x + y / 100
// ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For
example, to make the previous expression unambiguous, you could write the following:
(x + y) / 100
// unambiguous, recommended
If you don't explicitly indicate the order for the operations to be performed, the order is determined by the
precedence assigned to the operators in use within the expression. Operators that have a higher precedence get
evaluated first. For example, the division operator has a higher precedence than does the addition operator.
Therefore, the following two statements are equivalent:
x + y / 100

x + (y / 100) // unambiguous, recommended


When writing compound expressions, be explicit and indicate with parentheses which operators should be
evaluated first. This practice makes code easier to read and to maintain.
Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of
execution. The following types of expressions can be made into a statement by terminating the expression
with a semicolon (;).
Assignment expressions
Any use of ++ or - Method invocations
Object creation expressions
Such statements are called expression statements. Here are some examples of expression statements.
aValue = 8933.234;
// assignment statement
aValue++;
// increment statement
System.out.println("Hello World!");
// method invocation statement
Bicycle myBike = new Bicycle(); // object creation statement
In addition to expression statements, there are two other kinds of statements: declaration statements and
control flow statements. A declaration statement declares a variable. You've seen many examples of
declaration statements already:
double aValue = 8933.234; //declaration statement
Finally, control flow statements regulate the order in which statements get executed. You'll learn about
control flow statements in the next section, Control Flow Statements
Blocks
A block is a group of zero or more statements between balanced braces and can be used anywhere a single
statement is allowed. The following example, BlockDemo, illustrates the use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
43

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Questions and Exercises: Expressions, Statements, and Blocks


Questions
1. Operators may be used in building ___, which compute values.
2. Expressions are the core components of ___.
3. Statements may be grouped into ___.
4. The following code snippet is an example of a ___ expression.
5. 1 * 2 * 3
6. Statements are roughly equivalent to sentences in natural languages, but instead of ending with a
period, a statement ends with a ___.
7. A block is a group of zero or more statements between balanced ___ and can be used anywhere a
single statement is allowed.

44

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 6: Control Flow Statements


The statements inside your source files are generally executed from top to bottom, in the order that they
appear. Control flow statements, however, break up the flow of execution by employing decision making,
looping, and branching, enabling your program to conditionally execute particular blocks of code. This
section describes the decision-making statements (if-then, if-then-else, switch), the looping
statements (for, while, do-while), and the branching statements (break, continue, return)
supported by the Java programming language.
The if-then and if-then-else Statements
The if-then Statement
The if-then statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test condition evaluates to true. The syntax is:
if (expression)
{
statement(s);
}
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to
false. You could use an if-then-else statement in the applyBrakes method to take some action
if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error
message stating that the bicycle has already stopped.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score
of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo
{
public static void main(String[] args)
{
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';

45

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
System.out.println("Grade = " + grade);
}
}
The output from the program is:
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements
are executed (grade = 'C';) and the remaining conditions are not evaluated.
The switch Statement
Unlike if-then and if-then-else, the switch statement allows for any number of possible
execution paths. A switch works with the byte, short, char, and int primitive data types. It also
works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap"
certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).
The following program, SwitchDemo, declares an int named month whose value represents a month
out of the year. The program displays the name of the month, based on the value of month, using the
switch statement.
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February");break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");
}
}
}
In this case, "August" is printed to standard output.
The body of a switch statement is known as a switch block. Any statement immediately contained by the
switch block may be labeled with one or more case or default labels. The switch statement
evaluates its expression and executes the appropriate case.
Of course, you could also implement the same thing with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
46

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment
call. You can decide which one to use based on readability and other factors. An if-then-else
statement can be used to make decisions based on ranges of values or conditions, whereas a switch
statement can make decisions based only on a single integer or enumerated value.
Another point of interest is the break statement after each case. Each break statement terminates the
enclosing switch statement. Control flow continues with the first statement following the switch block.
The break statements are necessary because without them, case statements fall through; that is, without
an explicit break, control will flow sequentially through subsequent case statements. The following
program, SwitchDemo2, illustrates why it might be useful to have case statements fall through:
class SwitchDemo2 {
public static void main(String[] args)
{
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if(((year % 4 == 0)&& !(year % 100 == 0))||(year%400 ==
0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
This is the output from the program.

47

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Number of Days = 29
echnically, the final break is not required because flow would fall out of the gswitch statement anyway.
However, we recommend using a break so that modifying the code is easier and less error-prone. The
default section handles all values that aren't explicitly handled by one of the case sections.
The while Loop
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:
while (expression)
{
statement(s);
}
The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. The while
statement continues testing the expression and executing its block until the expression evaluates to false.
Using the while statement to print the values from 1 through 10 can be accomplished as in the following
WhileDemo program:
class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The do while Loop
The Java programming language also provides a do-while statement, which can be expressed as follows:
do
{
statement(s);
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom
of the loop instead of the top. Therefore, the statements within the do block are always executed at least
once, as shown in the following DoWhileDemo program:
class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do
{
48

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("Count is: " + count);


count++;
} while (count <= 11);
}
}
The for Loop
The for loop provides a compact way to iterate over a range of values. Programmers often refer to it as the
"for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general
form of the for statement can be expressed as follows:
for (initialization; termination; increment)
{
statement(s);
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable
for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the numbers 1
through 10 to standard output:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends
from its declaration to the end of the block governed by the for statement, so it can be used in the
termination and increment expressions as well. If the variable that controls a for statement is not needed
outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are
often used to control for loops; declaring them within the initialization expression limits their life span and
reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
for ( ; ; ) {
// infinite loop
49

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

// your code goes here


}
The for statement also has another form designed for iteration through Collections and arrays This form is
sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and
easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers)
{
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array. The output from this
program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous
discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or
do-while loop, as shown in the following BreakDemo program:
class BreakDemo
{
public static void main(String[] args)
{
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,2000, 8, 622, 127
};
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++)
{
if (arrayOfInts[i] == searchfor)

50

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
foundIt = true;
break;
}
}
if (foundIt)
{
System.out.println("Found " + searchfor + " at index " + i);
}
else
{
System.out.println(searchfor + " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates
the for loop when that value is found. Control flow then transfers to the print statement at the end of the
program. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the inner most switch, for, while, or do-while statement,
but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is
similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array.
When the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo
{
public static void main(String[] args)
{
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt)
{
System.out.println("Found " + searchfor +" at " + i + ", " +
j);
51

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
else
{
System.out.println(searchfor+ " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label.
Control flow is transferred to the statement immediately following the labeled (terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled
form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the
loop. The following program, ContinueDemo , steps through a String, counting the occurences of the
letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds
to the next character. If it is a "p", the program increments the letter count.
class ContinueDemo
{
public static void main(String[] args)
{
String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++)
{
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When you run the
program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given label. The
following example program, ContinueWithLabelDemo, uses nested loops to search for a substring
within another string. Two nested loops are required: one to iterate over the substring and one to iterate over
the string being searched. The following program, ContinueWithLabelDemo, uses the labeled form of
continue to skip an iteration in the outer loop.
class ContinueWithLabelDemo
{
52

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public static void main(String[] args)


{
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++)
{
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0)
{
if (searchMe.charAt(j++)!= substring.charAt(k++))
{
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Here is the output from this program.
Found it
Labelled Loops
In Java, we can give a label to a block of statements. A label is any valid Java variable name. To give a label
to a loop, place it before the loop with a colon at the end. Example:
Loop1:
for(..)
{
..
..
}
A block of statements can be labeled as shown below:
Block1: {
..
..
Block2: {
.
.
}
}
We have seen that a simple break statement causes the control to jump outside the nearest loop and a simple
continue statement restarts the current loop. If we want to jump outside a nested loops or to continue a loop
that is outside the current one, then we may have to use the labeled break and labeled continue statements.
Example:
outer: for ( int m = 1; m <11; m++)
53

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
for( int n = 1; n<11; n++)
{
System.out.print( + m*n);
if (n == m)
continue outer;
}
}
Here, the continue statement terminates the inner loop when n = m and continues with the next iteration of the
outer loop.
Following program illustrates the use of break and continue statements.
class ContinueBreak
{
public static void main(String args[])
{
LOOP1 : for(int i = 1; i<100; i++)
{
System.out.println( );
if( i>=10); break;
for( int j = 1; j<100 ; j++)
{
System.out.print( * );
if( j == i)
continue LOOP1;
}
}
System.out.println(termination by break);
}
}
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
The return Statement
The last of the branching statements is the return statement. The return statement exits from the current
method, and control flow returns to where the method was invoked. The return statement has two forms:
one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that
calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a
method is declared void, use the form of return that doesn't return a value.
54

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

return;
The Classes and Objects lesson will cover everything you need to know about writing methods.
Questions and Exercises: Control Flow Statements
Questions
1. The most basic control flow statement supported by the Java programming language is the ___
statement.
2. The ___ statement allows for any number of possible execution paths.
3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the
loop.
4. How do you write an infinite loop using the for statement?
5. How do you write an infinite loop using the while statement?
Exercises
Consider the following code snippet.
if (aNumber >= 0)
if (aNumber == 0) System.out.println("first string");
else System.out.println("second string");
System.out.println("third string");
a. What output do you think the code will produce if aNumber is 3?
b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of
the program? Is it what you predicted? Explain why the output is what it is; in other words, what is
the control flow for the code snippet?
c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier to
understand.
d. Use braces, { and }, to further clarify the code.

55

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 7: Classes and Objects


Class
The introduction to object-oriented concepts in the lesson titled Object-oriented Programming
Concepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes
as subclasses. Here is sample code for a possible implementation of a Bicycle class, to give
you an overview of a class declaration. Subsequent sections of this lesson will back up and
explain class declarations step by step. For the moment, don't concern yourself with the details.
public class Bicycle
{
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear)
{
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue)
{
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
A class declaration for a MountainBike class that is a subclass of Bicycle might look like
this:
public class MountainBike extends Bicycle {
// the MountainBike subclass has one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
56

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

// the MountainBike subclass has one method


public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike inherits all the fields and methods of Bicycle and adds the field
seatHeight and a method to set it (mountain bikes have seats that can be moved up and down
as the terrain demands).
Declaring a Class
You've seen classes defined in the following way:
class classname
{
//field and method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides
for the life cycle of the objects created from the class: constructors for initializing new objects, declarations
for the fields that provide the state of the class and its objects, and methods to implement the behavior of the
class and its objects.
The preceding class declaration is a minimal oneit contains only those components of a class declaration
that are required. You can provide more information about the class, such as the name of its superclass,
whether it implements any interfaces, and so on, at the start of the class declaration. For example,
class MyClass extends MySuperClass implements YourInterface
{
//field, constructor, and method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface
interface.
You can also add modifiers like public or private at the very beginningso you can see that the opening line
of a class declaration can become quite complicated. The modifiers public and private, which determine what
other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance
will explain how and why you would use the extends and implements keywords in a class declaration. For the
moment you do not need to worry about these extra complications.
In general, class declarations can include these components, in order:
1. Modifiers such as public, private, and a number of others that you will encounter later.
2. The class name, with the initial letter capitalized by convention.
3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can
only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
5. The class body, surrounded by braces, {}.
Declaring Member Variables
There are several kinds of variables:
Member variables in a classthese are called fields.
Variables in a method or block of codethese are called local variables.
Variables in method declarationsthese are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;

57

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public int speed;


Field declarations are composed of three components, in order:
1. Zero or more modifiers, such as public or private.
2. The field's type.
3. The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The
public keyword identifies these fields as public members, accessible by any object that can access the class.
Example:
class rectangle
{
int length;
int width;
}
Access Modifiers
The first (left-most) modifier used lets you control what other classes have access to a member field. For the
moment, consider only public and private. Other access modifiers will be discussed later.
public modifierthe field is accessible from all classes.
private modifierthe field is accessible only within its own class.
In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly
accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by
adding public methods that obtain the field values for us:
public class Bicycle {
private int cadence;
private int gear;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear)
{
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public int getCadence()
{
return cadence;
}
public void setCadence(int newValue)
{
cadence = newValue;
}
public int getGear()
{
return gear;
}
public void setGear(int newValue)
{
gear = newValue;
}
public int getSpeed()

58

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
return speed;
}
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
}
Types
All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you can
use reference types, such as strings, arrays, or objects.
Variable Names
All variables, whether they are fields, local variables, or parameters, follow the same naming rules and
conventions that were covered in the Language Basics lesson, VariablesNaming .
In this lesson, be aware that the same naming rules and conventions are used for method and class names,
except that
the first letter of a class name should be capitalized, and
the first (or only) word in a method name should be a verb.
Defining Methods
Methods are declared inside the body of the class but immediately after the declaration of instance variable.
The general form of a method declaration is
modifier Return-type MethodName (parameter-list)
{
Method-body;
}
Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons)
{
//do the calculation here
}
The only required elements of a method declaration are the method's return type, name, a pair of parentheses,
(), and a body between braces, {}.
More generally, method declarations have 5 components, in order:
1. Modifierssuch as public, private, and others you will learn about later.
2. The return typethe data type of the value returned by the method, or void if the method does not
return a value.
3. The method namethe rules for field names apply to method names as well, but the convention is a
little different.
4. The parameter list in parenthesisa comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
5. The method body, enclosed between bracesthe method's code, including the declaration of local
variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson.

59

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Method Overloading
The Java programming language supports overloading methods, and Java can distinguish between methods
with different method parameters. This means that methods within a class can have the same name if they
have different parameter lists.
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so
on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each
methodfor example, drawString, drawInteger, drawFloat, and so on. In the Java programming
language, you can use the same name for all the drawing methods but pass a different argument list to each
method. Thus, the data drawing class might declare four methods named draw, each of which has a different
parameter list.
public class DataArtist {
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
Overloaded methods are differentiated by the number and the type of the arguments passed into the method.
In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they
require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments,
because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods
with the same signature even if they have a different return type.
Objects
A typical Java program creates many objects, which as you know, interact by invoking methods. Through
these object interactions, a program can carry out various tasks, such as implementing a GUI, running an
animation, or sending and receiving information over a network. Once an object has completed the work for
which it was created, its resources are recycled for use by other objects.
Creating Objects
As you know, an object in Java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also referred to as instantiating an object.
Objects in java are created using the new operator. The new operator creates an object of the specified class
and returns a reference to that object. Here is an example of creating an object of class Rectangle.
Rectangle rectOne
rectOne = new Rectangle();

//Declare the object


//instantiate the object

The first line declares a variable to hold the object reference and the second line actually assigns the object
reference to the of the variable. The rectone is now an object of the Rectangle class.

60

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Both statements can be combined into one as shown below:


Rectangle rectone= new Rectangle();

Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that
memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an
object, you are creating an "instance" of a class, therefore "instantiating" a class.
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable
of the appropriate type, like:
Point originOne = new Point(23, 94);
The reference returned by the new operator does not have to be assigned to a variable. It can also be used
directly in an expression. For example:
int height = new Rectangle().height;
Accessing Class Members
Once you've created an object, you probably want to use it for something. You may need to use the value of
one of its fields, change one of its fields, or call one of its methods to perform an action.
Accessing an Class variable
Class variables are accessed by their name. You may use a simple name for a variable within its own class.
For example, we can add a statement within the Rectangle class that prints the width and height:
System.out.println("Width and height are: " + width + ", " + height);
In this case, width and height are simple names.
Code that is outside the object's class must use an object reference or expression, followed by the dot (.)
operator, followed by a simple field name, as in:
ObjectName.variableName
For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So
to refer to the origin, width, and height fields within the Rectangle object named rectOne, the
CreateObjectDemo class must use the names rectOne.origin, rectOne.width, and
rectOne.height, respectively. The program uses two of these names to display the width and the
height of rectOne:
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
Attempting to use the simple names width and height from the code in the CreateObjectDemo class
doesn't make sense those fields exist only within an object and results in a compiler error.
Recall that the new operator returns a reference to an object. So you could use the value returned from new to
access a new object's fields:
int height = new Rectangle().height;
This statement creates a new Rectangle object and immediately gets its height. In essence, the statement
calculates the default height of a Rectangle. Note that after this statement has been executed, the program
no longer has a reference to the created Rectangle, because the program never stored the reference
anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.
The instance variable of the Rectangle class may be accessed and assigned values as follow:
61

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

rectone.width = 10;
rectone.height = 15;
Calling an class Methods
You also use an object reference to invoke an object's method. You append the method's simple name to the
object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any
arguments to the method. If the method does not require any arguments, use empty parentheses.
objectName.methodName(argumentList);
or
objectName.methodName();
The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to
change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:
System.out.println("Area of rectOne: " + rectOne.getArea());
...
rectTwo.getData(40, 72);
The first statement invokes rectOne's getArea() method and displays the results. The second line
invokes getData() method and then passes values 40 and 72 for the x and y parameters. This method then
assigns value to length and width variables respectively. The method is shown below:
void getData(int x,int y)
{
length = x;
width = y;
}
As with instance fields, objectName must be a name of an object. You can use a variable name, but you also
can use any expression that returns an object reference. The new operator returns an object reference, so you
can use the value returned from new to invoke a new object's methods:
new Rectangle(100, 50).getArea()
The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle
object. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to
compute the area of the new rectangle.
Application of class and object:
class Rectangle
{
int length,width;
void getData(int x, int y)
{
length = x;
width = y;
}
int rectArea()
{
int area = length * width;
return(area);
}
}
class rectArea
{
public static void main(String args[])
{
62

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

int area1,area2;
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
rect1.length = 15;
rect1.width = 10;
area1 = rect1.length * rect1.width;
rect2.getData(20,12);
area2 = rect2.rectArea();
System.out.println(Area1 = + area1);
System.out.println(Area2 = + area2);
}
}
Output would be:
Area1 = 150
Area2 = 240
Constructor
We know that all the objects that are created must be given initial values. We have done this earlier using two
approaches. The first approach uses the dot operator to access the instance variables and then assigns values
to them individually. The second approach takes the help of a method like getData to initialize each object
individually using statements like,
rect1.getData(15,10);
it would be simpler and more concise to initialize an object when it is first created. Java supports a special
type of method, called constructor, that enables an object to initialize itself when it is created.
Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even
void.
Initializing an Object
Here's the code for the Point class:
class Point {
int x = 0;
int y = 0;
Point(int a, int b) //constructor
{
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration uses the same
name as the class and it has no return type. The constructor in the Point class takes two integer arguments,
as declared by the code (int a, int b). The following statement provides 23 and 94 as values for those
arguments:
Point originOne = new Point(23, 94);
The result of executing this statement can be illustrated in the next figure:

63

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Here's the code for the Rectangle class, which contains one constructor:
class Rectangle
{
int width = 0;
int height = 0;
Rectangle(int x, int y)
{
width = y;
length = x;
}
// a method to calculate the are of rectangle
int rectArea()
{
return(length * width);
}
}
class RectangleArea
{
Public static void main(string args[])
{
Rectangle rect1 = new Rectangle(15,10); // calling constructor
int area1 = rect1.rectArea();
System.out.println(Area1 = + area1);
}
}
Output will be :
Area1 = 150
The Garbage Collector
Some object-oriented languages require that you keep track of all the objects you create and that you
explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and errorprone. The Java platform allows you to create as many objects as you want, and you don't have to worry about
destroying them. The Java runtime environment deletes objects when it determines that they are no longer
being used. This process is called garbage collection.
An object is eligible for garbage collection when there are no more references to that object. References that
are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an
object reference by setting the variable to the special value null. Remember that a program can have
multiple references to the same object; all references to an object must be dropped before the object is eligible
for garbage collection.

64

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The Java runtime environment has a garbage collector that periodically frees the memory used by objects that
are no longer referenced. The garbage collector does its job automatically when it determines that the time is
right.
the this Keyword
Within an instance method or a constructor, this is a reference to the current object the object whose
method or constructor is being called. You can refer to any member of the current object from within an
instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or
constructor parameter.
For example, the Point class was written like this
class Point {
public int x = 0;
public int y = 0;
//constructor
Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
class Point {
public int x = 0;
public int y = 0;
//constructor
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object's fields inside the constructor x is a local copy
of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a particular
method. There are two levels of access control:
At the top levelpublic, or package-private (no explicit modifier).
At the member levelpublic, private, protected, or package-private (no explicit
modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes
everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within
its own package (packages are named groups of related classesyou will learn about them in a later lesson.)
At the member level, you can also use the public modifier or no modifier (package-private) just as with
top-level classes, and with the same meaning. For members, there are two additional access modifiers:
private and protected. The private modifier specifies that the member can only be accessed in its
own class. The protected modifier specifies that the member can only be accessed within its own package
(as with package-private) and, in addition, by a subclass of its class in another package.
The following table shows the access to members permitted by each modifier.

65

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Modifier
public

Access Levels
Class Package Subclass World
Y

protected Y

no modifier

Y
N
N
N
The first data column indicates whether the class itself has access to the member defined by the access level.
As you can see, a class always has access to its own members. The second column indicates whether classes
in the same package as the class (regardless of their parentage) have access to the member. The third column
indicates whether subclasses of the class declared outside this package have access to the member. The
fourth column indicates whether all classes have access to the member.
Access levels affect you in two ways. First, when you use classes that come from another source, such as the
classes in the Java platform, access levels determine which members of those classes your own classes can
use. Second, when you write a class, you need to decide what access level every member variable and every
method in your class should have.
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the
four classes in this example and how they are related.
private

Understanding Instance and Class Members


In this section, we discuss the use of the static keyword to create fields and methods that belong to the
class, rather than to an instance of the class.
Static Variables
When a number of objects are created from the same class blueprint, they each have their own distinct copies
of instance variables. In the case of the Bicycle class, the instance variables are cadence, gear, and
speed. Each Bicycle object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the
static modifier. Fields that have the static modifier in their declaration are called static fields or class
variables. They are associated with the class, rather than with any object. Every instance of the class shares a
class variable, which is in one fixed location in memory. Any object can change the value of a class variable,
but class variables can also be manipulated without creating an instance of the class. Such members can be
defined as follows:
static int count;
For example, suppose you want to create a number of Bicycle objects and assign each a serial number,
beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance
variable. At the same time, you need a field to keep track of how many Bicycle objects have been created
so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to
the class as a whole. For this you need a class variable, numberOfBicycles, as follows:
public class Bicycle
{
private int cadence;
private int gear;
private int speed;
// add an instance variable for the object ID
private int id;
// add a class variable for the number of Bicycle objects
instantiated
private static int numberOfBicycles = 0;
}
66

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Class variables are referenced by the class name itself, as in


Bicycle.numberOfBicycles
This makes it clear that they are class variables.
Note: You can also refer to static fields with an object reference like
myBike.numberOfBicycles
but this is discouraged because it does not make it clear that they are class variables.
Static Methods
The Java programming language supports static methods as well as static variables. Static methods, which
have the static modifier in their declarations, should be invoked with the class name, without the need for
creating an instance of the class, as in
ClassName.methodName(args)
Note: You can also refer to static methods with an object reference like
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.
A common use for static methods is to access static fields. For example, we could add a static method to the
Bicycle class to access the numberOfBicycles static field:
static int getNumberOfBicycles() {
return numberOfBicycles;
}
We can define our own static methods as shown below:
class MathOperation
{
static float mul(float x, float y)
{
return(x*y);
}
static float divide (float x, float y)
{
return(x/y);
}
}
class MathApplication
{
public static void main(String args[])
{
float a = Mathoperation.mul(4.0,5.0);
float b = Mathoperation.divide(a,2.0);
System.out.println(b = + b);
}
}
Output will be:
B = 10.0
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.

67

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Class methods cannot access instance variables or instance methods directlythey must use an

object reference. Also, class methods cannot use the this keyword as there is no instance for
this to refer to.
Final variables
The static modifier, in combination with the final modifier, is also used to define constants. The
final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI,
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do
so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of
more than one word, the words are separated by an underscore (_).

68

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 8: Inheritance and Interface


Inheritance
In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can
be derived from other classes, thereby inheriting fields and methods from those classes.
Definitions:
A class that is derived from another class is called a subclass (also a derived class, extended class, or child
class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Excepting Object, which has no superclass, every class has one and only one direct superclass (single
inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and
ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes
in the inheritance chain stretching back to Object.
The idea of inheritance is simple but powerful: When you want to create a new class and there is already a
class that includes some of the code that you want, you can derive your new class from the existing class. In
doing this, you can reuse the fields and methods of the existing class without having to write them yourself.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are
not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked
from the subclass.
What You Can Do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass
is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the
parent. You can use the inherited members as is, replace them, hide them, or supplement them with new
members:
The inherited fields can be used directly, just like any other fields.
You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding it (not recommended).
You can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it.
You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
You can declare new methods in the subclass that are not in the superclass.
You can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
The following sections in this lesson will expand on these topics.
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the superclass has public
or protected methods for accessing its private fields, these can also be used by the subclass.
A nested class has access to all the private members of its enclosing classboth fields and methods.
Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private
members of the superclass.
The inheritance may take different forms:
Single inheritance(only one super class)
Multiple inheritance(several super classes)
69

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Hierarchical inheritance(one super class, many subclasses)


Multilevel inheritance(derived from derived class)
These forms are shown below:
A

(a) Single Inheritance

(b) Hierarchical Inheritance

C
C

(c) Multilevel inheritance

(d) Multiple inheritance

Defining a subclass
A subclass is defined as follows:
class subclasname entends superclassname
{
Variable declaration;
Method declaration;
}
The keyword extends signifies that the properties of the superclassname are extends to the subclassname.
The subclass will now contain its own variables and methods as well those of the super class. Application of
single inheritance:
class Room
{
int length;
int breadth;
Room(int x, int y)
l
Length = x;
breadth = y;
}
int area()
{
return( length * breadth);
}
}
class Bedroom extends Room
70

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
int height;
Bedroom(int x, int y, int z)
{
super(x,y);
// pass values to superclass
height = z;
}
int volume()
{
return(length * breadth * height);
}
}
class InherTest
{
public static void main(string args[])
{
Bedroom room1 = new Bedroom(14,12,10);
int area1 = room1.area();
// superclass method
int volume1 = room1.volume(); //baseclass method
System.out.println(Area1 = + area1);
System.out.println(Volume = + volume);
}
}
The output of program is:
Area1 = 168
Volume = 1680
The program defines a class Room and extends it to another class BedRoom. Note that the class BedRoom
defines its own data members and methods. The subclass BedRoom now includes three instance variables,
namely length, breadth and height and two methods, area and volume.
The constructor in the derived class uses the super keyword to pass values that are required by the vase
constructor. The statement
BedRoom room1 = new BedRoom(14,12,10);
Calls first the BedRoom constructor method, which in turn class the Room constructor method by using the
super keyword.
Finally, the object room1 of the subclass BedRoom calls the method area defined in the super class as well
as the method volume defined in the subclass itself.
Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a super class. Java
supports this concept and uses it intensively in building its class library. This concept allows us to build a
chian of classes as shown in figure.

71

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Grandfather

Father

Child

Superclass

Intermediate superclass

Subclass

The clas A serves as a base class for the derived class B which in turn serves as a base class for the derived
class C. the chain ABC is known as inheritance path.
A derived class with multilevel base classes is declared as follows.
class A
{
.
.
}
class B extends A // First level
{
.
.
}
class c extends B //
Second level
{
.
.
}
This process may be extended to any number of levels. The class C can inherit the members of both A and B
as shown in figure.
class C members
class B members
class A members

C contains B which contains A

72

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the hierarchical design of a program.
Many programming problems can be cast into a hierarchy where certain features of one level are shared by
many others below the level. As and example, figure shows a hierarchical classification of accounts in a
commercial bank. This is possible because all the accounts possess certain common features.
Account

Saving

Short

Fixed-deposit

Medium

Current

Long

Hierarchical classification of bank accounts

Overriding and Hiding Methods


Instance Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the superclass overrides the superclass's method.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is
"close enough" and then to modify behavior as needed. The overriding method has the same name, number
and type of parameters, and return type as the method it overrides. An overriding method can also return a
subtype of the type returned by the overridden method. This is called a covariant return type.
Class Methods
If a subclass defines a class method with the same signature as a class method in the superclass, the method in
the subclass hides the one in the superclass.
The distinction between hiding and overriding has important implications. The version of the overridden
method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked
depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains
two classes. The first is Animal, which contains one instance method and one class method:
public class Animal
{
public static void testClassMethod()
{
System.out.println("The class method in Animal.");
}
public void testInstanceMethod()
{
System.out.println("The instance method in Animal.");
}
}
73

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The second class, a subclass of Animal, is called Cat:


public class Cat extends Animal
{
public static void testClassMethod()
{
System.out.println("The class method in Cat.");
}
public void testInstanceMethod()
{
System.out.println("The instance method in Cat.");
}
public static void main(String[] args)
{
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
The Cat class overrides the instance method in Animal and hides the class method in Animal. The main
method in this class creates an instance of Cat and calls testClassMethod() on the class and
testInstanceMethod() on the instance.
The output from this program is as follows:
The class method in Animal.
The instance method in Cat.
As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version
of the overridden method that gets invoked is the one in the subclass.
class Alpha
{
int x;
Alpha(int x)
{
this.x = x;
}
void display()
//method defined
{
System.out.println(Alpha x = + x);
}
}
class Beta extends Alpha
{
int y;
Beta(int x,int y)
{
super(x);
this.y = y;
}
void display()
//method defined again
{
System.out.println(Alpha x = + x);

74

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println(Beta y = + y);
}
}
class OverrideTest
{
public static void main(string args[])
{
Beta b1 = new Beta(100,200);
b1.dispaly();
}
}
Output:
Alpha x = 100
Beta y = 200
Note: the method display() defined in the subclass is invoked.
The finalize() Method
The Object class provides a callback method, finalize(), that may be invoked on an object when it
becomes garbage. Object's implementation of finalize() does nothing - you can override
finalize() to do cleanup, such as freeing resources.
The finalize() method may be called automatically by the system, but when it is called, or even if it is
called, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, if
you don't close file descriptors in your code after performing I/O and you expect finalize() to close them
for you, you may run out of file descriptors.

Final Classes and Methods


You can declare some or all of a class's methods final. All methods and variables can be overridden by default
in subclass.You use the final keyword in a method declaration to indicate that the method cannot be
overridden by subclasses. The Object class does this - a number of its methods are final. Example:
final int SIZE = 100;
final void showstatus() { ..}
You might wish to make a method final if it has an implementation that should not be changed. For example,
you might want to make the getFirstPlayer method in this ChessAlgorithm class final:
class ChessAlgorithm {
final ChessPlayer getFirstPlayer() {
return ChessPlayer.WHITE;
}
}
Methods called from constructors should generally be declared final. If a constructor calls a non-final method,
a subclass may redefine that method with surprising or undesirable results.
Note that you can also declare an entire class final this prevents the class from being subclassed. This is
particularly useful, for example, when creating an immutable class like the String class.
Sometimes we may like to prevent a class being further subclasses for security reasons. A class that cannot be
subclassed is called final class. This is achieved by
final class AClass {}
final class BClass extends AClass {}
Abstract Methods and Classes

75

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Using making final we ensure that the method is not redefined in a subclass. That is, the method can never be
subclassed. Java allows us to do something that is exactly opposite to this. That is, we can indicate that a
method must always be redefined in a subclass, thus making overriding compulsory.
An abstract class is a class that is declared abstractit may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by
a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
abstract class GraphicObject
{
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, the subclass must also be declared abstract.
Note: All of the methods in an interface are implicitly abstract, so the abstract modifier is not used with
interface methods (it could beit's just not necessary).
Abstract Classes versus Interfaces
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain
implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial
implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only
abstract method declarations, it should be declared as an interface instead.
Questions
1. Consider the following two classes:
public class ClassA {
public void methodOne(int i) {
}
public void methodTwo(int i) {
}
public static void methodThree(int i) {
}
public static void methodFour(int i) {
}
}
public class ClassB extends ClassA {
public static void methodOne(int i) {
}
public void methodTwo(int i) {
}
public void methodThree(int i) {
}
public static void methodFour(int i) {
}
}
a. Which method overrides a method in the superclass?
b. Which method hides a method in the superclass?
c. What do the other methods do?

76

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Interface
There are a number of situations in software engineering when it is important for disparate groups of
programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to
write their code without any knowledge of how the other group's code is written. Generally speaking,
interfaces are such contracts.
For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through
city streets without a human operator. Automobile manufacturers write software (Java, of course) that
operates the automobilestop, start, accelerate, turn left, and so forth. Another industrial group, electronic
guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System)
position data and wireless transmission of traffic conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can
be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then
write software that invokes the methods described in the interface to command the car. Neither industrial
group needs to know how the other group's software is implemented. In fact, each group considers its
software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to
the published interface.
Interfaces in Java
Java does not support multiple inheritance. That is classes in java cannot have more than one superclass . for
instance, a definition like
class A extends B extends C
{

..
}
It is not permitted in java. Since C++ like implementation of multiple inheritances proves difficult and adds
complexity to the language, java provides an alternate approach known as interfaces to support the concept of
multiple inheritances. Although a java class cannot be a subclass of more than one superclass, it can
implement more than one interface, thereby enabling us to create classes that build upon other classes without
the problems created by multiple inheritances.
Defining interfaces
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a
major difference. The difference is that interfaces define only abstract methods and final fields. This means
that interfaces do not specify any code to implement these methods and data fields. Contains only constants.
Therefore it is the responsibility of the class thats implements an interface to define the code for
implementation of these methods.
The syntax of interface defination:
interface InterfaceName
{
variables declaration;
methods declaration;
}
Here, interface is the keyword and InterfaceName is any valid variable. Variables are declared as follows:
static final type VariableName = value;
Note that all variables are declared as constants.
77

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In the Java programming language, an interface is a reference type, similar to a class, that can contain only
constants, method declaration, and nested types. There are no method bodies. Interfaces cannot be
instantiatedthey can only be implemented by classes or extended by other interfaces.
Here is the example of an interface definition that contains two variables and one method:
interface Item
{
static final int code = 1001;
static final String name = Fan;
void display();
}
Note that the method declarations have no braces and are terminated with a semicolon.
To use an interface, you write a class that implements the interface. When an instantiable class implements an
interface, it provides a method body for each of the methods declared in the interface
Extending Interfaces
An interface can extend other interfaces, just as a class can extend or subclass another class. However,
whereas a class can extend only one other class, an interface can extend any number of interfaces. The
interface declaration includes a comma-separated list of all the interfaces that it extends.
interface name2 extends name1,name3
{
Body of name2
}
For example, we can put all constant in one interface and the methods in the other. This will enables us to use
the constants in classes where the methods are not required.
interface ItemConstants
{
int code = 1001;
string name = Fan;
}
interface Item extends itemConstants
{
void display();
}
The interface Item would inherit both the constants code and name into it. Note that the variables name and
code are declared like simple variables. It is allowed because all the variables in an interface are treated as
constants although the keyword final and static are not present.
The interface body contains method declarations for all the methods included in the interface. A method
declaration within an interface is followed by a semicolon, but no braces, because an interface does not
provide implementations for the methods declared within it. All methods declared in an interface are
implicitly public, so the public modifier can be omitted.
An interface can contain constant declarations in addition to method declarations. All constant values defined
in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.
Implementing an Interface
To declare a class that implements an interface, you include an implements clause in the class declaration.
Your class can implement more than one interface, so the implements keyword is followed by a commaseparated list of the interfaces implemented by the class.
By convention, the implements clause follows the extends clause, if there is one.
class classname implements interfacename
{
78

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Body of classname
}
Here the class classname implements the interface interfacename. A more general form of implementation
may look like this:
class classname extends superclass implements interface1, interface2
{
Body of classname
}
This shows class can extend another class while implementing interfaces. Implementation of interfaces as
class types is illustrated by following program. In this program, first we create an interface Area and
implements the same in two different classes, Rectangle and Circle. We create an instance of each class
using the new operator. Then we declare an object of type Area, the interface class. Now, we assign the
reference to the Rectangle object rect to area. When we call the compute method of area, the Rectangle
class is invoked. We repeat the same thing with the Circle object.
// InterfaceTest.java
interface Area
// interface defined
{
final static float pi = 3.14;
float compute (float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return(pi*x*y);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area;
area = react;
System.out.println(area of Rectangle = + area.compute(10,20));
area = cir;
System.out.println(area of Circle = + area.compute(10,0));
}
}
The output is as follows:
area of Rectangle = 200
area of Circle = 314

79

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

program: Implementing multiple inheritance


class Student
{
int rollnumber;
void gerNumber(int n)
{
rollNumber = n;
}
void putNumber()
{
System.out.println(Roll No : + rollNumber);
}
}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1 = m1;
part2 = m2;
}
void putMarks()
{
System.out.println( Marks obtained );
System.out.println( part1 = + part1);
System.out.println( part2 = + part2);
}
}
interface Sports
{
float sportWt = 6.0F;
void putWt();
}
class Results extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println(Sports Wt = + sportWt);
}
void display()
{
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putWt();
System.out.println(Total score = + total);
}
}

80

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

class Hybrid
{
public static void main(String args[])
{
Results student1 = new Results();
student1.getNumber(1234);
student1.getMarks(27.5F,33.0F);
student1.display();
}
}
output:
Roll No = 1234
Marks obtained
part1 = 27.5
part2 = 33
Sports Wt = 6
Total score = 66.5
Lesson 9: Numbers and Strings
Numbers
This section begins with a discussion of the Number class (in the java.lang package) and its subclasses.
In particular, this section talks about the situations where you would use instantiations of these classes rather
than the primitive data types. Additionally, this section talks about other classes you might need to work with
numbers, such as formatting or using mathematical functions to complement the operators built into the
language.
Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects. This section describes using the String class to create and manipulate strings.
It also compares the String and StringBuilder classes.
Numbers
This section begins with a discussion of the Number class in the java.lang package, its subclasses, and
the situations where you would use instantiations of these classes rather than the primitive number types.
Finally, the Math class in java.lang is discussed. It contains mathematical functions to complement the
operators built into the language. This class has methods for the trigonometric functions, exponential
functions, and so forth.
The Numbers Classes
When working with numbers, most of the time you use the primitive types in your code. For example:
int i = 500;
float gpa = 3.65f;
byte mask = 0xff;
There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper
classes for each of the primitive data types. These classes "wrap" the primitive in an object. Often, the
wrapping is done by the compilerif you use a primitive where an object is expected, the compiler boxes the
primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the
compiler unboxes the object for you.
Here is an example of boxing and unboxing:
Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);

81

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

When x and y are assigned integer values, the compiler boxes the integers because x and y are integer
objects. In the println() statement, x and y are unboxed so that they can be added as integers.
All of the numeric wrapper classes are subclasses of the abstract class Number:

There are three reasons that you might use a Number object rather than a primitive:
1. As an argument of a method that expects an object (often used when manipulating collections of
numbers).
2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper
and lower bounds of the data type.
3. To use class methods for converting values to and from other primitive types, for converting to and
from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).
As pointed out earlier, vectors cannot handle primitive data types like int, float, long, char, and double.
Primitive data types may be converted into object types by using the wrapper classes contained in the
java.lang package.
Wrapper classes for converting simple types
Simple type
wrapper class
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long
The wrapper classes have a number of unique methods for handling primitive data types and objects.
Converting primitive numbers to object numbers using constructor methods
Constructor calling
conversion action
Integer IntVal=new Integer(i);
primitive integer to Integer object
Float FloatVal=new Float(f);
primitive float to Float object
Double DoubleVal=new Double(d);
primitive double to Double object
Long LongVal=new Long(l);
primitive long to Long object
Converting object numbers to primitive numbers using typeValue() method
Method calling
conversion action
int j = IntVal.intValue();
object to primitive integer
float f=FloatVal.floatValue();
object to primitive float

82

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

long l=LongVal.longValue();
double d= DoubleVal.doubleValue();

object to primitive long


object to primitive double

Converting numbers to strings using to string() method


Method calling
conversion action
str= Integer.toString(i);
primitive integer to string
str=Float.toString(f);
primitive float to string
str=Double.toString(d);
primitive double to string
str=Long.toString(l);
primitive long to string
Converting string objects to numeric objects using the static method valueof()
method calling
conversion action
DoubleVal=Double.valueOf(str);
converts string to Double object
FloatVal=Float.valueOf(str);
converts string to Float object
IntVal=Integer.valueOf(str);
Converts string to Integer object
LongVal=Long.valueOf(str);
converts string to Long object
Converting numeric strings to primitive numbers using parsing methods
Method calling
conversion action
int i = Integer.parseInt(str);
converts string to primitive integer
long i = Long.parseLong(str);
converts string to primitive long
Mathematical functions and constants
The Math class includes two constants:
Math.E, which is the base of natural logarithms, and
Math.PI, which is the ratio of the circumference of a circle to its diameter.
The Math class also includes more than 40 static methods. The following table lists a number of the basic
methods.
Math Methods
Method

Description

abs(x)

Returns the absolute value of the argument.

ceil(x)

Returns the smallest integer that is greater than or equal to the argument. Returned
as a double.

floor(x)

Returns the largest integer that is less than or equal to the argument. Returned as a
double.

rint(d)

Returns the integer that is closest in value to the argument. Returned as a double.

round(d)

Returns the closest long or int, as indicated by the method's return type, to the
argument.

min(arg1, arg2)

Returns the smaller of the two arguments.

83

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

max(arg1, arg2)

Returns the larger of the two arguments.

exp(d)

Returns the base of the natural logarithms, e, to the power of the argument.

log(d)

Returns the natural logarithm of the argument.

pow(base,
exponent)

Returns the value of the first argument raised to the power of the second argument.

sqrt(d)

Returns the square root of the argument.

sin(d)

Returns the sine of the specified double value.

cos(d)

Returns the cosine of the specified double value.

tan(d)

Returns the tangent of the specified double value.

asin(d)

Returns the arcsine of the specified double value.

acos(d)

Returns the arccosine of the specified double value.

atan(d)

Returns the arctangent of the specified double value.

atan2(y, x)

Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and


returns theta.

Random Numbers
The random() method returns a randomly selected number between 0.0 and 1.0. The range includes 0.0 but
not 1.0. To get a number in a different range, you can perform arithmetic on the value returned by the random
method. For example, to generate an integer between 0 and 9, you would write:
int number = (int)(Math.random() * 10);
By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0.
Using Math.random works well when you need to generate a single random number. If you need to
generate a series of random numbers, you should create an instance of java.util.Random and invoke
methods on that object to generate numbers.
Array
Array is the most important thing in any programming language. By definition, array is the static memory
allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same
types. It also stores the values in memory at the fixed size. Multiple types of arrays are used in any
programming language such as: one - dimensional, two - dimensional or can say multi - dimensional.
Declaration of an array
int num[];
or
int num = new int[2];
Sometimes user declares an array and its size simultaneously. You may or may not be define the size in the
declaration time. Such as:
int num[] = {50,20,45,82,25,63};
In this program we will see how to declare and implementation. This program illustrates that the array
working way. This program takes the numbers present in the num[] array in unordered list and prints numbers
in ascending order. In this program the sort() function of the java.util.*; package is using to sort all the

84

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending
order by default. This function held the argument which is the array name num.
Here is the code of the program to arrange the numbers in ascending order.
import java.util.*;
class array
{
public static void main(String[] args)
{
int num[] = {50,20,45,82,25,63};
int i = num.length;
int i,j,t;
System.out.print("Given number : ");
for (i = 0;i < l;i++ )
{
System.out.print(" " + num[i]);
}
System.out.println("\n");
System.out.print("Accending order number : ");
Arrays.sort(num);
for(i = 0;i < l;i++)
{
System.out.print(" " + num[i]);
}
}
}
Output of the program:
C:\ jdk\bin >javac array.java
C:\ jdk\bin >java array
Given number : 50 20 45 82 25 63
Ascending order number : 20 25 45 50 63 82
Java Copy Array Example
In this tutorial, you will learn how to copy data from one array to another. Here, providing you an example
with code and its explanation to given below.
This is a program that follows one dimensional array. In this program, firstly we have to define a class
"CopyArray". Now, we take two integer type array like: array1[] and array2[]. The array1[] contains some
integer type values (2,3,4,5,8,9) and another is blank. After initializing this, now we get number of rows and
columns by using the array1.length. We use the 'for' loop statement for displaying and copying (array1[j] =
array2[j] ) the array.
Here is the code of this program:
class CopyArray
{
public static void main(String[] args)
{
int array1[]= {2,3,4,5,8,9};
int array2[] = new int[6];
System.out.println("array:");
System.out.print("[");
85

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

for (int i=0; i<array1.length; i++)


{
System.out.print(" "+array1[i]);
}
System.out.print("]");
System.out.println("\narray1:");
System.out.print("[");
for(int j=0; j<array1.length; j++)
{
array2[j] = array1[j];
System.out.print(" "+ array2[j]);
}
System.out.print("]");
}
}
charAt() Method
In this section, you will get the detailed explanation about the charAt() method of String class. We are going
for using charAt() method. You can see how to use the method by syntax. There is a section provided for
understanding the usage of the method practically.
Description of program:
Here, you will understand about the procedure of the charAt() method through the following java program.
This program reads a string as input through the keyboard. And first this shows the length of the string then
find the character at the 4th (mentioned as a parameter of the method) position of the string that is retrieved
by using charAt() method. This method takes a parameter that is the position of the string. The charAt()
method returns a character value for the character at the given position of the string.
Here is the code of this program:
import java.io.*;
class CharAt
{
public static void main(String[] args)
{
try
{
BufferedReader object=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String");
String s=object.readLine();
int len=s.length();
System.out.println(len);
char char1=s.charAt(4);
System.out.println(char1);
}
catch(Exception e){}
}
}
Output this program:
C:\ jdk\bin >java CharAt
Enter the String
roseindia
9
i
86

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

length() Method
In this section, you will learn how to use length() method of the String class. We are going to using length()
method. These method are illustration as follow here:
Description of program:
Here, we will know that how many character of length in String. First of all, we have to define class named
"StringLength". Inside of class we have to define method of class in main class. After that we create one
method which returns the integer type values. So we are using to length() method of the String class for the
purpose.
length() method : This method return the length of this string as an integer value.
Here is the the code of this program:
import java.io.*;
class StringLength
{
public static void main(String[] args)
.{
try
{
BufferedReader object=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Eneter string value:");
String s=object.readLine();
int len=s.length();
System.out.println(len);
}
catch(Exception e){}
}
}
Output this program:
C:\ jdk\bin >javac StringLength.java
C:\ jdk\bin >java StringLength
Eneter string value:
amar
4
toUpperCase() Method
In this section, you will learn how to use toUpperCase() method of the String class. We are going for using
toUpperCase() method. This method is explained as follows:
Description of program:
Here, you will see the procedure of converting letters of the string in uppercase letter. So, we are using
toUpperCase() method of the String class for the purpose.
The following program convert the string "india" into "INDIA" by using toUpperCase() method.
toUpperCase(): This method returns a string value.
Here is the code of this program:
class ConvertInUpperCase
{
public static void main(String args[])
{
String roseindia = "india";

87

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("String is : " + roseindia);


String upper = roseindia.toUpperCase();
System.out.println("String in uppercase letter: " + upper);
}
}
Output of program:
C:\ jdk\bin >javac ConvertInUpperCase.java
C:\ jdk\bin >java ConvertInUpperCase
String is : india
String in uppercase letter: INDIA
String Array
In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array
and the syntax for using in the program. This section provides you a simple java program which illustrates
about the string array in very efficient manner.
Program Description:
Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar",
"santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving
from the specified string array named roseindia. In this program all the string values are stored in the
roseindia string array at the declaration time.
Here is the code of this program:
class StringCharacter
{
static String[] roseindia={"chanan","tapan","Amar","santosh","deepak"};
public static void main(String args[])
{
for(int i=0;i<5;i++)
. {
System.out.println(roseindia[i]);
}
}
}
Output of program:
C:\ jdk\bin >javac StringCharacter.java
C:\ jdk\bin >java StringCharacter
chanan
tapan
Amar
santosh
deepak
Average of Array
In this section, we will learn how to get an average of array. For this, first of all we have to define a class
name "ArrayAverage" that has double type array to contain some values. Now we take a double type data
that calculates the average of array (result/nums.length). And finally it will display the result on the
command prompt with message by using the System.out.println().
Here is the code of this program
class ArrayAverage

88

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
public static void main(String[] args)
{
double nums[]={1.0,2.3,3.4,4.5,40.5};
double result=0.0;
int i=0;
for(i=0; i < nums.length; i++).
{
result=result + nums[i];
}
System.out.println("Average is =" + result/nums.length);
}
}
Matrix
A matrix is a collection of data in rows and columns format.
Description of program:
In this program we are going to implement a matrix. To make a program over the two dimensional array,
first of all we have to declare class named as MatrixExample that has one static method outputArray()
which takes integer type array and represents it. For displaying the matrix we need to its rows and column
by using the array.length method. Now, we use the for loop to print all the values stored in the array. At
last use the main() method inside which we are going to declare the values of the multidimensional array
which we are going to use. Call the outputArray() method inside the main method. The output will be
displayed to the user by println() method.
Here is the code of this Example:
class MatrixExample
{
public static void main(String[] args)
{
int array[][]= {{1,3,5},{2,4,6}};
System.out.println("Row size= " + array.length);
System.out.println("Column size = " + array[1].length);
outputArray(array);
}
public static void outputArray(int[][] array)
{
int rowSize = array.length;
int columnSize = array[0].length;
for(int i = 0; i <= 1; i++)
{
System.out.print("[");
for(int j = 0; j <= 2; j++)
{
System.out.print(" " + array[i][j]);
}
System.out.println(" ]");
}
System.out.println();
}
89

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
Sum of two Matrix
In this section, we are going to calculate the sum of two matrix and containing its rows and columns. See
below for better understanding to this.
In this program we are going to calculate the sum of two matrix. To make this program, we need to declare
two dimensional array of type integer. Firstly it calculates the length of the both the arrays. Now we need
to make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop the
rows and column will get divide. This process will be performed again for creating the second matrix.
After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by
using the for loop with array[i][j]+array1[i][j]. The output will be displayed by using the println() method.
Here is the code of this program:
class MatrixSum
{
public static void main(String[] args)
{
int array[][]= {{4,5,6},{6,8,9}};
int array1[][]= {{5,4,6},{5,6,7}};
System.out.println("Number of Row= " + array.length);
System.out.println("Number of Column= " + array[1].length);
int l= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < l; i++)
. {
for(int j = 0; j <= l; j++)
{
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int m= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < m; i++)
. {
for(int j = 0; j <= m; j++)
{
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
System.out.println("Addition of both matrix : ");
for(int i = 0; i < m; i++)
{
for(int j = 0; j <= m; j++)
{
System.out.print(" "+(array[i][j]+array1[i][j]));
}
System.out.println();
}
}
90

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
Output of program:
C:\ jdk\bin >javac MatrixSum.java
C:\ jdk\bin >java MatrixSum
Number of Row= 2
Number of Column= 3
Matrix 1 :
456
689
Matrix 2 :
546
567
Addition of both matrix :
9 9 12
11 14 16
Multiplication of two Matrix
This is a simple java program that teaches you for multiplying two matrix to each other. Here providing
you Java source code with understanding the Java developing application program. We are going to make a
simple program that will multiply two matrix. Two dimensional array represents the matrix.
Now, make this program, you have to declare two multidimensional array of type integer. Program uses
two for loops to get number of rows and columns by using the array1.length. After getting both matrix
then multiply to it. Both matrix will be multiplied to each other by using 'for' loop. So the output will be
displayed on the screen command prompt by using the println() method.
Here is the code of this program:
class MatrixMultiply{
public static void main(String[] args) {
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
}

91

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

for(int i = 0; i < x; i++) {


for(int j = 0; j < y-1; j++) {
for(int k = 0; k < y; k++){
array2[i][j] += array[i][k]*array1[k][j];
}
}
}
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array2[i][j]);
}
System.out.println();
}
}
}
Square Elements of Two Dimensional Array
This is a simple java program for implementing the two dimensional array program and its square. This
session provide you the best explanation with mathematical operation.
Description of progarm:
We are going to display the square of two matrix. Firstly, we have to define a class "SquareMatrix". Then
we take an integer type array that contains integer type values. After this, we use two 'for' loop that
denotes rows and columns of a matrix. After getting both the matrix with us we need to square both matrix.
When we go to square this array then we use "square[i][j] =square[i][j] * square[i][j]". So, the output
will be displayed on the screen command prompt by using the println() method.
Here is the code of this program
public class SquareMatrix
{
public static void main(String[] args)
{
int square[][]= {{1,3,5},{2,4,6}};
System.out.println("Your Original Matrix: ");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(square[i][j] + " ");
}
System.out.println();
}
for(int i = 0; i <= 1; i++)
{
for(int j = 0; j <= 2; j++)
{
square[i][j] = square[i][j] * square[i][j];
}
}
System.out.println("Matrix after changes: ");
for(int i = 0; i < 2; i++)
92

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
for(int j = 0; j < 3; j++)
{
System.out.print(square[i][j] + " ");
}
System.out.println();
}
}
}
Characters
Most of the time, if you are using a single character value, you will use the primitive char type. For
example:
char ch = 'a';
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; // an array of chars
There are times, however, when you need to use a char as an objectfor example, as a method argument
where an object is expected. The Java programming language provides a wrapper class that "wraps" the
char in a Character object for this purpose. An object of type Character contains a single field, whose
type is char. This Character class also offers a number of useful class (i.e., static) methods for
manipulating characters.
You can create a Character object with the Character constructor:
Character ch = new Character('a');
The Java compiler will also create a Character object for you under some circumstances. For example, if
you pass a primitive char into a method that expects an object, the compiler automatically converts the
char to a Character for you. This feature is called autoboxingor unboxing, if the conversion goes the
other way.
Here is an example of boxing,
Character ch = 'a'; // the primitive char 'a' is boxed into the Character
object ch
and here is an example of both boxing and unboxing,
Character test(Character c) {...} // method parameter and return type =
Character object
char c = test('x'); // primitive 'x' is boxed for method test, return is
unboxed to char 'c'
The following table lists some of the most useful methods in the Character class, but is not exhaustive. For
a complete listing of all methods in this class (there are more than 50), refer to the
java.lang.Character API specification.
Useful Methods in the Character Class
Method

Description

isLetter(char ch)
isDigit(char ch)

Determines whether the specified char value is a letter or a digit,


respectively.

isWhitespace(char
ch)

Determines whether the specified char value is white space.

isUpperCase(char ch)

Determines whether the specified char value is uppercase or lowercase,

93

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

isLowerCase(char ch)

respectively.

toUpperCase(char ch)
toLowerCase(char ch)

Returns the uppercase or lowercase form of the specified char value.

toString(char ch)

Returns a String object representing the specified character valuethat is,


a one-character string.

Escape Sequences
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The
following table shows the Java escape sequences:
Escape Sequences
Escape
Sequence

Description

\t

Insert a tab in the text at this point.

\b

Insert a backspace in the text at this point.

\n

Insert a newline in the text at this point.

\r

Insert a carriage return in the text at this point.

\f

Insert a formfeed in the text at this point.

\'

Insert a single quote character in the text at this point.

\"

Insert a double quote character in the text at this point.

\\

Insert a backslash character in the text at this point.

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For
example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes.
To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.
The Java platform provides the String class to create and manipulate strings.

Creating Strings
String manipulation is the most common part of many Java program. Strings represent a sequence of
characters. The easiest way to represent a sequence of characters to Java is by using a character array.
Example:
char charArray[] = new char[4];
charArray[0] = J;
charArray[1] = a;
94

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

charArray[2] = v;
charArray[3] = a;
Although character arrays have the advantage of being able to query their length, they themselves are not
good enough to support the range of operations we may like to perform on strings. For example, copying one
character array into another might require a lot of book keeping effort. Fortunately, Java is equipped to handle
these situations more efficiently.
In Java, strings are class objects and implemented using two classes, namely, string and stringBuffer. A
java string is an instantiated object of the String class.Java string as compared to C strings, are more reliable
and predictable. This is basically due to Cs lack of bounds checking. A Java string is not a character array
and is not NULL terminated. strings may be declared and created as follows:

String stringName:
StringName = new String (string);
Example:
String firstName;
firstName = new String (Anil) ;
These two statement may be combined as follows:
String firstName = new String (Anil) ;
Like arrays, it is possible to get the length of string using the length method of the String class.
int m = firstName.length ( ) ;
Note the use of parentheses here. Java strings can be concatenated using the + operator. Examples:
String fullName = name1 + name2;
String city1
= New + Delhi ;
where name1 and name2 are Java strings containing string constants. Another example is:
System.out.print1n(firstName +Kumar ) ;
String Arrays
We can also create and use arrays that contain strings. The statement
String itemArray [ ] = new String [3] ;
will create an itemArray of size 3 to hold three string constants. We can assign the strings to the itemArray
element by element using three different statements or more efficiently using a for loop.
String Methods
The string class defines a number of methods that allow us to accomplish a variety of string manipulation
tasks. Hear lists some of the most commonly used string methods, and their tasks.
s2=s1.toLowerCase;
s2=s1.toUpperCase;
s2=s1.replace(x,y);
s2=s1.trim();
s1.equals(s2)
s1.equalsIgnoreCase(s2)
s1.length()
s1.CharAt(n)
s1.compareTo(s2)
s1.concat(s2)
s1.substring(n)
s1.substring(n,m)

95

converts the string s1 to all lowercase


converts the string s1 to all Uppercase
Replace all appearances of x with y
remove white spaces at the beginning and end of the string
s1
returns true if s1 is equal to s2
returns true if s1=s2,ignoring the case of characters
gives the length of s1
gives nth character of s1
returns negative if s1<s2,positive if s1>s2, and zero if s1 is
equal s2
concatenates s1 and s2
gives substring starting from nth character
gives substring starting from nth character up to mth (not
ncluding mth)

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

String.ValueOf(p)
p.toString()
s1.indexOf(x)
s1.indexOf(x,n)
String.VauldeOf(Variable)

creates a string object of the parameter p (simple type of


object)
creates a string representation of the object p
gives the position of the first occurrence of x in the string s1
gives the position of x that occurs after nth position in the
string s1
converts the parameter value to string representation

String Length
Methods used to obtain information about an object are known as accessor methods. One accessor method
that you can use with strings is the length() method, which returns the number of characters contained in
the string object. After the following two lines of code have been executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
A palindrome is a word or sentence that is symmetricit is spelled the same forward and backward, ignoring
case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the
String method charAt(i), which returns the ith character in the string, counting from 0.
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an array of chars
for (int i = 0; i < len; i++)
{
tempCharArray[i] = palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++)
{
charArray[j] = tempCharArray[len - 1 - j];
}
String revPalindrome = new String(charArray);
System.out.println(revPalindrome);
}
}
Running the program produces this output:
doT saw I was toD
Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");
Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!"
which results in
96

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
Such a concatenation can be a mixture of any objects. For each object that is not a String, its
toString() method is called to convert it to a String.
Note: The Java programming language does not permit literal strings to span lines in source files, so you must
use the + concatenation operator at the end of each line in a multi-line string. For example,
String quote = "Now is the time for all good " +
"men to come to the aid of their country.";
Breaking strings between lines using the + concatenation operator is, once again, very common in print
statements.
Converting Between Numbers and Strings
Converting Strings to Numbers
Frequently, a program ends up with numeric data in a string objecta value entered by the user, for example.
The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float, Long, and
Short) each provide a class method named valueOf that converts a string to an object of that type. Here is
an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and
performs arithmetic operations on the values:
public class ValueOfDemo {
public static void main(String[] args) {
//this program requires two arguments on the command line
if (args.length == 2) {
//convert strings to numbers using wrapper class
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
//do some arithmetic
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("a / b = " + (a / b) );
System.out.println("a % b = " + (a % b) );
} else {
System.out.println("This program requires two command-line
arguments.");
}
}
}
The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:
a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5
Converting Numbers to Strings
97

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Sometimes you need to convert a number to a string because you need to operate on the value in its string
form. There are several easy ways to convert a number to a string:
int i;
String s1 = "" + i; //Concatenate "i" with an empty string;
//conversion is handled for you.
or
String s2 = String.valueOf(i); //The valueOf class method.
Each of the Number subclasses includes a class method, toString(), that will convert its primitive type
to a string. For example:
int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);
The ToStringDemo example uses the toString method to convert a number to a string. The program
then uses some string methods to compute the number of digits before and after the decimal point:
public class ToStringDemo
{
public static void main(String[] args)
{
double d = 858.48;
String s = Double.toString(d);
int dot = s.indexOf('.');
System.out.println(dot + " digits before decimal point.");
System.out.println( (s.length() - dot - 1)+" digits after decimal
point.");
}
}
The output of this program is:
3 digits before decimal point.
2 digits after decimal point.
Manipulating Characters in a String
The String class has a number of methods for examining the contents of strings, finding characters or
substrings within a string, changing case, and other tasks.
Other Methods for Manipulating Strings
Here are several other String methods for manipulating strings:
Other Methods in the String Class for Manipulating Strings
Method

Description

split(String regex)
split(String regex, int limit)

Searches for a match as specified by the string argument


(which contains a regular expression) and splits this string
into an array of strings accordingly. The optional integer
argument specifies the maximum size of the returned array.
Regular expressions are covered in the lesson titled
"Regular Expressions."

String trim()

Returns a copy of this string with leading and trailing white


space removed.

98

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

String toLowerCase()
String toUpperCase()

Returns a copy of this string converted to lowercase or


uppercase. If no conversions are necessary, these methods
return the original string.

An Example
The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate
different parts of a file name.
Note: The methods in the following Filename class don't do any error checking and assume that their
argument contains a full directory path and a filename with an extension. If these methods were production
code, they would verify that their arguments were properly constructed.
class Filename
{
String fullPath;
char pathSeparator, extensionSeparator;
Filename(String str, char sep, char ext)
{
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
String extension()
{
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
String filename()
// gets filename without extension
{
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
String path()
{
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
class FilenameDemo
{
public static void main(String[] args)
{
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH,'/', '.');
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
99

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

And here's the output from the program:


Extension = html
Filename = index
Path = /home/mem
As shown in the following figure, our extension method uses lastIndexOf to locate the last
occurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf to
extract the file name extension that is, the substring from the period to the end of the string. This code
assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns 1, and the substring method throws a StringIndexOutOfBoundsException.

Also, notice that the extension method uses dot + 1 as the argument to substring. If the period
character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one
larger than the largest index into the string (because indices start at 0). This is a legal argument to
substring because that method accepts an index equal to, but not greater than, the length of the string and
interprets it to mean "the end of the string."
StringBuffer Class
StringBuffer is a peer class of String. While string creates strings of fixed_length, stringBuffer Creates strings
of flexible length that can be modified in terms of both length and content. We can insert characters and
substrings in the middle of a string, or append another string to the end.
Method
Task
s1.setChartAt(n,x)
modifies the nth character to x
s1.append(s2)
appends the string s2 to s1 at the end
s1.insert(n,s2)
inserts the string s2 at the position n of the string s1
s1.serLength(n)
sets the length of the string s1 to n. if n<s1.length() s1 is truncated.if
n>s1.length() zeros are added to s1
Program illustrates the use of these methods:
class StringManipulation
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer(Object language);
System.out.println(Original String : + str);
// obtaining sring length
System.out.println(Length of string : + str.length());
//Accessing characters in a string
for(int I=0; i<str.length(); i++)
{
int p = I + 1;
System.out.println(Character at position : + p + is + str.charAt(i));
100

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
//inserting a string in the middle
String aString new String(str.toString());
int pos = aString.indexOf( language);
str.insert(pos, Oriented );
System.out.println(Modified string : + str);
// modified characters
str.setCharAr(6, -);
System.out.println(String now : + str);
//Appending a string at the end
str.append( improves security.);
System.out.println(Appended string : + str);
}
}
Output:
Original string : Object language
Length of string : 15
Character at position : 1 is O
Character at position : 2 is b
Character at position : 3 is j
Character at position : 4 is e
Character at position : 5 is c
Character at position : 6 is t
Character at position : 7 is
Character at position : 8 is l
Character at position : 9 is a
Character at position : 10 is n
Character at position : 11 is g
Character at position : 12 is u
Character at position : 13 is a
Character at position : 14 is g
Character at position : 15 is e
Modified string : Object Oriented language
String now : Object-Oriented language
Appended string : Object-Oriented language improves security.
Vectors
we have seen that J2SE 5.0 version supports the concept of variable arguments to methods. This feature can
also be achieved in java through the use of the vector class contained in the java.util package. This class can
be used to create a generic dynamic array known as vector that can hold objects of any type and any
number. The objects do not have to be homogeneous. Array can be easily implemented as vectors. Vectors
are created like arrays as follows:

101

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Vector intVect=new Vector(); //declaring without size


Vector list=new Vector(3);
//declaring with size
Note that a vector can be declared without specifying any size explicitly. A vector without size can
accommodate an unknown number of items. Even, when a size is specified , this can be overlooked and a
different number of items may be put into the vector. Remember, in contrast, an array must always have its
size specified.
Vectors possess a number of advantages over arrays.
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.
A major constraint in using vectors is that we cannot directly store simple data type in a vector; we can only
store objects. Therefore, we need to convert simple types to objects. This can be done using the wrapper
classes discussed in the next; section. The vector class supports a number of methods that can be used to
manipulate the vectors created.
Method call
task performed
list.addElement(item)
adds the item specified to the list at the end
list.elementAt(10)
gives the name of the 10th object
list.size()
gives the number of objects present
list.removeElement(item)
removes the specified item from the list
list.removeElementAt(n)
removes the item stored in the nth position of the list
list.removeAllElements()
removes all the elements in the list
list.copyInto(array)
copies all items from list to array
list.insertElementAt(item,n)
inserts the item at nth position
program illustrates the use of array, string and vector.
import java.util.*;
class LanguageVector
{
public static void main(String args[])
{
Vector list = new Vector();
int length = args.length;
for(int i = 0; i < length; i++)
{
list.addElement(args[i]);
}
list.insertElementAt(COBOL,2);
int size = list.size();
String listArray[] = new String[size];
list.copyInto(listArrary);
System.out.println(List of languages :);
for(int i = 0; i <size; i++)
{
System.out.println(listAray[i]);

102

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
}
}
command line input and output are:
C:\jdk\bin> java LanguageVector Ada BASIC C++ FORTRAN Java
List of languages
Ada
BASIC
C++
FORTRAN
Java

103

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 10: Packages


Packages are Javas way of grouping a variety of classes and interfaces together. The grouping usually done
according to functionality. In fact, packages act as containers for classes. Package is a concept similar to
class libraries in other languages.
By organizing our classes into packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two
different packages can have the same name. They may be referred by their fully qualified name, comprising
the package name and the class name.
3. Packages provide a way to hide classes thus preventing other programs or packages from accessing
classes that are meant for internal use only.
4. Packages also provide a way for separating design from coding. First we can design classes and decide
their relationships, and then we can implement the Java code needed for the methods. It is possible to change
the implementation of any method without affecting the rest of the design.
Package categories in Java
Java supports two types of packages as shown below in the hierarchy structure:

Build-In Packages( Java API Packages):


Java packages can be categorized in the hierarchy structure shown as:

Packages in the Java language begin with "java" as we can found in both hierarchy structure shown
above. Note that, the package "java" also has subpackages in which the package "awt" is further has a
subpackage called "event" that is imported to access classes and interfaces to handle the events fired on
the awt-component in a program. Thus the the expression to import the package is shown as"
import awt.event.*;
104

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lets understand these java packages shown in the table, from which you can access interfaces and classes.
Package Name Description
It contains essential classes that represent primitive data types (such as int & char) as
well as more complex classes, including numerics, strings, objects, compiler, runtime,
java.lang
security, and threads. This is the only package that is automatically imported into every
Java program.
This package provides classes to manage input and output streams to read data
java.io
from and write data to files, strings, and other sources.
It contains miscellaneous utility classes, including generic data structures, bit sets,
java.util
time, date, string manipulation, random number generation, system properties,
notification, and enumeration of data structures.
It provides an integrated set of classes to manage user interface components such
java.awt
as windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text
fields.
java.net

It provides classes for network support, including URLs, TCP sockets, UDP sockets, IP
addresses, and a binary-to-text converter.

java.applet

It enables the programmer to create applets through the Applet class. It also
provides several interfaces that connect an applet to its document and to resources for
playing audio.

Using system packages


There are two ways of accessing the classes stored In a package. The first approach is to use the fully
qualified class name of the class that we want to use. This is done by; using the package name containing the
class and then appending the class name to it using the dot operator. For example, if we want to refer to the
class color In the awt package, then we may do so as follows:
Java.awt.color
Notice that awt is a package within the package java and the hierarchy is represented by separating the levels
with dots. This approach is perhaps the best and easiest one if we need to access the class only once or when
we need not have to access any other classes of the package.
But, in many situations, we might want to use a class in a number of places in the program or we may; like to
use many of the class contained in a package. We may achieve this easily as follows:
import packagename.classname;
Or
import packagename.*;
these are known as Import statements and must appear at the top of the file, before any class declarations,
import is a keyword.
The first statement allows the specified class in the specified package to be imported. For example, the
statement
Import java.awt.color;
Imports the class colour and therefore the class name can now be directly used in the program. There is no
need to use the package name to qualify the class.
The second statement imports every class contained in the specified package. For example, the statement

105

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

import java.awt.*;
will bring all classes of java.awt package.
Create Your Own Package
The package to which the source file belongs is specified with the keyword package at the top left of the
source
file, before
the
code
that
defines
the
real
classes
in
the
package.
Suppose we have a source file called "HelloWorld.java" and we want to put this file in a package
"mypackage" then the following code is written as shown in the given example:
package mypackage;
class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Before running this program make sure to do the following things:
1.
2.
3.
4.

Create a directory "mypackage" .


Save the source file as "HelloWorld.java" in the created directory.
Set the class path as set CLASSPATH = .;C:\;
Go to the "mypackage" directory and compile the program as
C:\mypackage>javac
HelloWorld.java

5. Run the program.


If you try to run this program, you will get the following exceptions (or error):
C:\mypackage>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name:
mypackage/HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
This is, because the class "HelloWorld" belongs to the package "mypackage". So If we want to run it, we
have to tell the JVM about its fully-qualified class name as (mypackage.HelloWorld) instead of its plain
class name (HelloWorld). Fully-qualified class name is the name of the java class that includes its
package
name.
Now run the program as shown:
C:\mypackage>java
mypackage.HelloWorld
Hello World!
106

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The ways to Compile the Package:


Compile in the same directory: If you have a hierarchy of packages to compilation then you can compile
the package without going to the subdirectories and specifying the complete directory path with the class .
Suppose, you have a hierarchy of packages as "india.mycompany.mainpackage.mypackage" including
the class "HelloWorld" then type the following command shown as:
C:\javac
C:\india\mycompany\mainpackage\mypackage\HelloWord.java
This command will reach to the last subdirectory and compile the class "HelloWorld".
Compile into the Different Directory: On the other hand, if you want to compile the same package
available in the hierarchy manner to another directory (location) then syntax is shown as:
C:\javac -d <target_directory>
<complete_directorypath>
Suppose, you want to save the compiled package to the location "D:\myfolder" then type the following
command shown as:
C:\javac -d D:\myfolder C:\
india\mycompany\mainpackage\mypackage\HelloWord.java
This command puts the folder "india" along with its subfolders and the class file "HelloWorld.class" to
the new location as D:\myfolder.
How to import a package
There are two ways so that you can use the public classes stored in package.
Declaring the fully-qualified class name. For example,
mypackage.HelloWorld helloworld = new mypackage.HelloWorld();
Using an "import" keyword: For example,
import world.*; // we can call any public classes inside the mypackage package
Lets see an example importing the created package into the another program file.
package importpackage;
public class HelloWorld
{
public void show()
{
System.out.println("This is the function of the class HelloWorld!!");
}
}
In this program the package "importpackage" is created under the "c:\nisha" directory that will be
imported into another program file to call the function of the class "HelloWorld".
Now make a program file named "CallPackage" under the "c:\nisha" directory importing the package
"importpackage".
import importpackage.*;
class CallPackage{
public static void main(String[] args){
HelloWorld h2=new HelloWorld();
h2.show();
}
107

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
Out of the program:
C:\nisha\importpackage>javac *.java
C:\nisha\importpackage>cd..
C:\nisha>javac CallPackage.java
C:\nisha>java CallPackage
This is the function of the class HelloWorld!!
Make sure to the directory structure for this program shown as:

Using Package
The listing below shows a package named package1 containing a single class ClassA.
package package1;
public class ClassA
{
public void displayA()
{
System.out.println(Clas A):
}
}
This source file should be named ClassA.java and stored in the subdirectory package1.
Now compile this java file. The resultant ClassA.class will be stored in the same subdirectory.
Let us consider another package package2 containing again a single class as shown below:
package package2;
public class ClassB
{
protected int m = 10;
public void dispalyB()
{
System.out.println(Class B);
}
}
As usual, the source file and the compiled file of this package are located in the subdirectory package2.
Program shown below uses classes contained in both the packages.
import pacakge1.ClassA;
import pacakge2.*;
class PackageTest2
{
public static void main(String args[])
{
ClassA objA = new ClassA();

108

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

ClassB objB = new ClassB();


objA.displayA();
objB.displayB();
}
}
This program will be saved as PackageTest.java, compiled and run to obtain the result:
Class A
Class B
m = 10
Lesson 11: Thread
Overview of Threads
A process is an instance of a computer program that is executed sequentially. It is a collection of
instructions which are executed simultaneously at the rum time. Thus several processes may be associated
with the same program. For example, to check the spelling is a single process in the Word Processor
program and you can also use other processes like printing, formatting, drawing, etc. associated with this
program.
Thread
A thread is a lightweight process which exists within a program and executed to perform a special task.
Several threads of execution may be associated with a single process. Thus a process that has only one
thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a
multi-threaded process.
In Java Programming language, thread is a sequential path of code execution within a program. Each
thread has its own local variables, program counter and lifetime. In single threaded runtime environment,
operations are executes sequentially i.e. next operation can execute only when the previous one is
complete. It exists in a common memory space and can share both data and code of a program. Threading
concept is very important in Java through which we can increase the speed of any application. You can see
diagram shown below in which a thread is executed along with its several operations within a single
process.

Main Thread
When any standalone application is running, it firstly execute the main() method runs in a one thread,
called the main thread. If no other threads are created by the main thread, then program terminates when
the main() method complete its execution. The main thread creates some other threads called child threads.
The main() method execution can finish, but the program will keep running until the all threads have
complete its execution.
Multithreading in Java
109

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

So far you have learned about a single thread. Lets us know about the concept of multithreading and learn
the implementation of it. But before that, lets be aware from the multitasking.
Multitasking :
Multitasking allow to execute more than one tasks at the same time, a task being a program. In
multitasking only one CPU is involved but it can switches from one program to another program so quickly
that's why it gives the appearance of executing all of the programs at the same time. Multitasking allow
processes (i.e. programs) to run concurrently on the program. For Example running the spreadsheet
program and you are working with word processor also. Multitasking is running heavyweight processes by
a single OS.
Multithreading :
Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the
same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system.
In the multithreading concept, several multiple lightweight processes are run in a single process/task or
program by a single processor. For Example, When you use a word processor you perform a many
different tasks such as printing, spell checking and so on. Multithreaded software treats each process as a
separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution
running concurrently. It allows a program to be more responsible to the user. When a program contains
multiple threads then the CPU can switch between the two threads to execute them at the same time.
For example, look at the diagram shown as:

In this diagram, two threads are being executed having more than one task. The task of each thread is
switched to the task of another thread.
It is important to remember that threads running in parallel does not really mean that they actually run at
the same time. Since all the threads are running on a single processor, the flow of execution is shared between
the threads. The java interpreter handles the switching of control between the threads in such a way that it
appears they are running concurrently.
Multithreading is a powerful programming tool that makes java distinctly different from its fellow
programming languages. Multithreading is useful in a number of ways. It enables programmers to do multiple
things at one time. They can divide a long program into threads and execute them in parallel. For example, we
can send tasks such as printing into the background and continue to perform some other task in the
foreground.
Advantages of multithreading over multitasking :
Reduces the computation time.
Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than between processes.
Cost of communication between threads is relatively low.

110

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Life Cycle of A Thread


When you are programming with threads, understanding the life cycle of thread is very valuable. While a
thread is alive, it is in one of several states. By invoking start() method, it doesnt mean that the thread has
access to CPU and start executing straight away. Several factors determine how it will proceed.

Different states of a thread are:

1. New state After the creations of Thread instance the thread is in this state but before the start()
method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters
runnable state after the invoking of start() method but a thread can return to this state after either
running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting
for a turn on the processor.
3. Running state A thread is in running state that means the thread is currently executing. There are
several ways to enter in Runnable state but there is only one way to enter in Running state: the
scheduler select a thread from runnable pool.
4. Dead state A thread can be considered dead when its run() method completes. If any thread comes
on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another
thread.
Different states implementing Multiple-Threads are:

111

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

As we have seen different states that may be occur with the single thread. A running thread can enter to any
non-runnable state, depending on the circumstances. A thread cannot enter directly to the running state from
non-runnable state; firstly it goes to runnable state. Now lets understand the some non-runnable states which
may be occur handling the multithreads.
Sleeping On this state, the thread is still alive but it is not runnable, it might be return to runnable
state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time.
You can use the method sleep( ) to stop the running state of a thread.
static void sleep(long millisecond) throws InterruptedException

Waiting for Notification A thread waits for notification from another thread. The thread sends
back to runnable state after sending notification from another thread.
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

Blocked on I/O The thread waits for completion of blocking operation. A thread can enter on this
state because of waiting I/O resource. In that case the thread sends back to runnable state after
availability of resources.

Blocked for joint completion The thread can come on this state because of waiting the completion
of another thread.

Blocked for lock acquisition The thread can come on this state because of waiting to acquire the
lock of an object.

Methods that can be applied on a Thread:


Some Important Methods defined in java.lang.Thread are shown in the table:
Return
Method
Description
Type
start( )
void
Start the thread by calling its run method.
This method is the entry point to execute thread, like the main method for
run( )
void
applications.
sleep( )
void
Suspends a thread for a specified amount of time (in milliseconds).
This method returns the number of active threads in a particular thread
activeCount( )
int
group and all its subgroups.
interrupt( )
void
The method interrupt the threads on which it is invoked.
By invoking this method the current thread pause its execution temporarily
yield( )
void
and allow other threads to execute.

112

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Thread Creation
In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one
of two ways:
Extending the java.lang.Thread Class
Implementing the java.lang.Runnable Interface

I. Extending the java.lang.Thread Class


For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you
have to follow these steps:
1. Extend the java.lang.Thread Class. The Thread class can be extended as follows:
class Mythread extends Thread
{

}
2. Override the run( ) method in the subclass from the Thread class to define the code executed by the
thread. The basic implementation of run() method look like:
public void run()
{
.//thread code here
.
}
3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass
constructor.
MyThread obj = new MyThread();
4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. To
actually run an instance of our thread class, we must write the following:
obj,start();
note : the 3rd and 4th step can be combines as follow:
new MyThread().start();
The following program demonstrates a single thread creation extending the "Thread" Class:
class MyThread extends Thread
{
String s=null;
MyThread(String s1)
{
s=s1;
start();
113

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
public void run()
{
System.out.println(s);
}
}
public class RunThread
{
public static void main(String args[])
{
MyThread m1=new MyThread("Thread started....");
}
}
Output of the Program is :
C:\j2se6\thread>javac RunThread.java
C:\j2se6\thread>java RunThread
Thread started....
An example of multithreaded programming:
class A extends thread
{
public void run()
{
for(int i = 1; i <=5 ; i++)
{
System.out.println(\tFrom ThreadA : i = + i);
}
System.out.println(Exit from A);
}
}
class B extends thread
{
public void run()
{
for(int j = 1; j <=5 ; j++)
{
System.out.println(\tFrom ThreadA : j = + j);
}
System.out.println(Exit from B);
}
}
class C extends thread
{
public void run()
{
for(int k = 1; k <=5 ; k++)
{
System.out.println(\tFrom ThreadA : k = + k);
}

114

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println(Exit from C);


}
}
class TreadTest {
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
output :
First Run
From Thread A : i = 1
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit from A
From Thread B : j = 5
Exit from B
From Thread C : k = 5
Exit from C

Second Run
From Thread A : i = 1
From Thread A : i = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5
Exit from A
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 5
Exit from C
From Thread B : j = 5
Exit from B

II. Implementing the java.lang.Runnable Interface


The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code executed
by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
The following program demonstrates the thread creation implenting the Runnable interface:
class MyThread1 implements Runnable
{
Thread t;
String s=null;
MyThread1(String s1)
{
s=s1;
t=new Thread(this);
t.start();
}
public void run()

115

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
System.out.println(s);
}
}
public class RunableThread
{
public static void main(String args[])
{
MyThread1 m1=new MyThread1("Thread started....");
}
}
However, this program returns the output same as of the output generated through the previous program.
Output of the Program is:
C:\j2se6\thread>javac RunableThread.java
C:\j2se6\thread>java RunableThread
Thread started....
Example:
class X implements Runnable
{
public void run()
{
for(int i=1 ; i<=5 ; i++)
{
System.out.println(\t ThreadX : + i);
}
}
}
class RunnableTest
{
public static void main(String args[])
{
X objrun = new X();
Thread threadX = new Thread(objrun);
thread.start();
System.out.println(End of main Thread.);
}
}
output:
End of main Thread
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
End of ThreadX
There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:
1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you
implement Runnable interface then you can do this.

116

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

2. The class implementing the Runnable interface can avoid the full overhead of Thread class which
can be excessive.
Thread Priorities
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to
determine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities.
The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.
Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10
(highest priority given by the constant Thread.MAX_PRIORITY). The default priority is
5(Thread.NORM_PRIORITY).
Constant
Thread.MAX_PRIORITY
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY

Description
The maximum priority of any thread (an int value of 10)
The minimum priority of any thread (an int value of 1)
The normal priority of any thread (an int value of 5)

The methods that are used to set the priority of thread shown as:
Method
Description
setPriority() This is method is used to set the priority of thread.
getPriority() This method is used to get the priority of thread.
When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when
multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest
priority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at the
execution time a thread with a higher priority and all other threads are runnable then the runtime system
chooses the new higher priority thread for execution. On the other hand, if two threads of the same priority
are waiting to be executed by the CPU then the round-robin algorithm is applied in which the scheduler
chooses one of them to run according to their round of time-slice.
Thread Scheduler
In the implementation of threading scheduler usually applies one of the two following strategies:
Preemptive scheduling If the new thread has a higher priority than current running thread leaves
the runnable state and higher priority thread enter to the runnable state.
Time-Sliced (Round-Robin) Scheduling A running thread is allowed to be execute for the fixed

time, after completion the time, current thread indicates to the another thread to enter it in the
runnable state.
You can also set a thread's priority at any time after its creation using the setPriority method. Lets see, how
to set and get the priority of a thread.
class MyThread1 extends Thread
{
MyThread1(String s)
{
super(s);
start();
}
public void run()

117

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
for(int i=0;i<3;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
class MyThread2 extends Thread
{
MyThread2(String s)
{
super(s);
start();
}
public void run()
{
for(int i=0;i<3;i++)
{
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
public class ThreadPriority
{
public static void main(String args[])
{
MyThread1 m1=new MyThread1("My Thread 1");
MyThread2 m2=new MyThread2("My Thread 2");
}
}
Output of the Program:
C:\nisha>javac ThreadPriority.java
C:\nisha>java ThreadPriority
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
118

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Thread Priority :Thread[My Thread 1,1,main]


Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
In this program two threads are created. We have set up maximum priority for the first thread "MyThread2"
and minimum priority for the first thread "MyThread1" i.e. the after executing the program, the first thread is
executed only once and the second thread "MyThread2" started to run until either it gets end or another
thread of the equal priority gets ready to run state.
Deadlock
A situation where a thread is waiting for an object lock that holds by second thread and this second thread
is waiting for an object lock that holds by first thread, this situation is known as Deadlock.
Lets see a situation in the diagram shown below where the deadlock condition is occurred :

In this diagram two threads having the Printing & I/O operations respectively at a time. But Thread1
need to printer that is hold up by the Thread2, likewise Thread2 need the keyboard that is hold up by
the Thread1. In this situation the CPU becomes ideal and the deadlock condition occurs because no one
thread is executed until the holdup resources are free.
The following program demonstrates the deadlock situation:
public class DeadDemo{
public static void main(String args[]){
String s1="Dead";
String s2="Lock";
MyThread1 m=new MyThread1(s1,s2);
MyThread2 m1=new MyThread2(s1,s2);
}
}
class MyThread1 extends Thread{
String s1;
String s2;
MyThread1(String s1, String s2){
this.s1=s1;
this.s2=s2;

119

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

start();
}
public void run(){
while(true)
{
synchronized(s1)
{
synchronized(s2)
{
System.out.println(s1+s2);
}
}
}
}
}
class MyThread2 extends Thread
{
String s1;
String s2;
MyThread2(String s1,String s2)
{
this.s1=s1;
this.s2=s2;
start();
}
public void run(){
while(true){
synchronized(s2){
synchronized(s1){
System.out.println(s2+s1);
}
}
}
}
}
Output of the program is:
C:\j2se6\thread>javac DeadDemo.java
C:\j2se6\thread>java DeadDemo
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
LockDead
LockDead
120

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

LockDead
LockDead
LockDead
LockDead
LockDead
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
DeadLock
.........
.........
C:\j2se6\thread>
Synchronized Threads
In Java, the threads are executed independently to each other. These types of threads are called as
asynchronous threads. But there are two problems may be occur with asynchronous threads.
Two or more threads share the same resource (variable or method) while only one of them can access
the resource at one time.
If the producer and the consumer are sharing the same kind of data in a program then either producer
may produce the data faster or consumer may retrieve an order of data and process it without its
existing.
Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreases
value of the variable "count" by 1 respectively shown as:
public void increment( )
{
count++;
}
public void decrement( )
{
count--;
}
public int value()
{
return count;
}
When the two threads are executed to access these methods (one for increment( ),another for decrement(
)) then both will share the variable "count". in that case, we can't be sure that what value will be returned
of variable "count".
We can see this problem in the diagram shown below:

121

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

To avoid this problem, Java uses monitor also known as semaphore to prevent data from being
corrupted by multiple threads by a keyword synchronized to synchronize them and intercommunicate to
each other. It is basically a mechanism which allows two or more threads to share all the available
resources in a sequential manner. Java's synchronized is used to ensure that only one thread is in a critical
region. critical region is a lock area where only one thread is run (or lock) at a time. Once the thread is in
its critical section, no other thread can enter to that critical region. In that case, another thread will has to
wait until the current thread leaves its critical section.
General form of the synchronized statement is as:
synchronized(object)
{
// statements to be synchronized
}
Inter-Thread Communication
Java provides a very efficient way through which multiple-threads can communicate with each-other. This
way reduces the CPUs idle time i.e. A process where, a thread is paused running in its critical region and
another thread is allowed to enter (or lock) in the same critical section to be executed. This technique is
known as Interthread communication which is implemented by some methods. These methods are
defined in "java.lang" package and can only be called within synchronized code shown as:
Method
Description
It indicates the calling thread to give up the monitor and go to sleep until some other
wait( )
thread enters the same monitor and calls method notify() or notifyAll().
notify( )
It wakes up the first thread that called wait() on the same object.
Wakes up (Unloack) all the threads that called wait( ) on the same object. The highest
notifyAll( )
priority thread will run first.
All these methods must be called within a try-catch block.
Lets see an example implementing these methods :
class Shared
{
int num=0;
boolean value = false;
synchronized int get()
{
if (value==false)
try {
wait();
}
catch (InterruptedException e)
122

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
System.out.println("InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify();
return num;
}
synchronized void put(int num)
{
if (value==true)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.num=num;
System.out.println("Produce: " + num);
value=false;
notify();
}
}
class Producer extends Thread
{
Shared s;
Producer(Shared s)
{
this.s=s;
this.start();
}
public void run()
{
int i=0;
s.put(++i);
}
}
class Consumer extends Thread
{
Shared s;
Consumer(Shared s)
{
this.s=s;
this.start();
}
public void run()

123

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
s.get();
}
}
public class InterThread
{
public static void main(String[] args)
{
Shared s=new Shared();
new Producer(s);
new Consumer(s);
}
}
Output of the Program:
C:\jdk\bin>javac InterThread.java
C:\jdk\bin>java InterThread
Produce: 1
consume: 1
In this program, two threads "Producer" and "Consumer" share the synchronized methods of the class
"Shared". At time of program execution, the "put( )" method is invoked through the "Producer" class
which increments the variable "num" by 1. After producing 1 by the producer, the method "get( )" is
invoked by through the "Consumer" class which retrieves the produced number and returns it to the
output. Thus the Consumer can't retrieve the number without producing of it.
Lesson 12: Exceptions
The Java programming language uses exceptions to handle errors and other exceptional events. This lesson
describes when and how to use exceptions.
Types of Errors
Errors may broadly be classified into two categories:
1. Compile-time Errors
2. Run-time Errors
Compile-time Errors:
All Syntax errors will be detected and displayed by the Java compiler and therefore these errors are known as
compile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is therefore
necessary that we fix all the errors before we can successfully compile and run the program.
Most of the compile-time errors are due to typing mistakes. The common problems are:
Missing semicolons
Missing brackets in classes and methods
Misspelling of identifiers and keywords.
Missing double quotes in strings
Use of undeclared variables
Incompatible types in assignments/initialization.
Bad reference to objects.
Use of = in place of == operator.
Run-time Errors:
Sometimes, a program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong output due to wrong logic or may terminate due to errors such as stack
overflow. Most common run-time errors are:
124

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Dividing an integer by zero.


Accessing an element that is out of the bounds of an array.
Trying to store a value into an array of an incompatible class or type.
Trying to cast an instance of a class to one of its subclass.
Passing a parameter that is not in a valid range or value for a method
Trying to illegally change the state of a thread.
Attempting to use a negative size for an array.
Converting invalid string to number.
Accessing a character that is out of bounds of a string.

What Is an Exception?
The term exception is shorthand for the phrase "exceptional event."
Definition: An exception is an event, which occurs during the execution of a program, which disrupts the
normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system.
The object, called an exception object, contains information about the error, including its type and the state of
the program when the error occurred. Creating an exception object and handing it to the runtime system is
called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of
possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the
method where the error occurred. The list of methods is known as the call stack (see the next figure).

The call stack.


The runtime system searches the call stack for a method that contains a block of code that can handle the
exception. This block of code is called an exception handler. The search begins with the method in which the
error occurred and proceeds through the call stack in the reverse order in which the methods were called.
When an appropriate handler is found, the runtime system passes the exception to the handler. An exception
handler is considered appropriate if the type of the exception object thrown matches the type that can be
handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all
the methods on the call stack without finding an appropriate exception handler, as shown in the next figure,
the runtime system (and, consequently, the program) terminates.

125

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Searching the call stack for the exception handler.


Using exceptions to manage errors has some advantages over traditional error-management techniques.
The purpose of exception handling mechanism is to provide a means to detect and report an exceptional
circumstances so that appropriate action can be taken. The mechanism suggests incorporation of a separate
error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective action (Handle the exception)
Some common exceptions that we must watch out for catching are listed below:
Exception Type
Cause of Exception
ArithmeticExcepton
Caused by math error such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException
Caused when a program tries to store the wrong type of data in an array
FileNotFoundException
Caused by an attempt to access a nonexistent file
IOException
Caused by general I/O failures, such as inability to read from a file
NullPointerException
Caused by referencing a null object
NumberFormatException
Caused when a conversion between strings and number fails
OutOfMemoryException
Caused when theres not enough memory to allocate a new object.
StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character
position in a string.
The Catch or Specify Requirement
Valid Java programming language code must honor the Catch or Specify Requirement. This means that code
that might throw certain exceptions must be enclosed by either of the following:
A try statement that catches the exception. The try must provide a handler for the exception, as
described in Catching and Handling Exceptions.
A method that specifies that it can throw the exception. The method must provide a throws clause
that lists the exception, as described in Specifying the Exceptions Thrown by a Method.
Code that fails to honor the Catch or Specify Requirement will not compile.
Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at
the three basic categories of exceptions, only one of which is subject to the Requirement.
The Three Kinds of Exceptions

126

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The first kind of exception is the checked exception. These are exceptional conditions that a well-written
application should anticipate and recover from. For example, suppose an application prompts a user for an
input file name, then opens the file by passing the name to the constructor for java.io.FileReader.
Normally, the user provides the name of an existing, readable file, so the construction of the FileReader
object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the
name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A wellwritten program will catch this exception and notify the user of the mistake, possibly prompting for a
corrected file name.
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions,
except for those indicated by Error, RuntimeException, and their subclasses.
The second kind of exception is the error. These are exceptional conditions that are external to the
application, and that the application usually cannot anticipate or recover from. For example, suppose that an
application successfully opens a file for input, but is unable to read the file because of a hardware or system
malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch
this exception, in order to notify the user of the problem but it also might make sense for the program to
print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error
and its subclasses.
The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the
application, and that the application usually cannot anticipate or recover from. These usually indicate
programming bugs, such as logic errors or improper use of an API. For example, consider the application
described previously that passes a file name to the constructor for FileReader. If a logic error causes a
null to be passed to the constructor, the constructor will throw NullPointerException. The
application can catch this exception, but it probably makes more sense to eliminate the bug that caused the
exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those
indicated by RuntimeException and its subclasses.
Errors and runtime exceptions are collectively known as unchecked exceptions.
Bypassing Catch or Specify
Some programmers consider the Catch or Specify Requirement a serious flaw in the exception mechanism
and bypass it by using unchecked exceptions in place of checked exceptions. In general, this is not
recommended. The section Unchecked Exceptions The Controversy talks about when it is appropriate to
use unchecked exceptions.
Catching and Handling Exceptions
This section describes how to use the three exception handler components the try, catch, and
finally blocks to write an exception handler. The last part of this section walks through an example and
analyzes what occurs during various scenarios.
The following example defines and implements a class named ListOfNumbers. When constructed,
ListOfNumbers creates a Vector that contains 10 Integer elements with sequential values 0 through
9. The ListOfNumbers class also defines a method named writeList, which writes the list of numbers
into a text file called OutFile.txt. This example uses output classes defined in java.io, which are
covered in Basic I/O.
//Note: This class won't compile by design!
import java.io.*;
import java.util.Vector;
class ListOfNumbers
{

127

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

private Vector vector;


private static final int SIZE = 10;
public ListOfNumbers ()
{
vector = new Vector(SIZE);
for (int i = 0; i < SIZE; i++)
{
vector.addElement(new Integer(i));
}
}
public void writeList()
{
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++)
{
out.println("Value at: " + i + " = " + vector.elementAt(i));
}
out.close();
}
}
The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the
file cannot be opened, the constructor throws an IOException. The second boldface line is a call to the
Vector class's elementAt method, which throws an ArrayIndexOutOfBoundsException if the
value of its argument is too small (less than 0) or too large (more than the number of elements currently
contained by the Vector).
If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception
thrown by the FileWriter constructor. However, it does not display an error message about the exception
thrown by elementAt. The reason is that the exception thrown by the constructor, IOException, is a
checked
exception,
and
the
one
thrown
by
the
elementAt
method,
ArrayIndexOutOfBoundsException, is an unchecked exception.
Now that you're familiar with the ListOfNumbers class and where the exceptions can be thrown within it,
you're ready to write exception handlers to catch and handle those exceptions
The try Block
The first step in constructing an exception handler is to enclose the code that might throw an exception within
a try block. In general, a try block looks like the following.
try
{
Code
// generates an exception
}
catch and finally blocks
The segment in the example labeled code contains one or more legal lines of code that could throw an
exception. (The catch and finally blocks are explained in the next two subsections.)
To construct an exception handler for the writeList method from the ListOfNumbers class, enclose
the exception-throwing statements of the writeList method within a try block. There is more than one
way to do this. You can put each line of code that might throw an exception within its own try block and
provide separate exception handlers for each. Or, you can put all the writeList code within a single try
block and associate multiple handlers with it. The following listing uses one try block for the entire method
because the code in question is very short.
private Vector vector;
128

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

private static final int SIZE = 10;


PrintWriter out = null;
try
{
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++)
{
out.println("Value at: " + i + " = " + vector.elementAt(i));
}
}
catch and finally statements . . .
If an exception occurs within the try block, that exception is handled by an exception handler associated
with it. To associate an exception handler with a try block, you must put a catch block after it; the next
section shows you how.
The catch Blocks
You associate exception handlers with a try block by providing one or more catch blocks directly after the
try block. No code can be between the end of the try block and the beginning of the first catch block.
try
{
}
catch (ExceptionType name)
{
}
catch (ExceptionType name)
{
}
Each catch block is an exception handler and handles the type of exception indicated by its argument. The
argument type, ExceptionType, declares the type of exception that the handler can handle and must be the
name of a class that inherits from the Throwable class. The handler can refer to the exception with name.
The catch block contains code that is executed if and when the exception handler is invoked. The runtime
system invokes the exception handler when the handler is the first one in the call stack whose
ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown
object can legally be assigned to the exception handler's argument.
The following are two exception handlers for the writeList method one for two types of checked
exceptions that can be thrown within the try statement.
try
{
}
catch (FileNotFoundException e)
{
System.err.println("FileNotFoundException: " + e.getMessage());
throw new SampleException(e);
}
129

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
Both handlers print an error message. The second handler does nothing else. By catching any IOException
that's not caught by the first handler, it allows the program to continue executing.
The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions is
covered in detail later in this chapter in the How to Throw Exceptions section.) In this example, when the
FileNotFoundException is caught it causes a user-defined exception called SampleException to
be thrown. You might want to do this if you want your program to handle an exception in this situation in a
specific way.
Exception handlers can do more than just print error messages or halt the program. They can do error
recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using
chained exceptions, as described in the Chained Exceptions section.
The finally Block
The finally block always executes when the try block exits. This ensures that the finally block is
executed even if an unexpected exception occurs. But finally is useful for more than just exception
handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
continue, or break. Putting cleanup code in a finally block is always a good practice, even when no
exceptions are anticipated.
Note: If the JVM exits while the try or catch code is being executed, then the finally block will not
execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally
block will not execute even though the application as a whole continues.
The try block of the writeList method that you've been working with here opens a PrintWriter. The
program should close that stream before exiting the writeList method. This poses a somewhat
complicated problem because writeList's try block can exit in one of three ways.
1. The new FileWriter statement fails and throws an IOException.
2. The vector.elementAt(i) statement fails and throws an
ArrayIndexOutOfBoundsException.
3. Everything succeeds and the try block exits normally.
The runtime system always executes the statements within the finally block regardless of what happens
within the try block. So it's the perfect place to perform cleanup.
The following finally block for the writeList method cleans up and then closes the PrintWriter.
finally
{
if (out != null)
{
System.out.println("Closing PrintWriter");
out.close();
}
else
{
System.out.println("PrintWriter not open");
}
}

130

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In the writeList example, you could provide for cleanup without the intervention of a finally block.
For example, you could put the code to close the PrintWriter at the end of the try block and again
within the exception handler for ArrayIndexOutOfBoundsException, as follows.
try
{
out.close();
//Don't do this; it duplicates code.
}
catch (FileNotFoundException e)
{
out.close();
//Don't do this; it duplicates code.
System.err.println("Caught: FileNotFoundException: " +
e.getMessage());
throw new RuntimeException(e);
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
However, this duplicates code, thus making the code difficult to read and error-prone should you modify it
later. For example, if you add code that can throw a new type of exception to the try block, you have to
remember to close the PrintWriter within the new exception handler.
Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise
recovering resources, place the code in a finally block to ensure that resource is always recovered.
Putting It All Together
The previous sections described how to construct the try, catch, and finally code blocks for the
writeList method in the ListOfNumbers class. Now, let's walk through the code and investigate what
can happen.
When all the components are put together, the writeList method looks like the following.
void writeList()
{
PrintWriter out = null;
try
{
System.out.println("Entering try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++)
out.println("Value at: " + i + " = " +
vector.elementAt(i));
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println("Caught " + "ArrayIndexOutOfBoundsException:
"
+

e.getMessage());

}
catch (IOException e)

131

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{
System.err.println("Caught IOException: " + e.getMessage());
}
finally
{
if (out != null)
{
System.out.println("Closing PrintWriter");
out.close();
}
else
{
System.out.println("PrintWriter not open");
}
}
}
Throwing our own Exception
There may be times when we would like to throw our own exceptions. We can do this by using the keyword
throw as follows:
throw new Throwable_subclass;
Example:
throw new ArithmeticException();
Following program demonstrate the use of user-defined subclass of Throwable class. Note that Exception is
a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class
that extends Throwable can be thrown and caught.
import java.lang.Exception;
class MyException extendsException
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z = (float) x / (float) y;
if( z < 0.01)
{
throw new MyException(Number is too small.);
}
}
catch (MyException e)
{
System.out.println(Caught my exception);
System.out.println(e.getMessage());
132

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}
finally
{
System.out.println(I am always here.);
}
} }
A run of program produce:
Caught my exception
Number is too small.
I am always here.
The object e which contains the error message Number is too small is caught by the catch block which then
displays the message using the getMessage() method.
Lesson 13: Applet
Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web
browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so
there are some restrictions on it. Applet can't access system resources on the local computer. Applets are
used to make the web site more dynamic and entertaining.
Advantages of Applet:
Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security
approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning to a web page
User can also have full access to the machine if user allows
Disadvantages of Java Applet:
Java plug-in is required to run applet
Java applet requires JVM so first time it takes significant startup time
If applet is not already cached in the machine, it will be downloaded from internet and will take time
Its difficult to design and build good user interface in applets compared to HTML technology

How Applets differ from Applications


Although both the applets and stand-alone applications are Java programs, there are significant differences
between them. Applets are not full-featured application programs. They are usually written to accomplish a
small task or a component of a task. Since they are usually designed for use on the Internet, they impose
certain limitations and restrictions in their design.
1. Applets do not use the main() method for initiating the execution of the code. Applets, when loaded,
automatically call certain methods of Applet class to start and execute the applet code.
2. Unlike stand-alone applications, applets cannot be run independently. They are run from inside a webpage
using a special feature known as HTML tag.
3. Applets cannot read from or write to the files in the local computer.
4. Applets cannot communication with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++.

133

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Life Cycle of Applet


Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed.
Here are the lifecycle methods of an Applet:
init(): This method is called to initialized an applet
start(): This method is called after the initialization of the applet.
stop(): This method can be called multiple times in the life cycle of an Applet.
destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.
init () method: The life cycle of an applet begins when the applet is first loaded into the browser and
called the init() method. The init() method is called only one time in the life cycle on an applet. The init()
method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed
parameter through the PARAM tag of html file using get Parameter() method All the initialization such as
initialization of variables and the objects like image, sound file are loaded in the init () method .After the
initialization of the init() method user can interact with the Applet and mostly applet contains the init()
method.
Start () method: The start method of an applet is called after the initialization method init(). This method
may be called multiple times when the Applet needs to be started or restarted. For Example if the user
wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web
browser and the user will be back on the applet. In the start method user can interact within the applet.
Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start ()
method. Or should be called at least one time. There is only miner difference between the start() method
and stop () method. For example the stop() method is called by the web browser on that time When the user
leaves one applet to go another applet and the start() method is called on that time when the user wants to
go
back
into
the
first
program
or
Applet.
destroy() method: The destroy() method is called only one time in the life cycle of Applet like init()
method. This method is called only on that time when the browser needs to Shut down.
The steps involved in developing and testing in applet are:
1. Building an applet code (.java file)
2. Creating an executable applet. (.class file)
3. Designing a web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APPLET> tag into the web page.
6. Creating HTML file.
7. Testing the applet code.
Creating First Applet Example
First of all we will know about the applet. An applet is a program written in java programming language
and embedded within HTML page. It runs on the java enabled web browser such as Netscape navigator or
Internet Explorer.
In this example you will see, how to write an applet program. Java source of applet is then compiled into
java class file and we specify the name of class in the applet tag of html page. The java enabled browser
loads class file of applet and run in its sandbox.
Here is the java code of program:
import java.applet.*;
import java.awt.*;

134

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public class FirstApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString("Welcome in Java Applet.",40,20);
}
}
Here is the HTML code of the program:
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800"
HEIGHT="500"></APPLET>
</BODY>
</HTML>
Passing Parameter in Java Applet
Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass
the parameters from your html page to the applet embedded in your page. The param tag(<parma name=""
value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of
applet and passing parameter in applet, a example is given below.
In this example, we will see what has to be done in the applet code to retrieve the value from parameters.
Value of a parameter passed to an applet can be retrieved using getParameter() function. E.g. code:
String strParameter = this.getParameter("Message");
Printing the value
Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html
page. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will display
the value passed as parameter. In our case applet should display "Welcome in Passing parameter in java
applet example." message.
Here is the code for the Java Program :
import java.applet.*;
import java.awt.*;
public class appletParameter extends Applet
{
private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g)
{
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}
Here is the code for the html program:
<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>

135

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet
example.">
</APPLET>
</BODY>
</HTML>
There is the advantage that if need to change the output then you will have to change only the value of the
param tag in html file not in java code.
Compile the program:
javac appletParameter.java
Output after running the program:
To run the program using appletviewer, go to command prompt and type appletviewer
appletParameter.html Appletviewer will run the applet for you and it should show output like Welcome in
Passing parameter in java applet example. Alternatively you can also run this example from your
favorite java enabled browser.
Here is the code for the html program :
<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>
There is the advantage that if need to change the output then you will have to change only the value of the
param tag in html file not in java code.
Compile the program :
javac appletParameter.java
Output after running the program :
To run the program using appletviewer, go to command prompt and type appletviewer
appletParameter.html Appletviewer will run the applet for you and and it should show output like
Welcome in Passing parameter in java applet example. Alternatively you can also run this example
from your favorite java enabled browser.
Lesson 14: Graphics
Graphics environment variables
Graphics commands are called as methods belonging to a special type of variable, called a Graphics
Environment variable. Normally, these commands will only be called in the special method called paint,
which is given the task of drawing the screen.
When the Java applet is activated, Java looks for a method called paint which has a single parameter of type
Graphics. If it doesn't find one, then it doesn't spit out an error - but it doesn't draw anything on the screen
either! Java also calls the paint method automatically in some other circumstances. For instance, if you resize

136

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

the browser window in which the applet is sitting, you will see the applet flicker as the screen is automatically
updated.
Usually, Java applets contain a method like this:
public void paint (Graphics g)
{
Screen-drawing statements go here
}
All the screen drawing instructions will start with the characters g., indiciating that they are part of the
Graphics parameter passed. However, the parameter is only called g by tradition - there's no logical reason
why the parameter shouldn't be called any legal name you want. You could easily write a paint method that
looked like this:
public void paint (Graphics three_blind_mice)
{
three_blind_mice.drawLine(100,150,325,72);
}
In this case, all the drawing instructions would start with three_blind_mice. as that is the name of the
parameter. There may be cases where you need to draw things on the screen at some other point in the
program. You can access the screen at any point by declaring a variable of type Graphics and using the
methods within it. I will go into variables in more detail in a later section, but suffice it to say that if you ever
need to draw something on the screen at some point other than in the paint() method, then include the
following lines in your program at the relevant point:
Graphics temp_g = getGraphics();
temp_g.drawOval(300,120,100,75);
The first of the two lines declares a graphics environment variable - I've chosen to call it temp_g, but you
could give it any name you wanted - and sets it to the current graphics settings, using the built-in method
getGraphics. Be careful to get the capital letter in that - Java is case sensitive, and it won't recognise the
method if you call it GETGRAPHICS or Getgraphics etc.
The second of the two lines is an example of how the new graphics variable could be used. Obviously, you
would replace that line with the particular instruction that you wanted.
The co-ordinate system
All graphics instructions use a co-ordinate system just like the one that you learned at school. Each "unit" is
one pixel wide, so the entire screen is about 600 units wide and about 400 or so units high. This is why coordinates in Java programs tend to be fairly large values.
The (0,0) point of the co-ordinates (the origin) is always the top-left
corner of the Java applet window. The first number of each pair refers to
the number of pixels across the screen, the second number refers to the
number of pixels down the screen. The maximum co-ordinate values in
each case depend on the size of the applet window, which was determined
when the applet was called in the web page. You will recall that you called
it with the command
<applet code="first.class" width="150" height="150"></applet>
The width="150" height="150" part determines the maximum coordinate as (150,150). If you try to draw something at a co-ordinate larger than this, then it wouldn't appear on
the screen. If you draw anything (a line, oval or rectangle) that would be partly on the screen and partly off,
then only a fraction of the shape would appear, chopped off by the edge of the window.
Lines, ovals, rectangles and arcs
The graphics environment contains the following instructions for drawing lines, ovals (ellipses - including
circles), rectangles and arcs:
g.drawLine(100,100,420,312);
g.drawRect(72,160,200,35);

137

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

g.drawOval(300,120,100,75);
g.drawArc(250,250,100,100,0,180);
Note that all the instructions start with g. as they are part of the Graphics Environment variable g. They all
also end with a semicolon (;). All statements - graphics or otherwise - in Java end with a semicolon. Also,
bear in mind that names in Java are case sensitive, so the names must be typed in in lower case letters with the
single upper case (capital) letter in the middle of the name as shown. Otherwise the compiler won't recognise
them.
The instruction drawLine draws a line (surprise, surprise!) It is given four
numbers. The first two numbers represent the x- and y-co-ordinates of one end of
the line, and the last two number represent the x- and y-co-ordinates of the other
end. The instruction that you see above
draws a
line from
coordinates
(100,100) to (420,312).
The
instruction drawRect draws
a
rectangle. It is given four
numbers.
The first two numbers are
the x- and y-co-ordinates of the top-left corner. You might expect the other two numbers to be the x- and yco-ordinates of the opposite corner (as they would be in some other programming languages), but no! They
represent the width and the height of the rectangle. In the case of the example above, the rectangle has its topleft corner at (72,160) and a width of 200 and a height of 35. Its bottom-right corner is at (72+200,160+35)
i.e. (272,195).
The instruction drawOval is given four numbers. You have to
imagine that the oval is drawn within an invisible rectangle. The
four numbers represent the top-left co-ordinates of the rectangle
and its width and height, in the same way as for rectangles. This
mean that the oval drawn in the example above completely fills
an invisible rectangle whose top-left co-ordinate is at (300,120)
and whose bottom-right co-ordinate is at (400,195). The width
of the oval at its widest point is 100 pixels, and its height at its
maximum point is 75. There is no standard way of drawing an oval at a slanted angle.
The graphics environment also gives a method which draws arcs, i.e. sections of oval shapes (or circles, of
course). Arcs have starting angles and arc angles, with all angles being measured from the "East" position
(pointing to the right). The arc angle basically means the ending angle minus the starting angle.
To draw an arc, use the drawArc command. This is given six numbers. The first four specify the rectangle in
which the entire oval is enclosed, even though only part of that oval is to be drawn. The last two numbers
specify the starting angle and the arc angle (both in degrees). Here's an example:
drawArc(100,100,80,60,45,120);
Of course, if the start angle is specified as 0 and the ending angle as
360, then the arc drawn is a complete oval.
Filled shapes
There are three more shape-drawing instructions, they are the "fill"
equivalent of drawRect, drawOval and drawArc:
g.fillRect(72,160,200,35);
g.fillOval(300,120,100,75);
g.fillArc(250,250,100,100,0,180);
The results they produce is simply a filled-in version of the basic shape, except for fillArc which produces a
pie-slice effect.
Text strings

138

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

You already met the instruction used to display strings on the screen. In case you didn't, you won't be
surprised to hear that it is drawString. Just to remind you - a string is a piece of text, anything from a single
character (a term which includes letters, punctuation, symbols such as @ or ^, and even the space character)
to a whole sentence. Strings are specified by placing them within double quotation marks.
The method drawString is given three parameters between brackets. The first item is the string itself to be
displayed on the screen. The other two numbers specify where the string is to appear. It represents the top-left
corner of the string. However, the second number actually specifies the y-co-ordinate of a line on which the
text sits. Some characters, such as 'g' or 'y' will drop down below this imaginary line, as shown in the
following example:
g.drawString("This is hugely easy",40,60);
Color
If you don't specify a color for drawing shapes or text, then Java uses the default color of black. Specifying a
color is fairly easy - although you can only specify one of 13 standard colors (including white).
There is a standard method built into graphics environment variables called setColor (note the American
spelling of 'Color'). It expects to be given a color name, but the color name must be of a standard type
specified in yet another class called Color. What all this means is that colors are chosen as follows:
g.setColor(Color.blue);
g.setColor(Color.orange);
Here are the thirteen standard colors. Make sure you use them exactly as specified - don't alter the case of the
letters or insert spaces in the middle of them, and note the spelling of 'Gray'.
black
Gray
orange
yellow
blue
green

pink

cyan

darkGray

magenta

white

lightGray

red

Any color that you choose will then be used for drawing all lines, text, shapes and as the fill-in color for
shapes until you choose another color. You can also determine the color of the background to the applet. This
is done using the following instruction:
setBackground(Color.cyan);
Again, like the setColor method, it is important to note that the name of the method is all lower case letters
except for the capital B in the middle. However, please note that setBackground is not part of the graphics
environment, and as such, does not need to be preceded by g. In fact, if you do put g. at the beginning, then
the Java compiler complains. I have fallen into this trap many times!
An example graphical applet
Here is an example Java applet which demonstrates the commands that described ablove.
import java.awt.*;
import java.applet.*;
public class graph_ex extends Applet
{
public void paint (Graphics g)
{ setBackground(Color.cyan);
g.drawString("Here are a selection of blank shapes.",20,40);
g.drawLine(20,40,200,40);
g.setColor(Color.blue);
g.drawLine(20,50,70,90);
g.setColor(Color.red);
g.drawRect(100,50,32,55);
g.setColor(Color.green);
139

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

g.drawOval(150,46,60,60);
g.setColor(Color.magenta);
g.drawArc(230,50,65,50,30,270);
g.setColor(Color.black);
g.drawString("Here are the filled equivalents.",20,140);
g.drawLine(20,140,200,140);
g.setColor(Color.yellow);
g.fillRect(100,150,32,55);
g.setColor(Color.pink);
g.fillOval(150,146,60,60);
g.setColor(Color.darkGray);
g.fillArc(230,150,65,50,30,270);
}
}
Using control loops in Applets
We can use all control structures in an applet. Following program uses for loop for drawing circles repeatedly.
import java.awt.*;
import java.applet.*;
public class ControlLoop extends Applet
{
public void paint(Graphics g)
{
for(int i=0; i<=4; i++)
{
if( (i%2) == 0)
g.drawOval(120, i*60+10, 50, 50);
else
g.fillOval(120, i*60+10, 50, 50);
}
}
}
Output:

140

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

repaint
Occasionally, there will be points in the program where you will want it redraw the screen. Perhaps the screen
has changed (the paint method can easily cope with if statements that get it to draw different things in
different circumstances). To call the paint method in these circumstances, use the following instruction:
repaint();
Note that there are no parameters (no numbers, strings or graphics environments) passed to this method, but
you still must include the two brackets and follow them with the obligatory semicolon, like this ();
It is vital that you don't include this method inside the paint method itself. If you did, the paint method would
never terminate, as it would always be calling itself.

141

6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290
3rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499