You are on page 1of 219

Self Learning Material

Programming in Java
(MCA-201)

Course: Post Graduate Diploma in


Computer Applications
Semester-II

Distance Education Programme

I.K. Gujral Punjab Technical University


Jalandhar

Syllabus
I.K. Gujral Punjab Technical University

PDCA-201Programming in Java
SECTION-A
FUNDAMENTALS OF OBJECT-ORIENTEDPROGRAMMING:-Introduction, Object-Oriented
Paradigm,BasicConceptsofObject-OrientedProgrammingBenefitsofOOP,Applications of
OOP.
How
JavaDiffersfromCandC++(Javacharacterset,Keywords,Identifiers,Literals,
Operators, Separators), DECISIONMAKINGAND LOOPING:-Introduction, The while
Statement,
ThedoStatement,TheforStatement(Additionalfeaturesofforloop,Nestingofforloops),
Jumps inLoops(Jumpingoutofaloop,Skippingapartofaloop),LabeledLoops.CLASSES.(10)
SECTION-B
OBJECTS AND METHODS:-Introduction, Defining a Class, Adding Variables, Adding
Variables, Adding Methods, Creating Objects, Accessing Class Members,
Constructors, Inheritance: Extending a Class (Defining a subclass, Subclass constructor,
Multilevel inheritance, Hierarchical inheritance), Overriding Methods, Final Variables and
Methods, Final Classes, Finalizer Methods.
ARRAYS, STRINGS AND VECTORS: - Arrays, One-Dimensional Arrays, Creating an Array
(Declarationofarrays,Creationofarrays,Initializationofarrays,Arraylength),Two-Dimensional
Arrays(Variablesizearrays),Strings(Stringarrays,Stringmethods,StringBufferclass),Vectors,
Wrapper Classes. INTERFACES: Introduction, Defining Interfaces, Extending Interfaces,
Implementing Interfaces, Accessing Interface Variables.
SECTION-C
PACKAGES: Introduction, System Packages, Using System Packages, Naming Conventions,
CreatingPackages,AccessingaPackage,UsingaPackage,AddingaClasstoaPackage,Hiding
Classes.MANAGINGERRORSANDEXCEPTIONS:-Introduction,TypesofErrors(Compile-time error,
Run-time error), Exceptions, Syntax of Exception Handling Code, Multiple Catch
Statements, Using finally Statement, Throwing Our Own Exceptions, Using Exceptions for
Debugging.

SECTION-D
APPLETPROGRAMMING:-Introduction, How Applets Differ from Applications, Preparing to
Write Applets, Building Applet Code, Applet Life Cycle (Initialization state, Running State, Idle
or stopped state, Dead state, Display state), Creating an Executable Applet, Designing a Web
Page (Comment Section, Head Section, Body Section), Applet Tag, Adding Applet to HTML
File, Running the Applet, More About Applet Tag, Passing Parameters to Applets, Aligning the
Display, More about HTML Tags, Displaying Numerical Values, Getting Input from the User.
SuggestedReadings/Books:
1.EBalagurusamy,ProgrammingwithJava, 4th Edition2010.
2.HebertSchildt,Java the Complete Reference,8th Edition2011.
3.BruceEckel,ThinkinginJava,KalyaniPublishers,4th Edition2011.

TableofContents
ChapterNo.
1
2
3
4
5
6

Titl
e

Written By

Page No.

Mr. Hardeep Singh, BBK DAV


College, Amritsar

Mr. Hardeep Singh, BBK DAV


College, Amritsar
Mr. Hardeep Singh, BBK DAV
College, Amritsar

15

Control structures branching

Mr. Hardeep Singh, BBK DAV


College, Amritsar

45

Control structures looping

Mr. Hardeep Singh, BBK DAV


College, Amritsar

61

Classes and wrapper classes

Mr. Hardeep Singh, BBK DAV


College, Amritsar

81

Mr. Avtar Singh Sidhu, Guru


Gobind Singh Khalsa College,
Sarhali

107

Mr. Avtar Singh Sidhu, Guru


Gobind Singh Khalsa College,
Sarhali

126

Mr. Avtar Singh Sidhu, Guru


Gobind Singh Khalsa College,
Sarhali

145

Mr. Avtar Singh Sidhu, Guru


Gobind Singh Khalsa College,
Sarhali
Mr. Avtar Singh Sidhu, Guru
Gobind Singh Khalsa College,
Sarhali
Mr. Avtar Singh Sidhu, Guru
Gobind Singh Khalsa College,
Sarhali

160

Fundamentals of Java
Java building blocks
Operators and Expressions

7
Array, Vectors and string handling

8
Interfaces

9
Packages

10
Exception handling

11
Introduction to applets

12
Advanced Applet Programming

30

177

197

Reviewed By
Pankaj Deep Kaur, GNDU Regional Campus,
Jalandhar
IK Gujral Punjab Technical University Jalandhar
All rights reserved with IK Gujral Punjab Technical University Jalandhar

PDCA-201
Programming in Java
Unit-I.

Lesson 1.

Fundamentals of Java

Chapter Index
Objectives
Introduction
1. Introduction to Java
Relation between C, C++ and Java
Features of Java
Important Java Terminology
i. Bytecode
ii. JDK
iii. JVM
iv. JRE
2. Object Oriented Paradigm
3. Basic Concepts of Object Oriented Programming
4. Benefits of OOP
5. Applications of OOP
6. Summary
7. Glossary
8. Answers to Check Your Progress / Self Assessment Questions
9. References / Suggested Readings
10. Model Questions

Objectives

To learn the basics of Java programming language.

Difference between C++ and Java.

Explore the features of Java.

Write simple programs in Java.

To learn fundamentals of Object Oriented Paradigm ?

To know the features and applications of Object Oriented Programming.

Introduction
Java is one of the most popular general purpose programming languages today. It is based on
object oriented programming paradigm, which itself is one of the most common programming
paradigm. Java source code is compiled into byte code which java interpreter is able to execute.
Java offers many special features like platform independence, supports multithreading and offers
applets. Four basic principles of object oriented programming are data abstraction, encapsulation,
inheritance and polymorphism.

Introduction to Java
Java is one of the very few pure object oriented programming languages and was created by
James Gosling at Sun Microsystems Inc. in 1990. The basic idea behind Java was to develop a
language that is much simpler than C++ and offers much wider scope than C++. It was originally
termed as Green Project and the team who created it was called Green Team. Later in 1991,
it was renamed Oak. Again in 1992, it was renamed Java. In January 2010, Sun Microsystems
was taken over by Oracle Corporation, therefore now, java belonged to Oracle, and following
this James Gosling resigned from Sun.
Java is a simple, portable, platform independent; pure object oriented language well suited to
design various types of applications. The applications comprise of designing CUI, GUI and web
applications (client side as well as server side), mobile applications, multimedia applications
etc.Apart from that, a special type of application known as appletcan be created in java that can
run inside a web browser.. Unlike C or C++ which are compiler based, Java uses a combination
of both interpreter and compiler. First of all java program is compiled by java compiler (javac) to
create a bytecode and then bytecode is executed by java interpreter called JVM (Java Virtual
Machine).

Figure 1.1 a. James Gosling.

1. b Java Logo used by Sun Microsystems.

1.c Java logo by Oracle

Features of Java
1. Simple :Java is a compact and simple language than C++. Many confusing features of
C++ like pointers, multiple inheritance, virtual functions, structure, union, operator
overloading etc. have been not been included in Java.
2. Platform Independent :Java is a platform independent language, so its programs can be
designed to run in a similar manner on multiple operating systems. In other
programming languages like C/C++, a program written on a machine with Windows OS,
can not be run on a different machine with Unix or Mac OS. But this problem does not
happen with Java. Java achieve this independence using its virtual machine called JVM

3.

4.

5.

6.

7.

(Java Virtual Machine). There exists a separate JVM for each OS.Pure Object Oriented
Language: In Java, everything is considered as an Object. Java posseses all the features
of a pure object oriented language, like Abstraction, Inheritance, Polymorphism etc. . An
extensive inbuilt class library in the form of API is available in Java. Further, no program
can be written in Java without the concept of a Class.
Robust :Here robust means reliable. Early checking of bugs happen in java which may
otherwise lead to run time errors and may cause a program to crash. Java also provides
strong type checking and has a run time exception handling feature . Another feature of
automatic garbage collection makes it more reliable.
Distributed :Java is a distributed language which means an application developed in
Java can be run on a network also. This is made possible by networking related API
provided by Java. It makes network communication from within an application very easy.
Automatic memory management: Java provides its own garbage collector, and
therefore memory management (memory allocation and de-allocation) is the
responsibility of JVM and programmer does not have to worry about it. JVM runs a
separate thread of garbage collector when any java application runs.
Multithreading: Java provides the feature to create multithreading based applications
and allows to run multiple threads of execution to run concurrently within the same
application. This improves the performance of an application.
Java Bytecode :A java program is not translated to native machine language. Rather it is
translated to java bytecode by java compiler (javac) which is later interpreted and
executed by java virtual machine.

Check Your Progress / Self Assessment Questions


Que 1. When was java developed?
Que 2. Who created Java?

Relation between C, C++ and Java


Some of the features of java have been inherently there in C and C++ also, but there are many
things that are new in java and infact they have different design goals. C++ was primarily
designed for systems and general purpose applications (desktop applications), extending the C
programming language. Java is a general-purpose, pure object-oriented programming language
that is specially designed to have very few implementation dependencies as possible. It is more
secure and highly portable. Java uses similar but incompatible syntax to C++. Java has much
wider scope than C/ C++ and can be used not only for general purpose desktop applications but

also for web applications and mobile applications. Relation between C, C++ and Java can be
depicted from following figure.

Figure 1.2 : Relation between C, C++ and Java.

Check Your Progress / Self Assessment Questions


Que. 3. What is the relation between C++ and Java?
Que. 4.Outline major differences between C++ and Java?

Important Java Terminology:


These are some very common terms in Java. Lets read about these.
Bytecode
Bytecode is the actual magic behind working of any java application. It is compiled code of Java
programs produced by java compiler. Unlike any other compiler, java source program is not
converted to machine language code by java compiler, rather a code understandable by Java
Virtual Machine only. So Bytecode can be considered to be machine language instruction set of
the Java virtual Machine. Java Byte code file generally has extension as .class extension. A Java
programmer needs not to be worry about having understanding of Java bytecode at all.

Java Software Development Kit (JDK) :JDK is used for development and execution of Java
programs. It contains all java standard API in the form of packages and classes. JDK includes
JRE (Java Runtime Environment) to execute java applications. JRE includes Java Virtual
Machine (JVM), core classes of java, and other supporting libraries. If a java application just
needs to be executed, only JRE can serve the purpose and can be downloaded separately. JDK

comprises of a collection of tools that can be used for developing and running Java programs.
JDK contains :

javac (Java compiler)


java (Java interpreter)
appletviewer (for viewing Java applets)
javap (Java disassembler)
javah (for C header files)
jdb (Java debugger)
javadoc (for creating HTML documents)

Java Virtual Machine (JVM) :A virtual machine is actually a software implementation of a


hardware that runs the applications similar to hardware. Java Virtual Machine (JVM) is the
major component of Java programming language. It does the job of interpreting and executing
compiled java program called bytecode. First, like an interpreter, it converts each statement of
java bytecode to machine language and then executes it. Further, Java compiler compiles java
source code to bytecode and Java Virtual Machine runs it. There is a separate JVM for each
Operating System and this makes java language platform independent. It thus enables
developers to concentrate on developing software without worrying about how and where the
software is to be used finally.
Java Run Time Environment (JRE) :If you want to run any java based application, your
machine must have Java Run Time Environment installed on it. Among other things, it includes,
JVM, Java class library and many other supporting files. JRE can also be obtained separately
without JDK.
Check Your Progress / Self Assessment Questions
Que 5. What is JDK?
Que 6.What is Bytecode?

A Simple Java Program


A java program is a collection of one or more java classes. Each class definition in source
program is translated to bytecode and a separate .class file is created after compilation by java
java compiler (javac). A very simple example of java program is given below:

/* Sample Java Program */


//My First Java Program (HelloWorld.java)
Class HelloWorld
{

//class definition.
Public static void main(String args [ ] )
{
//body of main
System.out.printl (Hello World !) ;
}

Java program can be written in any text editor like notepad. Type above program in a text file
and save the file as HelloWorld.java. All java program body is written inside a class. Note that
name of the class (having main method in it) must be exactly same as name of text file. When
this java program is compiled, a HelloWorld.class file is created which can be run by java. A
java program can contain multiple class files but only one class is allowed to have main method
in it. Also note that main method takes an argument of String type array. This can be used while
working with command line arguments.
Why is main () public static and void method?
First note that main is a method and belongs to a class. This main () method cannot be written
outside a class. It is declared to be public method of the class so that it can be called from
anywhere. It is static so that it can be called even without creating an object or instance of the
class. It is void which means it does not return anything.

Check Your Progress / Self Assessment Questions


Que 7. What is JVM?
Que 8. What type of arguments does main method take?

Object Oriented Paradigm


A Programming paradigm is basically a particular method/philosophy about how to solve a
programming problem. Among many programming paradigms available today, four most

popular paradigms are Imperative, Logical, Functional and the topmost popular one i.e. Object
Oriented.
In OO programming paradigm, the focus is on the real world entities and data ,around which the
problem revolves rather than on coding the solution. A problem is viewed as a group of
interacting entities called objects which are organized into classes.(A class is a template and an
object is an instance of the class). To develop an effective solution, developer tries to understand
the properties/features of objects and operations that can be performed on those objects. In object
oriented terminology, properties/features of objects are known as data members and operations
are known as member functions. Once objects, their features and their operations are well
understood , more effective solution can be developed with fewer efforts as compared to efforts
needed in other programming paradigms. Even a large and complex problem can be easily
understood and well managed in object oriented paradigm.
An example of real world entity is CAR, its features can be like Make, Model, FuelType,
SeatingCapacity etc. and operations that can be performed on a CAR can be, Drive(), Refill(),
FindSpeed() etc. This is shown in figure 1.3.
Class Vs Object: A class is a template using which objects or instances of the class are created.
All objects belonging to the same class have same feature set but distinct values. Each object is
distinct, and has separate representation in memory.

Figure 1.3.Class, Attributes and Methods.

Figure 1.4 Class and its three instances (objects)

Basic Concepts of Object Oriented Programming


Four major pillars on which the foundation of OOP lies are data abstraction, encapsulation,
inheritance and polymorphism.
Data abstraction : Data abstraction means to hide the irrelevant details from the user and show
only the minimum required part. It makes the understanding of the system easier for the user.
Encapsulation : Encapsulation is hiding and packaging data and the operations i.e. methods
which operate on that data into single logical unit. Data can be accessed only by the methods in
the same logical unit and remains protected from outside world. Java provides a keyword
private to make data or methods inaccessible to outer world. It thus increases safety of data by
eliminating the chances of illegal operations.
Inheritance : Inheritance is to reuse the already written code in some other parts of the project.
Through inheritance a new class called child class can be derived from an existing class called
parent class. Child class thus inherits all the features of the parent class resulting in reusability.
Reusability is the major advantage of inheritance.
Polymorphism : Polymorphism refers to creation of multiple functions or methods with same
name. They differ in method signatures i.e. number and type of arguments sent to functions.
When a method is called, compiler binds the call to the method which matches the number and
type of arguments.
Benefits of OOP
Code maintenance: OOP makes the code easily maintainable. Code debugging becomes easier
and needs fewer efforts as it is convenient to detect errors contained in self-contained templates
called classes.
Reusability: Code reusability is the basic advantage of inheritance which is one of the basic
building blocks of OOP. Once a class has been created and tested, more functionality is added in
classes being extended from it.
Scalable: As compared to structured programming, object oriented programming is more
scalable. Newer methods based on better and faster algorithms can replace earlier written
methods in the class.
Easily Manageable code :Ascompared to structured programming, it is easier to model a real
system in Object Oriented Programming based on the notion of objects and classes. The objects
can only be processed by the member functions of the same class.

Check Your Progress / Self Assessment Questions

Que. 9.What arethe four basic blocks of Object Oriented Paradigm?


Que. 10. Which feature of Object Oriented Paradigm contributes to reusability?
Applications of OOP
Object Oriented Programming Paradigm is gaining importance in many areas of real life. Some
of the common application areas of OOP include:

User interface design : Interface of many popular applications and even popular operating
systems like windows is developed using object oriented programming languages.

CAD (Computer Aided Design) :Software engineers can prepare 2-D and 3-D designs of
their products like automobiles etc. using CAD. CAD software isitself based on object
oriented paradigm.

Compiler Designing : A compiler is a type of system software that translates high level
language program to machine language. Coding a compiler is very easier in Object
oriented programming language like C++.

Relational Data Base Systems Design

CASE Tools

Simulation and modeling

Computer animation and games

Real Time Systems

Object oriented Databases

AI and Expert System, Neural Networks and Parallel Programming

Decision Support Systems (DSS) and Office Automation System (OAS)

10

Summary
Java developed by James Gosling, originally belonged to Sun microsystem, now currently owned
by Oracle Corporation. It is a pure object oriented language with features like Compact, robust,
distributed, automatic garbage collection, multithreading. It does not possess confusing features
of C++ like multiple inheritance, pointers etc.. Various types of applications can be created in
java like desktop applications (CUI and GUI), web application, mobile applications etc. It is
based on Object Oriented Paradigm which makes management of complex and large code more
manageable. Object oriented paradigm is based on four basic pillers viz data abstraction,
inheritance, polymorphism and Encapsulation.

11

Glossary

James Gosling : Person who originally developed Java in 1990.

Sun Microsystems : Java was developed at Sun Microsystems by James Gosling.

JVM: Java Virtual Machine. Part of java which makes java platform independent.

Pure OO : Java is one of the few Pure Object Oriented Languages.

Robust :Feature of java that makes it more reliable.

Garbage Collection : Automatic deallocation of memory is performed in Java by JVM.

Applet : Small programs written in java which can be run in any web browser or in a
small utility software which is part of Java Development Kit (JDK) called applet viewer.

JDK : Java Development Kit, a software bundle that comprises many small software to
install Java and develop java applications.

JRE : Java Run time Environment. Part of JDK, required to run java applications.

Bytecode :Java byte code is language understood by java virtual machine. Any java
source code is translated to java bytecode by java compiler and is run by java virtual
machine.

OO Paradigm : Object oriented programming paradigm, one of the four major


programming paradigms.

Data abstraction :Key feature of Object Oriented Programming that emphasizes on hiding
unwanted details from user.

Encapsulation : Packaging data and operations in one single logical unit called class.

Inheritance : Deriving or extending a class from another already developed class, gives
advantage of reusability.

Polymorphism :Defining multiple methods of same name but different arguments.

GUI : Graphical User Interface.

CUI : Character User Interface.

12

Answers to Check Your Progress / Self Assessment Questions


Ans. 1. Java was developed in 1990.
Ans. 2. Java was created by James Gosling at Sun Microsystems.
Ans. 3. Java is superset of C++ and has much larger scope than C++.
Ans. 4. Java is pure Object Oriented language, C++ is not. Java does not support mulitple
inheritance, pointers, structure and union etc. Java has applets and multithreading, C++ does not
have these features.
Ans. 5. JDK is Java Development Kit. It contains many small software to run and develop java
applications.
Ans. 6. Bytecode is code produced by java compiler in the form of .class files.
Ans. 7. Java Virtual Machine, runs java applications compiled in java bytecode.
Ans. 8.An array of String type.
Ans. 9.Data Abstraction, Inheritance, Polymorphism and Encapsulation.
Ans. 10.Inheritance.

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall
4. Introduction to Programming in Java: An Interdisciplinary Approach, Robert
Sedgewick's , Amazon

13

Model Questions

Write a note on features of Java


What is JDK ?
What is JRE ?
What is Bytecode?
What is appletviewer in Java?
How does java differ from C++ ?
Why is main method declared as public, static and void ?
What is Object Oriented Paradigm?
Explain the features of Object Oriented Paradigm.
What are the applications of Object Oriented Praradigm?

14

PDCA-201
Programming in Java
Unit-1.Lesson-2.

Java Building Blocks

Chapter Index
Objectives
Introduction

Java Differs from C and C++

Java character Set, Keywords, Identifiers, Literals, Operators, Separators

Data types

Constants

Variables and Scope of variables

Operators

Expressions

Flow Control statements

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

To know the differences between C++ and Java.

To learn about keywords, identifiers, literals, operators and character set of Java.

To know various types of expressions in Java.

Exploring flow control statements of Java.

15

Introduction
Though both C++ and Java are object oriented programming languages and java is a superset of
C++, still there are many major differences between java and C++. In this lesson, we will study
about these differences, character set, various data types, identifiers and operators of Java
language. Also, it will be explained which are many flow control statements in Java. Valid rules
and conventions to form legal identifiers, scoping rules of variables etc. will also be explained.

Java Differs from C and C++


There are many major and small differences in C++ and Java. Basically, Java is a big superset of
C++ and has a much wider scope than C++. C++ was developed in 1980s by Bjarne Stroustrep
at Bell Labs, USA, whereas Java was developed by James Gosling in 1991 at Sun Microsystems.
Some of the differences in C++ and Java are given below:

Java is a pure object oriented language whereas C++ is a weak object oriented language.

Java uses a combination of both, compiler and interpreter. Firstly java source code is
compiled by java compiler into bytecode, and then this bytecode is interpreted by java
interpreter, JVM. But C++ is purely a compiler based language. C++ source code is
compiled by compiler into machine language.

In C++, main method may exist even outside a class, and a program can be created
without any class, but in Java everything has to be inside a class. A program cannot be
written in Java without a class.

In C++, there can be class methods and c-style functions also. But in Java there are no
functions, only methods are available inside a class..

C++ has signed and unsigned data types. There are no such unsigned data types in Java.

There are no structures, unions, and pointers in Java; also, there is no typedef keyword as
found in C++.

C++ has preprocessor directives, like #define and # include, but Java does not use the
concept of preprocessor directives.

C++ has class and function templates, Java does not have templates.

16

C++ uses const keyword to create non-modifiable constants, java uses final keyword for
this purpose, and there is no const keyword in Java.

C++ supports multiple inheritance, Java does not support multiple inheritance.

C++ has goto statement to jump from one part of program to another part, Java does not
use goto keyword for jumping.

Java has labeled breaks and labeled continue, but these are not found in C++.

Java provides feature of automatic memory management. Java has its own garbage
collector which performs memory de-allocation of unused objects. But in C++, memory
de-allocation is pure responsibility of C++ programmer.

C++ uses the syntax of main method as main(int argc, char *argv[]) where as java uses
main method as main(string args[]) but uses command line arguments in different ways.
Further, C++ uses two syntax for main, main( ) and main(int argc, char *argv[]), but java
uses only one syntax of main method.

Strings are treated differently in C++ and java. A string in C++ is simply an array of char
data type and ends with a NULL. But, in Java, String is a class type defined in java.lang
package.

C++ supports both single and multidimensional arrays, Java does not support multidimensional arrays. To create multi-dimensional arrays in Java, an array of single
dimension array of single dim arrays is created.

Further, there is no boundary checking performed on arrays in C++, where as in java,


boundary checking is strictly enforced.

In Java we can create applets, which are small programs that run inside web browser.
C++ does not support this concept.C++ provides its library in the form of header files that
have .h extension. Java provides its API in the form of packages. C++ uses #include to
attach library files in a program, whereas Java uses import statement to include packages.

Check Your Progress / Self Assessment Questions

Ques 1. How does C++ and Java include library functions in a program?

Ques 2. How does C++ and Java create non-modifiable constants?

Ques 3. What is meant by boundary check?

17

Java character Set


Character set means set of characters that can be used in a language. Java character set is a
set of different types of characters that can be used to form basic programming elements like
variables, constants, expressions etc. while writing a java program. Java character set
includes:
o Alphabet : both lower case (a-z) and upper case (A-Z). These two are treated
differently as Java is a case sensitive language.
o Digits : 0-9. To write numbers.
o Symbols and special characters : Many symbols and special characters are used to
write expressions, operators, separators as explained ahead. Some of the symbols and
special characters include +, -, *, /, &. %, <, =, ==, ! _ Etc.

Java Keywords: A keyword is a predefined word that has a specific meaning and purpose in
Java, it cannot be used for any other purpose. There are many keywords in Java, like class,
interface, package main, for, while, if, try, catch, return, import etc. Some keywords like
const and goto are reserved words, it means though they are not currently used but they are
reserved for future.
A list of keywords of Java :abstract, continue, for, New, switch, default, goto, Package,
synchronized, Boolean, do, if, Private, this, break, double, implements, Protected, throw,
byte, else, import, public, throws, case, enum, instanceof, return, transient, catch, extends,
int, short, try, char, final, interface, static, void, class, finally, long, strictfp, volatile, const,
float, native, super, while
Note that all keywords of java are in lower case.
Java Identifiers: It is any user-defined word used to form a variable name, class name,
method name, package name, interface name etc. Identifier means it is used to identify
something in Java. There are some rules to form a valid identifier in Java, like, a keyword
cannot be used as identifier, an identifier name must start with an alphabet, an identifier
name in java is case sensitive (num, Num, NUM and NuM are different) and have no
maximum length. etc.

18

Java Literals: Literal means a constant. Whereas the value of a variablemay change any
number of times in program, a literal once initialized, cannot change. Java Literals are of four
types.
o String Literals: String literal is written by enclosing it in double quotes marks,
for example, Hello World!
o Character Literals: Character type literals are enclosed in single quotes and can
contain only one character. Like for gender we can use M or F, for grade we
can use A , B etc.
o Boolean Literals: Boolean data type has 2 literals, true and false.
o Numeric Literals: A numeric literal is a numeric constant like 123, 123.56 etc.

Check Your Progress / Self Assessment Questions


Ques 4. What is the difference between an identifier and a literal?
Ques 5. Is true and false are literals or keywords in Java?
Ques 6. What is difference between a keyword and a reserved word?

Java Operators
To perform different types of calculations in programs, java provides different types of
operators. There are three categories of operators, unary, binary and ternary. There are
arithmetic operators for performing mathematical or arithmetic operations, relational
operators for checking relations among operands, logical operators for performing logical
operations, conditional operator to check a condition and return a value,
increment/decrement operators to increment or decrement the value of a variable by 1 etc.
Operators operate on operands which may be variables or literals. Operators when
combined with operands create expressions, which calculate values and results.

Java Separators

19

Separators are some characters from java character set which act as punctuation characters. A
very simple and common example of a java separator is a semicolon(;).It is used at the end of
each statement to signify termination of a statement. Using semicolon as a separator multiple
statements can be written in one line. Other separators used in java are :
a. Parenthesis : for example used to write method arguments.
b. Curly braces : { and }, used to initialize array elements.
c. Brackets : [ and ], used to declare arrays.
d. Comma : used to separate variables in variable declaration, used in for loop to separate
expressions etc.
e. Period (.) : used to call a method on an object.

Data types in Java


While performing calculations in a program, we may have to deal with different types of
data. To store different types of data in different variables, Java provides different data types.
Broadly, there are two categories of data types in Java, these are primitive data types and
reference data types.

Figure 2.1: Java data types

1. Primitive Data types


A Primitive data type is a basic or elementary data type which is predefined in Java. For each
each primitive data type a separate keyword exists in Java. There are two primitive data

20

types, Boolean and numeric. Numeric data type is further of two types, integral and floating
point. Integral data type is used for integers or whole numbers, floating point is used with
real numbers.

a) Boolean data type is used to check whether a condition or an expression evaluates to true
or false. There are two Boolean literals true and false. For example, 5<7 gives true, 5==7
gives false.
b) Numeric Data types:
i.

Integral Data Types:


o char data type : It is used to represent single character textual data. A char in Java is
used to represents a 16-bit unsigned Unicode character. A char literal is enclosed in
single quotes (' '). For example:

'M' for Male, F for Female etc. It is considered

integral data type because each char is represented in memory by its integer Unicode
in the range 0 to 65535.
o byte data type : It is used to represent 8-bit integers in the range -128 to +127.
o short data type: It is used to represent 16-bit integers in the range -32768 to +32767.
o int data type: It is used to represent 32-bit integers in the range -2147483468 to
+2147483467. This range is given by -231 to +231.
o long data type: It is used to represent 64-bit integers in the range -263 to +263.

ii.

Real data types: These are also called floating point data types and are used to
represent real numbers (numbers with decimal point) in memory. It consists of
following types :
o float :float data type is of 4 bytes width. Its range is -3.4x1038 to +3.4x1038 and their
precision is 7 digits. Example of float data type values are : rate of interest, radius of
circle, area of a circle, standard deviation of a series etc.
o double: Sometimes it may be required to represent values larger or smaller than the
range of float. Java provides a bigger data type for this purpose named as double.
Width of double data type is 8 bytes, range is -1.7x10308 to +1.7x10308 and its
precision is 15 digits after decimal. Examples of use of double data type are : radius
of earth in inches, area of a nano organism etc.

21

Reference data types


These are non-primitive or derived data types that can be created or derived using primitive
data types. These are also called as user-defined data types. They are named so, as they
handle or manage their variables "by reference" or the address, the address of an object or
an array is stored in a variable and passed as arguments to methods,. In contrast, primitive
types are managed "by value" i.e. the actual primitive values is stored in a variable and value
is passed to methods as arguments. These are of following types :

Array: An array is a collection of contiguous data elements in memory. All elements


of array are homogenous i.e. they have same data type. An array is created using
primitive data types. For example, int num[ ] = new int[10] ; creates an array named
num having 10 elements, num[0], num[1], and so on up to num[9]. Here, 0, 1,, 9
are called index numbers.

Class: A class is basically a user defined data type. A class has data members and
member functions in it. All data members can either be primitive data type or can be
of another class type. So in a way, a class is also a derived data type. A variable of
class type is called an object or an instance of class. When an object is created, first a
reference variable of class type is created to hold the address of object in memory.
Example, String s ; will create a reference variable of String type.

Check Your Progress / Self Assessment Questions


Ques 7. What is the range of an int in java?
Ques 8. Which are two Boolean literals?
Ques 9. Which are different reference types in Java?

Constants

22

Constant is a name given to a literal whose value remains same throughout the program.
This is in contrast to a variable whose value may change any number of times in Java.
There are different types of constants in java, as given below:
o numeric constants like 123, 10.5 etc. To create a numeric constant of long type
simply place a L behind it, like 123L.
o Boolean constants like true / false
Java provides a keyword final that lets create a constant. For example, final int num=10 ;
makes num a constant.

Variables and Scope of variables


A java program may need to perform calculations on values. For this, values are stored in
memory locations which are accessed in program by names. These names of memory
locations are called as variables. In simple words, Variables are storage locations in memory
where a value gets stored. Variable name is a type of identifier. Value of a variable may
change any number of times in a program i.e. its value may vary, thats why a variable is
named so. To store values of different data types, variables of corresponding data type is
created. Java requires variables to be declared before using them.In case a variable is
accessed before its declaration, a compile time error is generated. Compile time errors are
generated by the compiler when compiling a program. Some valid variables names and their
declarations are :
int num ;
float circleArea;
double PIE=3.14 //declared and initialized.
boolean test ;

Scope of a variable
Scope of a variable is also called visibility of a variable that identifies the locations where a
variable can be accessed within a program. It depends upon where a variable has been
declared. Scoping rules of a variables decide its accessibility in different parts of the
program.

23

o Block level scope : Easiest to understand is block level scope. It means, a variable can
only be accessed inside a block where it is declared and cannot be accessed outside the
block. It is called local variable.
o Function level scope :A variable declared at the top of a function or method can be used
or accessed anywhere inside a method body. Such a variable is said to have function or
method level scope. It is local variable of the function or method.
o Class level scope :Data members declared inside a class are said to have class level
scope.
Example :
class Student
{
int rollno ;
int findMarks( )
{
float total_marks ;
:
:
{
int temp ;
:
:
}
}
}
In this example, rollno has class level scope, total_marks has method level scope and
temp has block-level scope.

Check Your Progress / Self Assessment Questions


Ques 10.How will you declare an integer constant of long data type?

Expressions
An expression is a combination of operands and operators. Operands may be
variables,constants or literals. An expression in java is same as a formula in mathematics.
An arithmetic expression is createdusing only arithmetic operations and operands. For
example, num1+num * 5.

24

A relational expression is two or more arithmetic expressions joined with relational


operators. It givesanswer in boolean value true or false. For example, num1+num2 < x*y
A logical expression is created when one or more relational expressions are joined with
logical operators. It also gives answer in boolean value true or false.

Flow Control statements

There are different types of statements in Java. By default, each statement of a program is
executed from top to bottom, linearly, exactly once. But in some cases this default flow of
execution may need to be altered or controlled as required. A special type of statements called
flow control statements are used to control or alter the default flow of execution of a program.
There are three sub-types of flow control statements. These are :
1. Selection statements: They are also known as branching statements and decisions making
statements. There are three java statements in this category, if, if-else and switch.
2. Iterative statements: They are used for repeating a group of statements. They are also
known as looping statements. This category has while loop, do-while loop, for loop and
for-each loop.
3. Control-transfer statements: These statements are known as jumping statements also.
There are break, return, continue and try-catch statements in this category.

Figure 2.2 : Flow control statement in Java


These statements will be explained in detail in Lesson 4 Control Structures Branching and
lesson 5 Control structures -Looping.
Check Your Progress / Self Assessment Questions
Ques 11.What arethe three types of flow control statements?

25

Summary
There are many major and small differences in C++ and Java. Basically, Java is a big superset of
C++ and has much wider scope than C++.
In C++, there can be class methods and c-style functions alsowhereas in Java there are no
functions, only methods (inside class).
C++ has signed and unsigned data types, there are no such unsigned data types in Java.
Java character set is set of different types of characters that can be used to form basic
programming elements like variables, constants, expressions etc. while writing a java program
A keyword is a predefined word that has a specific meaning and purpose in Java, it cannot be
used for any other purpose. There are many keywords in Java.
Java identifier is a user-defined word used to form a variable name, class name, method name,
package name, interface name etc.
To perform different types of calculations in programs, java provides different types of
operators. There are three categories of operators, unary, binary and ternary.
Java provides different data types. Broadly, there are two categories of data types in Java, these
are primitive data types and reference data types. Primitive data types include char, boolean,
byte, short, int, long. Non-primitive data types include array, class and interface.
A java program may need to perform calculations on values, for this values are stored in memory
locations which are accessed in program by names, these are called variables.
Scope of a variable is also called visibility of a variable. It means where a variable can be
accessed within program.
An expression is a combination of operators and operands. Operands may be variables or
constants or literals.

26

. A special type of statements called flow control statements are used to control the flow of
execution of a program.

27

Glossary

Character Set : Permissible set of characters in language, also called building blocks.

Keywords : some special words which have specific predefined meaning.

Identifiers: used defined names given to class, method, interface, variables etc.

Literals : constants.

final : a keyword of java, used to create constants.

Operators: symbols used to perform operations or calculations of operands.

Separators: special symbols used to separate variables and expressions etc.

Data types : indicate which type of data will be stored in a variable.

Scope of a variable : indicates visibility of a variable i.e. where a variable is accessible.

Expression : a combination of operators and operands.

Flow Control : controlling flow of execution of a program.

Answers to Check Your Progress / Self Assessment Questions


Ans 1.C++ uses preprocessor directives #include, and java uses import statement.
Ans 2.C++ uses # define preprocessor directive, whereas java uses final keyword.
Ans 3.Boundary check means performing check that array index is used only within the limit and
size of array.
Ans. 4.An identifier is a user-defined name given to a variable, class etc. whereas a literal is
constant.
Ans 5. Two boolean literals are true and false. But true (within double quotes) is a string
literal.
Ans 6.A keyword has a special, specific predefined meaning, a reserved word is a keyword
which is reserved for future use.
Ans 7.Range of int is :2147483468 to +2147483467. This range is give by -231 to +231

28

Ans. 8.These are true and false.


Ans 9.Different reference types in java are class, interface and array.
Ans 10.By suffixing L. for example, 123L.
Ans 11.Selection, iterative and control transfer.

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. What are the various data types of Java?
2. What are the rules to form a valid identifier?
3. Explain different types of operators available in Java?
4. What is the difference between an operator and a separator?
5. What is an expression? How an expression is formed?
6. What is meant by scope of a variable? Which are different types of scopes?

29

PDCA-201
Programming in Java
Unit-1.Lesson-3.

Operators and Expressions

Chapter Index
Objectives
Introduction

Operators, Operands and Expressions

Unary, Binary and Ternary Operators

Precedence and Associativity

Java Operators
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Assignment Operator
o Bitwise Operators
o Shift Operators
o Increment / Decrement Operators

o Other operators
new operator
instanceof operator
dot operator
Writing mathematical expressions in Java

Operator Precedence Chart

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

30

Objectives

To know various types of operators used in Java

To know difference among unary, binary and ternary operators.

To know how to form expressions in Java.

To be able to solve expressions in Java

To know operator precedence and associativity

Introduction
There are different types of operators provided by Java language to perform various types of
calculations. Various types of operators like relational, arithmetic, logical, conditional, bit-wise
etc will be studied in this chapter. Operator precedence decides which operator will be solved
first in an expression involving different operators. Operator associativity decides in which
direction operator works in an expression, left to right or right to left. An operator precedence
chart is given to know precedence or hierarchy of operators.

2.1 Operands, Operators and Expressions


Operands are values on which an operation or calculation is performed. These operands may be
direct constants or may be values stored in variables. Operators are specials symbols or
characters which are part of character set of Java language and are used to perform calculations
on operands. Operators indicate type of operation to be performed on operands. Expressions are
formed with the help of operands and operators. An expression is a valid combination of
operands and operators.

31

Figure 3.1: Expression, Operand, Operator.


There are variety of operators in Java, which are explained below:

Precedence and Associativity


Operator precedence decides which operator will be solved first in an expression involving
different operators. It is also known as hierarchy of operators. An example of precedence is
BODMAS that we are taught in school. Operator precedence comes into picture when in a given
expression there are different operators. For example, in an expression, x+y * z, firstly y is
multiplied by z and then the result is added to x. So x+y*z is solved like (x+(y*z)) and not like
((x+y)*z)

Operator associativity decides in which direction operator works in an expression, left to right or
right to left. Most of the operators have associativity from left to right, but some operators have
associativity right to left. Associativity comes into picture when same operator is repeated in an
expression. For example, in an expression x / y / z, first, x will be divided by y and then the
result will be divided by z. Its not like that y is divided by z first and x is divided by result given
by y/z.
So the direction of solving / is left to right. This is associativity.

Unary, Binary and Ternary Operators


Before we start to discuss about different operators available in Java, let us understand that all
operators fall broadly in three categories, unary, binary and ternary.
Unary Operators are those which work on a single operand and they have highest precedence
among three types of operators. Example, logical not operator (!) and increment/decrement
operators (++, --)
Binary operators are those which work on two operands at a time, most of the java operators are
binary operators. They are most commonly used. Some of the binary operators are
multiplication, division etc.
Ternary operators are those which work on three operands at a time. There is only one ternary
operators in Java, it is conditional operator (? :) which will be explained soon.

32

Check Your Progress / Self Assessment Questions


Ques 1. What is difference between an operator and an operand?
Ques 2.What are three categories of operators?
Ques 3. Which types of operators have highest precedence?

Java Operators :Various types of operators available in Java will be explained now, along with
their associativity.

Arithmetic Operators: Arithmetic operators are those operators which are used to perform
arithmetic operations. There are five arithmetic operators in Java, these are

Operation

Symbol
Used

Multiplication

Symbol

Purpose

Associativity

Multiplies x by y, written

Left to Right

Name
Asterisk

as x * y
Division

Slash

Gives quotient when x is

Left to Right

divided by y, written as
x/y.
Remainder

Percentage

Gives remainder when x

Left to Right

is divided by y, written as
x%y
Addition

Plus

Adds x and y, written as

Left to Right

x+y
Subtraction

Minus

Subtracts y from x,
written as x-y

33

Left to Right

In an expression, first multiplication, division and remainder are solved, when these are finished,
then addition and subtraction are solved, working on the expression from left to right. This is just
like BODMAS that is taught to us in schools.

So for example, if an arithmetic expression is 2+3*4-8/2%3 then it will be solved as :


2+3*4-8/2%3
= 2 + 12 - 8 / 2 % 3 (* is solved first)
= 2 + 12 - 4 % 3

(/ is solved next)

= 2 + 12 - 1

(% gives remainder)

= 14 -1

(there is no *, / or % left, so now solve +)

=13

Note that, there is no operator for raise to power. There is a static method given by Math class
for this purpose, it can be used as Math.pow(x, y) to calculate x y

Check Your Progress / Self Assessment Questions


Ques 4. How will you write xy+yx in Java?
Ques 5. What will be the result of : 1%5 + 5%1 + 5%5 ?

Relational Operator
Relational operators are used to check relation between operands. Relational operators give
answer in true or false only. Relational operators are generally used in decision making
(selection statements) and looping (iterative statements) that will be explained in lesson Flow
Control Statements . There are five relational operators as shown in table below:

Operation
Less than
Greater than

34

Symbol
Used
<
>

Symbol
Name
Less than
Greater than

Purpose

Associativity

Checks if x is less than y,


written as x<y
Check if x is greater than
y, written as x > y

Left to Right
Left to Right

Less than or
equal to

<=

Less than,
equal to

Greater than
or equal to

>=

Greater than,
equal to

Comparison

==

Not equal to

!=

double equal
to
Sign of
exclamation,
equal to

Checks if x is less than or


equal to y, written as x
<=y
Check if x is greater than
or equal to y, written as
x>=y
Checks if x is equal to y,
written as x = = y
Checks if x is not equal to
y, written as x != y

Left to Right

Left to Right

Left to Right
Left to Right

An expression that contains relational operator(s) is called relational expression. Relational


operators can be used to combine arithmetic operators. For example, x+y < a-b, disc<b2 4ac.
In a relational expression, first all arithmetic operators are solved then relational operators are
solved.
Example :2+3<4*5, in this relational expression, first of all 4*5 is solved giving 2+3<20, then
2+3 is solved giving 5<20, finally < is solved. Since 5<20 is correct, it gives final answer as true.

Logical Operators
Relational operators are used to check conditions. Sometimes more than one condition is to be
checked or tested. Then two or more relational expressions can be combined using logical
operators. There are three logical operators in Java.
Operation
Logical And

Symbol
Used
&&

Symbol
Name
Double
ampersand

Logical OR

||

Double pipe
sign

Logical NOT

Sign of
exclamation

Purpose

Associativity

Checks if both conditions


are true, written as
condition1 &&
condition2.
Checks if one or both
conditions are true,
written as condition1 | |
condition2.
Checks if conditon1 is
true or false, works on
single operand. It is unary
operator.

Left to Right

Example: totalIncome < 10000 && totalBonus < totalIncome * .25/100

35

Left to Right

Left to Right

This expression checks if total income is less than 10,000 AND total bonus is less than 25 % of
total income, here && operator used to join two relational expression, first one is totalIncode <
10000, and second one is totalBonus< totalIncome * .25/100.
Such expressions in which logical operators are used are called logical expressions.
In such an expression, first all arithmetic operators are solved, then relational and finally logical
operators are solved. Final result is always in terms of boolean true or false.

Check Your Progress / Self Assessment Questions


Ques 6. What is the result of 3<4 || 5<6?
Ques 7. What will be result of !(3<4 )?

Assignment Operator
Assignment operator is used with most of other operators. Its job is to assign a value to a
variable. It has least precedence. A variable is used at the left side of assignment operator, and on
its right side there can be a variable or a constant or an expression. It has right to left
associativity. It is a binary operator.
Operation
Assigning
value to a
variable
Example :

Symbol
Used
=

Symbol
Name
Equal to

Purpose

Associativity

Assigns a value to a
variable used on left side.

Right to Left

num1=10. Assigns value 10 to num1.


num1=num2. Assigns value of variable num2 to variable num1.
num1=num2 *5. Solves expression num2*5 and assigns result to num1.

There is one more way in which assignment operator can be used; it is called multi-assignment
i.e. assigning same value to multiple variables. Suppose it is required to assign same value 10 to
three variables x, y and z. It can be performed by writing : x=y=z=10 ;

Increment/Decrement Operators

36

These two are unary operators, increment operator is used to increment value of a variable by
one, that is to add one to value of a variable, and decrement operator is used to decrease the
value of a variable by 1.
Operation
Increment
value of a
variable
Decrement
value of a
variable

Symbol
Used
++

--

Symbol
Name
plus plus

Purpose

Associativity

Add one to existing value


of a variable

Right to Left

minus minus

subtracts one from


existing value of a
variable

Right to Left

Both these are of two types, pre and post.


Pre-increment is used as prefix to a variables like ++x. Post-increment is used as suffix to a
variable as x++. It makes difference when used with some other operators like, y=x++ is
different from y=++x. When used as post fix as in y=x++, it first assigns current value of x to y
and then increments x by 1. But when used as prefix as in y=++x, it first increments x then
assigns incremented value of x to y.
Pre-decrement is used as prefix to a variable like --x. Post-decrement is used as suffix to a
variable as x--. Just like increment, post and pre-decrement are different, i.e. y= --x is different
from y=x
Check Your Progress / Self Assessment Questions
Ques 8. What is the difference between a=b++ and a=++b.

Bit wise operators


Just like logical and (&&), logical or (||) and logical not (!), there are bitwise and, bitwise or,
bitwise not and bitwise xor operators available in Java. All these four are binary operators. They
work on bits of a number, for this; internally both operands are converted to their equivalent
binary representation and then operator is applied to individual bits.
Operation
bit wise and

37

Symbol
Used
&

Symbol
Name
Ampersand

Purpose

Associativity

To perform ANDing of
bits of two numbers

Left to Right

bitwise or

Pipe

bitwise not

Tilde sign

bitwise
exclusive or

Caret

To perform ORing of bits


of two numbers
To perform complement
of bits of a number. It
unary operator.
To perform bitwise
exclusing oring of bits

Left to Right
Left to Right

Left to right.

Example :5 | 7 will work as 00000101 & 00000111 it gives 00000111 i.e.7. Note that 5 || 7 will
give result as 1.
Ques 9. Which are various bit-wise operators?

Shift operators
There are two shift operators available in Java. These are left shift and right shift. Shift operators
also work on bits of a number and are considered as a type of bitwise operators. When bits of a
number are shifted to left, number gets multiplied by two, and when bits of a number are shifted
to right, it gets divided by two.
Operation
Left shift

Symbol
Used
<<

Right shift

>>

Symbol
Name
less than
symbol used
twice
Greater than
symbol used
twice

Purpose

Associativity

To shift bits of a number


towards left once.

Left to Right

To shift bits of a number


towards right once.

Left to Right.

Example :5 << 1 gives 10. Because when bits of 5 i.e. 0000 0101 are shifted to left once, they
become 0000 1010 and it represents number 10 (ten) in decimal. Similarly, if right shift is
performed on 139 giving binary as 10001011 it would give 01000101 i.e. 69.

Conditional Operator: As already explained, it is the only ternary operator that works on three
operands in Java. It uses symbol ? :. Its syntax is OperandOne ?OperandTwo : OperandThree
First of all, it evaluates first operand operandOne, and, if first operand gives true value, then
second operand operandTwo is evaluated (third operand OperandThree is not evaluated in this
case), but if first operand gives false, then third operand is evaluated (second operand is not

38

evaluated in this case). Actually, conditional operator provides an easy and short hand form of
equivalent selection statement if-else. Example : marksObtained >=60? gradeObtained=A :
gradeObtained=B . In this example, first operand is marksObtained >=60, second operand is
gradeObtained=A and third operand is gradeObtained=B. if marksObtained by student are
greater than or equal to 60 the gradeObtained will be assigned value A, and if marksObtained
by student>=60 returns false, gradeObtained will be assigned value B.

Operation
If then else

Symbol
Used
?:

Symbol
Name
Question
mark and
colon

Purpose

Associativity

To evaluate one of two


operands on the basis of a
condition given by first
operand.

Right to Left

Other Operators
Apart from above there are some other special operators available in Java. These are :
new operator : This operator is used to create a new object of a class. It assigns reference of
newly created object to reference value.
ExampleStudent s = new Student ( ) ; where Student is name of a class, s is a reference variable,
new Student( ) given on right side creates a new object

instanceof operator
instanceof operator is a binary operator.It is used to check whether an object is actually an
instance of a class or interface. Its syntax is objectName instanceof ClassName, where
objectName is name of object or instance, and ClassName is name of class. Here it is being
checked whether or not object objectName is an instance of class ClassName or not. Operator
instanceof returns true or false.
Example : s instanceof Student.

dot operator (.)

39

dot operator is used to call a method on an object or to access a data member with an object. For
example, if totalMarks is a data member and getMarks( ) is a method of Student class, and s is an
object of Student class and then dot operator can be used to access method and data member as
s.getMarks( ) and s.totalMarks.

Writing mathematical expressions in Java

x / y, and m X n is written as m * n, there is a specific

method of writing expression in Java. Some of the examples are given below in this
regard.

Mathematical expression

Java Expression
(x+y)/z

( + )
x2+y2

x*x + y*y

disc = b2 4 a c

disc=b*b -4 * a *c

( + )

Math.pow(x+a, n)

x<y<z

40

Math.sqrt(x+y)

ci=p*Math.pow(1+r/100, t)
x<y && y<z

Operator precedence chart


Since there are various operators in Java, and an expression may have different types of
operators, fix operator precedence helps compiler to solve an expression. Each operator is
solved in a fix sequence as per its precedence. Following chart shows precedence and
associativity of each operand found in Java.

Fig. : Operator precedence chart (taken from


http://www.tutorialspoint.com/java/java_basic_operators.htm ) ????????

41

Summary
Operands are values on which an operation or calculation is performed. These operands may be
direct constants or may be values stored in variables. Operators are specials symbols or
characters which are part of character set of Java language and are used to perform
calculationson operands. Operators indicate type of operation to be performed on operands.
Expressions are formed with the help of operands and operators.
Operator precedence decides which operator will be solved first in an expression involving
different operators. It is also, known as hierarchy of operators. Associativity decides in which
direction operator works in an expression. Most of the operators have associativity from left to
right, but some operators have associativity right to left. Unary Operators work on a single
operand and they have highest precedence among three types of operators. Binary operators
work on two operands at a time. Most of the java operators are binary operators. Ternary
operators work on three operands at a time. The only ternary operator available in Java is
conditional operator.

42

Glossary

Operator : a symbol used in Java, to indicate an operation or calculation to be performed.


It is a part of java character set.Operand: on which an operation or calculation is
performed.

Expression: a combination of operators and operands.

Unary : an operator that works on a single operand

Binary operator: an operator that works on two operands.

Ternary operator: an operator that works on three operands at a time, there is only one
ternary operator in java.

Conditional operator: only ternary operator in Java, its symbol is ? :

Precedence: order in which operators are applied. Each operator in Java has fix
precedence.

Hierarchy: another name for precedence.

Associativity: direction in which an operator is solved in Java.

Expression: a combination of operators and operands.

Flow control: controlling flow of execution of a program.

Answers to Check Your Progress / Self Assessment Questions


Ans 1.Operator indicates operation to be performed; operand is value on which operation is
performed.
Ans 2.Unary, binary and ternary.
Ans 3.Unary operators have highest precedence among unary, binary and ternary.
Ans. 4.xy+yx will be written as : x*y + y *x.
Ans 5.1%5 gives 1, 5%1 gives 0, 5%5 gives 0, 1+0+0 gives 1, so final answer is 1.
Ans 6.3<4 gives true, 5<6 gives true, finally true || true gives true. So final answer is true.
Ans 7. Not of true is false. So anwer is false.

43

Ans. 8.A=b++ will assign current value of b to a and then b will be incremented independent of
a, where as in a=++b, first b will be incremented and then incremented value of b will be
assigned to a.
Ans 9.Bit wise and (&), bit wise or (|), bit wise complement(~) and bit wise xor (^)
References / Suggested Readings
1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
Ques 1. Which are various binary operators in Java?
Ques 2.What is meant by precedence and associativity of an operator?
Ques 3.Explain the various shift operators in Java?
Ques 4.Explain the working of conditional operator in Java.
Ques. 5. Solve following :
i.
Find value of y and z.
x=10 ;
y=x++
z=++x;
ii.
Find value of y and z in :
x=10 ;
y=x<<2 ;
z=x>> 2;
iii.
Find value of y in :
x=10
y=x>=10? 20 : 30 ;

44

PDCA-201
Programming in Java
Unit-2.Lesson-4.

Control Structures branching

Chapter Index
Objectives
Introduction
Flow Control
Control Structures
Branching (Selection)
Simple if
if else
Nested if
if else ladder
switch
Summary
Glossary
Answers to Check Your Progress / Self Assessment Questions
References / Suggested Readings
Model Questions

Objectives

Knowing the meaning of decision making in programming.

Studying various flow control statements available in Java.

Exploring various selection statements available in Java.

Knowing various types of if statement.

Studying switch statement available in Java.

Introduction
Sometimes it is necessary to add decision making in our Java program. It means enabling our
Java program to decide whether or not to execute a group of statements. This decision may be
taken depending upon some condition. Decision making adds some intelligence to our program.

45

It changes the default behavior of the Java program whereby it executes each and every
statement of program from top to bottom.
Flow Control
In Java, the execution of the program begins with the main( ) method. The main( ) method
contains a group of statements that are executed sequentially one statement after the other. The
program terminates after executing the last statement of the main( ) method. The default
execution of statements can be controlled in a customized way using the controlstatements that
causes the flow of execution to branch or execute a block of statements repeatedly based upon
some condition.

Control Structures
The control statements in Java can broadly be put into three categories namely branching
(selection), iteration (looping), and jump statements. The branching statements chooses between
alternative paths or group of statements depending upon the outcome of a certain condition or
group of conditions. The iteration statements execute a block of statements repeatedly or
multiple times, based on condition. The jump statements are used to shift or transfer the control
to a specific part of the program.
Branching Statements (or Selection Statements)
The selection statements interrupt the normal flow of the program and makes selectionbetween
alternative paths depending upon the conditions outcome value while the program
executes.There are following four types of selection statements in Java, these are:

Simple if Statement

if-else Statement

else if ladder

switch statement

Simple if
The simple-if statement executes a certain piece of code only if a particular condition given with
if statement evaluates to true. If the condition evaluates to false, then no action will be taken

46

and the statements associated with if-block are skipped and the execution starts following the
next statement after the if-block.
if (<conditional expression>)
{
<groupor block of statements>; this is if block.
}

Where
if is a keyword in Java,
<conditional expression>is a boolean expression that evaluates to boolean values true or false.
<Group of statements> denotes compound statement called true part of if is executedonly when
condition is true.
Curly braces ({ and }) denote beginning and end of true block of if.
The flow chart of simple-if is shown in fig. 4.1.

Conditional
expression
expression
false

true

Group of statements

Next statement
Figure 4.1 Flow chart of simple if statement
The use of simple-if statement is demonstrated with the help of an example:

import ava.util.* ;
class SimpleIfDemo
{
public static void main(String[] args)
{
double pay, incomeTax, netPay ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter Basic Pay :");
pay = sc.nextDouble();
incomeTax =0;
netPay = pay ;
if(pay >= 30000)
{
incomeTax = pay * 30 / 100 ;

47

netPay = pay - taxded ;


}
//System.out.println("Income Tax : " + incomeTax) ;
System.out.println("Net Pay : " + netPay) ;
}
}
Output
Enter Basic Pay :42750
Net Pay : 29925.0

if-else
The simple if statement only executes a group of statements only if a condition or expression evaluates to true.
The if-else statement enables a program to make a selection between two different paths. The if block is
executed only if the condition is true and the else-block is executed only if the condition is false. The if-else
statement has the following syntax:

if (<conditional expression>)
{
<Statement Group 1>
}
else
{
<Statement Group 2>
}
The flow chart of if-else statement is shown in fig. 4.2.

False

Conditional
expression

<Statement Group 1 >

expression

True

<Statement Group 2 >

Next statement
Figure 4.2 Flow chart of if-else statement

Program to check if a number is even or odd


import java.util.* ;
class IfElseDemo
{

48

public static void main(String[] args)


{
int n ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter a integer number :");
n = sc.nextInt();
if(n % 2 == 0)
System.out.println("Number "+n+" is even ") ;
else
System.out.println("Number "+n+" is odd ")
}
}
Output
Enter a integer number :87
Number 87 is odd

Nested if
In a nested if statement, the if statement contains another if statement. The child if-else block can
be inserted either within the parent if-block or else-block. The nested if statement is useful in
complex situations, where a hierarchy of conditions is checked to choose an alternative path.The
general form of if else statement is:
if(condition1)
if(condition2)
if(condition3)
statement group 4
else
statement group 3
else
statement group 2
else
statement group 1
In the nested if-else statement, the condition of outermost if block is evaluated first. If it
evaluates to false, then the statement group 1 in the outermost else is executed and if-else is
terminated. On the other side, if the condition1 evaluates to true, then control jumps to execute
the next inner if statement. If the result of condition2 is false, then the statement group 2 is
executed. Otherwise, condition3 is evaluated. If outcome of condition3 is false, statement group
3 is executed, otherwise the statement group 4 is executed. The flow chart of nested if else
statement is shown in fig. 4.3.

49

Condition1

False

Statement Group-1

True
Condition 2

False

Statement Group-2

True
Condition 3

False

Statement Group-3

True
Statement
Group-4

Next Statement

Figure 4.3 Flow chart of nested ifelse statement

Program to find greatest of three numbers


import java.util.* ;
class NestedIfElseDemo
{
public static void main(String[] args)
{
int a,b,c ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter three integer values :");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
if(a > b)
{
if ( a > c )
{
System.out.println("Number "+a+" is greatest ") ;
}
else
{
System.out.println("Number "+c+" is greatest ") ;
}
}
else
{
if ( b > c )

50

{
System.out.println("Number "+b+" is greatest ") ;
}
else
{
System.out.println("Number "+c+" is greatest ") ;
}
}
}
}
Output
Enter three integer values :45 95 22
Number 95 is greatest

51

if else ladder
If-else ladder is useful in situations where we have to opt one path from many alternatives
available. For such situations, Java provides nested if-else-if ladder, using which, it is possible to
combine together several ifs and elses. But out of multiple alternatives written using many ifs
and many elses only one is executed and remaining all are skipped.
The general form of if..else..ifladder is shown here:
if(condition-1)
statement group 1
else if(condition-2)
statement group 2
else if(condition-3)
statement group 3
else
statement group 4
The conditions such as condition-1, condition-2 and condition-3 etc. are boolean expressions and
are evaluated from top to bottom one by one until an expression evaluates to true. As soon as a
true condition is found, the block of statements associated with it is executed and the rest of the
ladder is skipped. If none of the condition is true, the final else (optional)given at the end will be
executed. If the final else is missing, then no action takes place if all other conditions are false.
The flow chart representing if-else-if ladder is shown in fig. 4.4.
True

Condition1

Statement Group 1

False

Condition2
False

True

Statement Group 2
True

Condition3

Statement
Group 3

False

Statement Group 4
-

Next Statement

52

Figure4.4 Flow chart showing if else ladder

Program to get day number from user (1-7) and display print day name
import java.util.* ;
class IfElseLadderDemo
{
public static void main(String args[ ])
{
int week ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter a day (1-7) : ");
week = sc.nextInt() ;
String name ;
if(week == 1)
name = "Monday";
else if (week == 4)
name = "Thursday ";
else if(week == 3)
name = "Wednesday";
else if(week == 2)
name = " Tuesday";
else if(week == 5)
name = "Friday";
else if(week == 6)
name = "Saturday";
else if(week == 7)
name = "Sunday";
else
name = "Wrong week";
System.out.println("Name of the day is " + name) ;
}
}
Output
Enter a day (1-7) : 4
Name of the day is Thursday
Check Your Progress / Self Assessment Questions
6

Ques 1.What is the difference between simple-if and if-else statement?

53

Ques 2. Can we combine two relational conditions in an if statement?

Ques 3. Can we include an if statement in another if statement?

Ques 4. Is there any limit of if-else-if ladder?

Switch Statement
Although, the if-else-if ladder is good for selecting between multiple alternatives, but it is
confusing and complicated to understand. Java provides a solution to this problem in the form of
the switch statement. It is used to select one of several alternative paths in a program and the
choice is based upon aninteger value. A jumping statement break is used inside switch to transfer
the control outside switch block after performing required case or cases. The general form of
switch is as follows:
switch (<expression>)
{
case value_1:
statement block_1
break;
case value_2:
statement block_2
break;
:
case value_N:
statement block_n
break;
default:
default statement block
}
The flow chart demonstrating the switch statement is shown in fig. 4.5.

Expression

= Value_1

Statement block 1

= Value 2

= Value n

Statement block 2

...

Statement block n

Nextstatement

54

No match

Default Statement block

Figure4.6 Flow chart of switch statement

The switch block is declared using a keyword switch followed by the expression enclosed in the
parentheses. The body of the switch statement contains multiple switch blocks containing a
group of statements enclosed within curly braces. The <expression> can be a variable or any
boolean expression that evaluates to an integer value. The variable used inside switch must be
either byte, short, char, or int. It must not be long, either of the floating-point types, boolean, or
any object references. Strictly, we can say that the value must be assignment compatible with
integer values such as value1, value2, valuen which are case labels and are defined using the
keyword case followed by colon and can of data type char, byte, short or int. The default case is
optional and can be defined using the keyword default followed by colon.
The switch statement works like this:

The integral expression is evaluated first to yield a single value.

The value of the expression is successively tested against a list of case labels of data type
char, byte, short or int. When a match is found, a statement block associated with that
case label is executed.

If no case label is equal to the value of integral expression, the statement associated with
the default label is performed.

The break statement is optional and is used to exit from the switch block. If you omit the
breakstatement, execution will continue to the next case. Execution jumps to the default
statement if none of the case labels matches with the expression of theswitch( ) statement. In the
absence of default case, no action takes place if all matches fail. Although the default statement
is shown at the end of the switch( ) block in the above example, there is no rule that requires this
placement.Several case labels can have the same associated statement block. In that case, same
block of statements will execute for different case labels.
Program to get month number from user (1-12) and display the number of days in a month
import java.util.* ;
class SwitchDemo
{
public static void main(String args[ ])

55

{
int month ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter a month (1-12) : ");
month = sc.nextInt() ;
switch(month)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
System.out.println("Month has 31 days") ;
break ;
case 4: case 6: case 9: case 11:
System.out.println("Month has 30 days") ;
break ;
case 2:
System.out.println("Month has 28 days") ;
break ;
}
}
}
Output
Enter a month (1-12) : 4
Month has 30 days
A switch statement can be included in another switch statement known as nested switch
statement. Since eachswitch statement has its own independent block therefore, no conflicts arise
between the case labelof the inner switch and those of the outer switch. For example:
public class NestedSwitchDemo
{
public static void main(String[ ] args)
{
int a = 1, b = 2;
switch(a)
{
case 0:
System.out.println(" Value of a is 0 ") ;
switch(b)
{
case 0 :
System.out.println(" b is 0 ") ;
break ;
case 1 :
System.out.println(" b is 1 ") ;
break ;

56

default :
System.out.println("Default case of Nested Switch !!") ;
}
break ;
case 1:
System.out.println(" Value of a is 1 ") ;
switch(b)
{
case 0 :
System.out.println(" b is 0 ") ;
break ;
case 1:
System.out.println(" b is 1 ") ;
break ;
default :
System.out.println("Default case of Nested Switch !!") ;
}
break ;
default:
System.out.println("Default Case of Outer Switch !! ");
}
}
}
Output
Value of a is 1
Default case of Nested Switch !!

Check Your Progress / Self Assessment Questions


10 Ques 5.Can we use float or double variable or expression in a switch statement?
11 Ques 6. Can we attach more than one label with the switch block?
12 Ques 7. What is the use of break statement in the switch block?
13 Ques 8. What is the role of default statement block in a switch statement?

57

Glossary

flow control : to control the flow of execution in a program.

selection statements :category of statements in Java that are used for selecting which
one out of two blocks will execute depending upon some condition.

branching statements : same as selection statements.

decision making : to make a decision after evaluation a condition.

if :Java keyword and statement, also called simple if or if without else.

if-else :Java keywords, used to true and false blocks, one of these two block will execute.

nested if : a type of if statement, used when there are 2-4 choices to be evaluated.

else if ladder : a type of if statement used when there are many choices to be evaluated.

switch :Java keyword and statement, used when there are many choices to be evaluated.

case : Java keyword, used inside switch statement.

Answers to Check Your Progress / Self Assessment Questions


Ans 1.The simple-if is without else part where as if-else contains a else block.
Ans 2.Yes
Ans 3.Yes
Ans. 4.No
Ans 5.No
Ans 6.Yes
Ans 7.The break is used to jump out of the switch block.
Ans. 8.The default statement block is used to execute the statements when no label match with
the switch variable.

58

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. Which are various selection statements?
2. What is difference between simple if and if else statements?
3. Which are different types of if statement in Java?
4. What is use of nested if statement? Give an example.
5. What is use of else if ladder? How does it differ from nested if statement?
6. What is use of switch statement in Java? Give an example.
7. Which are various differences between else if ladder and switch statement?
8. Which are various limitations of switch statement in Java?
9. Write a program to find smallest of three numbers using nested if statement.
10. Write a program to calculate roots of a quadratic equation.

59

PDCA-201
Programming in Java
Unit-2.Lesson-5.

Control structures Looping

Chapter Index
Objectives
Introduction

Looping

The while Statement

The do-while Statement

The for Statement

Additional features of for loop

Nesting of for loops

Jumps in Loops(Jumping out of a loop, Skipping a part of a loop)

Labeled Loops

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

To know the meaning and importance of iterative code in programming.

To study various types of looping statements available in Java

To understand the difference between entry controlled and exit controlled

To know how control can be shifted outside a loop

To know the significance of nested loops.

60

61

Introduction
In the previous chapter, we have studied how to execute a group of statements and skip another
group on the basis of some conditions. Similarly, sometimes it may be required to execute a
block or group of statements more than once, this is called repetition. In this lesson, we will
study how repetition can be performed in Java program. Such type of code is called iterative
code. There are different ways to make iterative code, using looping statements provided by
Java. These statements are the topic of discussion of this lesson.
Looping
The loopingstatements allow a group of statements to be executed repeatedly and are also known
as iterative statements. The block of statements associated with a loop is executed multiple times
based on aboolean expression or condition. It is commonly used to determine when to terminate
the loop. The loop body contains a single statement or a block of statements. Java provides
following looping statements:

while Statement

do-while statement

for statement

for each statement

The while Statement


The while statement is an entry controlled looping statement that means, the condition is checked
first at the entry of the loop. If conditionevaluates to false the loop will not execute at all. The
statements to be executed are written inside the curly braces constitute the body of the loop. The
curly braces are not required if the body of the loop contains only a single statement.
The syntax of the while loop is:
while(condition)
{
<body of loop>
}

62

The flow chart of the while loop is shown in fig. 5.1.

True

condition

Body of Loop

False

Next Statement

Figure 5.1 Flowchart of while statement.


The conditioncan be any relational expression that evaluates to either true or false. It is evaluated
each time before executing the loop body. The body of the loop will be executed again and again
as long as the condition is true. When the conditionbecomes false, control exits from the loop
and passes to the next line of code immediately following the loop.
Program to calculate the mean of first n integer values.
class WhileLoopDemo
{
public static void main(String args[ ])
{
int i = 1 ;
double sum = 0 ;
double mean ;
int n =5; //assume n is 5.
while(i <= n)
{
sum += i ;
i++ ;
}
mean = sum / n ;
System.out.println("Value of Mean = " + mean);
}
}
Output
Value of Mean = 3.0

63

Program to find sum of digits of a given number


import java.util.* ;
class SumOfDigitsDemo
{
public static void main(String args[ ])
{
int n, temp, digit, sum =0 ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : " ) ;
n = sc.nextInt( );
temp = n ;
while( temp > 0)
{
digit = temp % 10 ;
sum = sum + digit ;
temp = temp / 10 ;
}
System.out.println("Sum of Digits of " + n + " is " + sum) ;
}
}
Output
Enter a Number : 5681
Sum of Digits of 5681 is 20

Check Your Progress / Self Assessment Questions


Que. 1.True/False :Body of while loop may contain a single statement or multiple statements or
can be empty also.
Que. 2. True/False :If the condition is false at the start, statements inside body of loop will not
execute even once.

64

The do-while Statement


The do-while loop is similar to while loop. The only difference between do-while and while is
that do-while evaluates its condition at the bottom of the loop instead of the top. Therefore, the
statements within the do block are always executed at least once. Syntax of do-while loop is :
do
{
<body of loop>
} while (condition) ;

Do loop starts here

Group of Statements

condition

true

False

Next
Statement

Figure 5.2 Flow chart of do-while loop.


In do-while loop, the condition to be evaluated comes
after the loop body, thus the do-while loop
is called exit controlled loop, because the condition is evaluated after executing the loop body.
This means that a do-while loop will always execute at least once even if the condition becomes
false at the start of the loop. The do-while statement executes the loop body as long as the loop
condition is true. When the loop condition become false, the loop is terminated and execution
continues with the statement immediately following the loop.
Program to evaluate sum of even numbers between 1 to 100.
class DoWhileDemo
{
public static void main(String args[ ])
{
int sum = 0, i = 2 ;
do
{
sum += i ;

65

i=i+2;
} while( i < 100 ) ;
System.out.println("Sum of even numbers between 1 to 100 = "+sum) ;
}
}
Output
Sum of even numbers between 1 to 100 = 2450

Check Your Progress / Self Assessment Questions


Que. 3. True/False :In case of while loop, body of loop follows condition whereas in case of
dowhile loop body of loop precedes loop condition.
Ques. 4. Find value of x at the end of loop :
int x=5;
do
{
x--;
}while(x>5);

The for Statement


The for loop statement provides a compact way than while or do-while, to iterate over a range of
values. The for loop is used when we know in advance the exact number of times a statement or
group of statements need to be executed. The syntax of the for loop statement is:
for(<initialization> ; <condition> ; < update expression>)
{
<body of loop>
}

The <initialization>part is used to declare and initializes loop control variables

that

controls the execution of the <loop body>. Initialization part is executed only once,when
the loop starts.

66

The <condition> is a boolean expression, usually involves the loop control variable. The
conditional expression is used to test the loop control variable against a target value such
that if the condition is true, the loop body is executed. When the condition becomes false,
the execution continues with the statement following the for loop.

After each iteration, the <update expression> is executed to update the value of the loop
control variable to ensure loop termination. The expression may increment or decrement
the value of the control variable. After execution of the update expression, the condition is
tested again to determine if the loop body should be executed again or not.

The flow chart of the for loop is shown in fig. 5.3.


initialization
False

condition
True
Group of
statements

update expression

Next Statement

Figure 5.3 Flow chart of for loop


Program to generate a multiplication table.
import java.util.* ;
class ForLoopDemo
{
public static void main(String args[ ])
{
int n, prod = 0 ;
Scanner sc = new Scanner(System.in);

67

System.out.print("Enter a Number : " ) ;


n = sc.nextInt( );
for(int i=1 ; i <= 10 ; i++)
{
System.out.println(n+" X "+i+" = "+(n*i)) ;
}
}
}
Output
Enter a Number : 7
7X1= 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
Additional features of for loop
The loop control variable can be incremented or decremented by any amount. For example:
Program to evaluate the sum of odd numbers.
import java.util.* ;
class ForLoopDemo
{
public static void main(String args[ ])
{
int n, sum = 0 ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : " ) ;
n = sc.nextInt( );
for(int i=1 ; i <= n ; i= i+2)
{
sum += i ;
}
System.out.println("Sum of odd numbers upto "+n+" numbers = "+sum) ;
}
}

68

Output
Enter a Number : 75
Sum of odd numbers upto 75 numbers = 1444

Multiple statements can be included in both <initialization> and <update expression>. Each
statement is separated from each other using comma operator. For example, in the following
code, two variables i and j are initialized in the initialization part. Also two increment expression
are used in the update expression part.
int i, j
for(j=1 , k = 5 ; j + k < 10 ; j++, k++)
{
// Body of loop
}
Note that while using comma operator, you can not mix expressions with variable declarations,
nor can you have multiple declarations of different types. So the following statement would be
illegal:
int i = 1 ;
for(i++, int j = 0 ; i < 10 ; j++) { }

//illegal

Example:
class MultiStatDemo
{
public static void main(String args[ ])
{
int i, j;
for(i=1, j=10 ; i < j ; i++, j--)
System.out.println("i = " + i+", j = "+j);
}
}
Output
i = 1, j = 10
i = 2, j = 9
i = 3, j = 8
i = 4, j = 7

69

i = 5, j = 6

In the conditional expression of the for loop, normally the loop control variable is tested against
a target value so as to exit from the loop. The variation of this is that any boolean expression can
be used that does not include the loop control variable. For example:

70

import java.util.Scanner ;
class MoreForLoopDemo
{
public static void main(String args[])
{
int i, n ;
double avg, sum = 0 ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : " ) ;
n = sc.nextInt( );
boolean limit = false;
i = 1;
for( ; !limit; )
{
sum += i ;
if(i == n) limit = true;
i++;
}
avg = sum / n ;
System.out.println("Average = " + avg);
}
}
Output
Enter a Number : 1000
Average = 500.5

An infinite for loop can be created by leaving the conditional expression or update expression or
all the parts blank. There are different ways to create infinite loop using for statement, these are :

for(int i=1 ; ; i++) { }

for(int i=1 ; i < 50 ; ) { }

for( ; ; ) { }

Nesting of for loops


A loop can be inserted inside another loop. The loop to be inserted is called inner loop and the
loop that contains another loop is called outer loop.The nested loop works in such a way that, for
each iteration of the outer loop, all iterations of the inner loop are carried out. In more details,

71

first pass or iteration of the outer loop triggers the inner loop, which executes to its completion
i.e. runs all iterations of the inner loop. Then the second pass of the outer loop triggers the inner
loop again and runs it to completion. This repeats until the outer loop terminates. Any number of
loops can be nested. For example:
class NestedLoopDemo
{
public static void main (String[ ] args)
{
int n=7, x=5, y= 1;
for(int i=0; i <= n ;i++)
{
for(int j=1; j <= i ; j++)
{
System.out.print(y + "\t");
y = y + x;
}
System.out.println("");
}
}
}
Outut
1
6
16
31
51
76
106

11
21
36
56
81
111

26
41 46
61 66 71
86 91 96 101
116 121 126 131

136

Check Your Progress / Self Assessment Questions


Que. 5. Find output of following program
int i=5 ;
int j=10;
for(i=5; i<10; i++)
{
j=j + i ;
j- - ;
}
System.out.println(J= + j ) ;

72

73

Jumps in Loops (Jumping out of a loop, Skipping a part of a loop)


The jump statements are used to transfer control to another part of the program and thus, breaks
the sequential flow of the program.Java supports three statements for this purpose.

break

continue

return

break Statement
In loops, the break statement is used to exit from the loop. In such a case, the loop is terminated
immediately and the remaining code in the body of the loop is skipped. The program control
transfer to the next statement after the loop. Figure 5.4 demonstrates the use of break.
statement1
statement2
:
start of loop

statement is executed

Loop body

:
if (<condition>)
break ;
Flow when
: break

Normal flow

end of loop

Statement outside loop body


Figure 5.4 Using break statement in a loop.
Example
class BreakLoopDemo
{
public static void main(String args[ ])
{
for(int i=2; i<100; i = i+2)
{
if(i == 10)
break ;
System.out.println("I = " + i);
}
System.out.println("Statement after loop");
}

74

}
Output
I=2
I=4
I=6
I=8
Statement after loop
continue Statement
The continue statement can be used in loops to prematurely stop the current iteration of the loop
body and to start with the next iteration. In whileand do-whileloops, a continuestatement causes
control to be transferred directly to the conditional expression that controls the loop. In a forloop,
control first transfers to the iteration portion of the forstatement and then to the conditional
expression. The figure 5.5 demonstrate the use of continue statement in the for loop.

statements
:

:
continue ;
:

Loop body

start of loop body

if (condition)
end of loop
body

Normal flow
Flow when continue
statement is executed

Figure 5.5 Using continue statement inside loop


For example:
class ContinueLoopDemo
{
public static void main(String args[ ])
{
int sum = 0 ;
for(int i=1; i <= 50 ; i++)
{
if(i%2 == 0)
continue ; //Rest of loop body skipped if i is divisible by 3
sum += i ;
}
System.out.println("Sum of odd numbers = "+sum);

75

}
}
Output
Sum of odd numbers = 625

Check Your Progress / Self Assessment Questions


Que 6 Find output .
int i=5 ;
int j=10;
for(i=5; i<10; i++)
{
j=j + i ;
j- - ;
if (j>30)
break;
if(j<20)
continue;
}
System.out.println( Now J= + j ) ;
return Statement
The return statement when used inside a method will stop the execution of the current method
and transfer the control back to the calling method. The return statement can be used in two
forms:
return or

return <expression>

The first form return just the control not return any value to the calling method. In the second
form, the <expression> is evaluated and the result obtained is returned to calling method.

Labeled Loops
In labeled loops, Java provides labeled jumping statements such as labeled break and continue
statement. The syntax of labeled break and continue are:
break label;
continue label ;
where, the label is a name that identifies the block of code.

76

Labeled break
The labeled break statementcan be used in any looping statement that causes an immediate exit
from any number of nested blocks. The control is transferred to the first statement given after the
corresponding labeled block. For example:
class LabeledBreakDemo
{
public static void main(String a[])
{
int i ;
OUT :
{
for(i=0; i<5; i++)
{
while (true) //infinite loop
{
System.out.println("Inside Inner Loop");
break OUT ;
} // inner loop ends
// System.out.println("Outer loop."); // Unreachable.
} // outer loop ends
} //OUT block ends
System.out.println("Exited from all nested blocks") ;
}
}
Output
Inside Inner Loop
Exited from all nested blocks

Labeled continue
Java providesa labeled continue statement that skips the remaining code in the body of the loop
and any number of enclosing loop statements. It proceeds with the next iteration of the enclosing
labeled loop statement. In a labeled while and do-while statements, the condition will be first
tested after executing the continue statement. In a labeled for loop statement, the increment
expression will be tested and the condition is evaluated.
Example:
classLabeledContinueDemo
{

77

public static void main(String args[ ])


{
OUT: // label
for (int row = 1; row <= 5; row++)
{
System.out.println( ) ;
for (int col = 1; col <= 10; col++)
{
if (col > row)
{
continue OUT ;
// next iteration of the labeled loop
}
System.out.print("*") ;
} // inner for( ) loop ends
} // outer for( ) loop ends
System.out.println( ) ;
System.out.println("Statement after outer forloop...." );
}
}
Output
*
**
***
****
*****
Statement after outer forloop....

Glossary

Iteration: one repletion of body of loop.

Iterative code : repetitive code. That is body of loop.

Loop : technique used to create iterative code.

Entry controlled: a type of loop where looping condition precedes loop body.

Exit controlled: a type of loop where loop body precedes looping condition

for loop: a type of entry controlled loop, a statement and keyword of Java, has 3 optional
parts.

while loop: another type of entry controlled loop, a statement in java, a keyword of Java.

do while loop : a type of exit controlled loop in Java.

78

break: a keyword of java, a statement to shift control from one statement to another
statement in another part of program.

continue : a keyword of Java, a statement used inside a loop body to start next iteration
of loop.

Answers to Check Your Progress / Self Assessment Questions


Ans 1. True
Ans 2. True.
Ans 3. True
Ans. 4. Value of x at end of loop is 4.
Ans 5.J=40
Ans 6. Now J=32

79

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press

Model Questions
Que. 1. What is meant by iterative code? What is difference between entry controlled loop and
exit controlled loop?
Que. 2. Which are different types of looping statements available in Java?
Que. 3. What is the syntax of for loop. Give an example.
Que. 4.How does while loop differ from a for loop?
Que. 5. Write a program to display first n elements of Fibonacci series using while loop.
Que. 6. How does while loop differ from do while loop?
Que.7. Explain for each loop available in Java.
Que. 8. Write a program to find factorial of a number using for loop and while loop.
Que. 9. What is meaning of Labeled Loop. Give an example.
Que. 10. How control can be shifted outside a loop?

80

Classes and Wrapper Classes


PDCA-201
Unit-3. Lesson - 6
Chapter Index
Objectives
Introduction

Defining a Class

Adding Variables

Adding Methods

Creating Objects

Accessing Class Members

Constructors

Inheritance

Extending a Class

Defining a subclass

Subclass constructor

Multilevel inheritance

Hierarchical inheritance

Overriding Methods

Final Variables and Methods

Final Classes

Finalizer Methods

Wrapper Classes

Autoboxing and Unboxing

Static Classes

Abstract Classes

Enumerated types and annotations

Method Overloading

81

Nesting of methods

Methods with varargs

Garbage Collection

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

Understanding the meaning and significance of classes and objects.

Learning the meaning, type and use of constructors.

Knowing the importance of inheritance and different types of inheritance.

Understanding the concept of method overloading and method overriding.

Understanding the concept of Garbage Collection.

Understanding the meaning and use of wrapper classes.

Introduction
Classes are the basic building blocks of a Java program. A class is like a structure or template that is used
to create objects. A class contains attributes and behaviour. The attributes are represented by variables
and the behaviour is represented by methods. A class is a user-defined data type that is created from
the java inbuilt primitive data types. Inheritance is one of the basic principles of object oriented
programming. Various types of inheritance will be studied here. Concept of method overloading and
method overriding will be explored.

82

6.1

Defining a Class

A class consists of variables and the methods that operate on those variables. The variables contain data
and the methods contain the code to process the data stored in variables. The variables and methods
are collectively known as class members. A class is declared using the keyword class followed by the
name of that class. The general form of a class definition is given below:
class ClassName
{
type varname_1 ;
type varname_2 ;
.
type varname_N ;

return_type methodname_1(type var_1, type var_2,,type var_N)


{

<method body>

}
return_type methodname_2(type var_1, type var_2,,type var_N)
{
<method body>
}
:
return_type methodname_N(type var_1, type var_2,,type var_N)
{
<method body>

83

}
}
As shown in the above class definition, the body of a class usually consists of instance variable and
methods.
6.1.1 Adding Variables
The variables declared within a class are also called as instance variables. The data types of instance
variablescan be of any primitive data types such as int, char, float, double etc. or can be a reference type
such as an object, array, string etc. You can define a class containing only member variables as shown
below:
class Employee
{
int empNo ;
String EmpName ;
double basicSal ;
}
The class Employee declared above contains three instance variables, empNo, EmpName and basicSal.

6.1.2 Adding Methods


A class can be declared to contain only instance variables, but it limits the applicability of the class. To
increase the power and flexibility of a class, methods are put in the class. A method contains code that
operates on instance variables and is used to perform a specific task.The return_type specifies the type
of data returned by the method. The return type can be any valid data type or class type. If a method
does not return any value, the return type should be of type void. The method_nameis any valid userdefined name assigned to a method. The variables (type var_1, type var_2,,type var_N ) are the
parameters that receive the value of the arguments at the time of calling the method. The parameter list

84

can be left blank, if a method does not require any value. Also, if a method have a return type other
than void, the method must contain a return statement of the form:
return result ;
Here, the result is the value to be returned.
For example, the class Employee as shown above is extended and contains a method findTax( ) as
illustrated below:
class Employee
{
int empNo ;
String EmpName ;
double basicSal ;
void findTax( )
{
double tax ;
percent = basicSal * 30/100.0;
System.out.println("The Income Tax is "+tax) ;
}
}
6.2 Creating Objects

An object is a physical implementation of a class and is known as an instance of a class.


Creating objects of a class is a two-step process:

Declare a variable of class type known as reference variable. The reference variable refers to the
object of the class. At this point, the reference variable contains the value null that means , it does
not point to any object yet.

85

Create an object using new operator and assign that object to a reference variable. The operator
new dynamically allocates memory for an object at runtime and returns a reference to it. In Java,
objects are manipulated through object references.

For Example
Employee e ;

creates reference variable.

e = new Employee ( ) ; creates an object

Check Your Progress / Self Assessment Questions


Ques 1. What is the difference between a class and object?
Ques 2. Which operator is used to create an instance of a class?

6.3

Accessing Class Members

Once an object of a class is created, its instance variables occupy memory and needs to be initialized.
The members of a class(variables and methods) can be accessed using the dot operator (.) with the
name of the object followed by the name of class member to be accessed. For example, the following
statements declare the Employee object and access the member empNo of the object e..
Employee e = new Employee ( )
e.empNo = 5209 ;
This statement assigns a value of 5209 to instance variable empNo within the object e.

Here is another example that demonstrates writing a class, creating objects of that class and accessing
its members to initialize them using a dot operator.
class Student New class student defined.
{

86

int rollno ;
double marks ;
public static void main(String a [ ])
{
Student ob = new Student( ) new object of Student class is created.
// assign values to data members of object
ob.rollno = 1001;
ob.marks = 567;
double result ;
result = ob.marks / 600 * 100 ;
System.out.println("The percentage is "+result) ;
}
}

6.4

Constructor

An object should be first initialized before using it in aprogram. In order to initialize an object,
each member variable of that object is initialized with some value. It is difficult to initialize all of
the variables in a class each time an object is created. For this purpose, constructor is used to
perform the initialization of variables upon creation of an object.A constructor is a special form
of a methodand is invoked automatically and immediately when an object is created using new
operator.However, there are some restrictions using a constructor:

A constructor must have the same name as the name of the class.

A constructor does not return anything by default, so no return type should be used, not even
void.

A class may have any number of constructors, this is called constructor overloading.

Every class has a default constructor. If we do not explicitly design a constructor for a class, the
java compiler builds a default constructor for that class.

87

For example:
class Student
{
int rollno ;
String name ;
double marks ;

Student(int r, String n, double m)


{
rollno = r ;
name = n ;
marks = m ;
}
double findPercentage( )
{
double result ;
result = marks / 600 * 100 ;
return result ;
}
}
class studentDemo
{
public static void main(String args[ ])
{
Student s1, s2 ;

88

s1 = new Student(1001,"Anil Kumar",123) ;


System.out.println("Marks Percentage of "+ s1.name+" is " + s1.findPercentage ( )) ;

s2 = new Student(1002,"Pawan Sharma",103) ;


System.out.println("Marks Percentage of "+ s2.name+" is " + s2.findPercentage ( )) ;
}
}

Check Your Progress / Self Assessment Questions


Ques 3. Which operator is used to access a class member?
Ques 4. What is the purpose of a constructor?

6.5 Inheritance
Inheritance is an important principle of OOPs that enables code reusability. In this mechanism, one class
(subclass) can inherit all the instance variables and methods of another class (superclass). With the help
of an inheritance, a class immediately has all the functionality of a superclass and the new subclass has
to incorporate only those things that are not present in the superclass. While creating inheritance
hierarchy, at the root level, a general class is created that contains common attributes. This class can
then be inherited by other more specific classes, each of them, adding specific things that are unique to
it. Thus, using inheritance, one needs to start from scratch.
The inheritance relationship can be shown in Fig. 6.1 using the UML class diagram using a solid line with
an arrow head pointing towards super class name.
Superclass

Subclass

89

Figure 6.1 UML diagram showing inheritance

6.6 Defining a Subclass


A subclass can be created using the keyword extends. All the members except private members are
automatically inherited in the subclass. The syntax to create a subclass is:
class subclass_name extends superclass_name
{
// members that are specific to subclass and are not persent in superclass
}
Here, the superclass is parent class that already exists.

6.7 Subclass Constructor


A subclass inherits all the public members of the superclass, it does not inherit constructors. Therefore,
the objects of subclass cannot be created and initialized using the constructor of its superclass. The
subclass require its own constructor in order to initialize objects. The constructor of superclass can be
invoked within the constructor of subclass using the keyword super. The super statement must be the
first statement in the subclass constructor.
Lets take an example to illustrate the use of constructors in inheritance:
class SuperClass
{

double a, b ;
SuperClass(double m, double n)
{

a=m;

90

b=n;
}
void print( )
{

System.out.println(a + " " + b) ;

}
}
class SubClass extends SuperClass
{

double c ;
SubClass(double m, double n, double o)
{ super(m,n) ;
c=o;
}
void mean( )
{

double result ;
result = (a + b+ c ) / 2 ;
System.out.println("Mean = "+ result) ;

}
}
class ConstructorDemo
{

public static void main(String args[])


{
SuperClass sup = new SuperClass(25,37) ;
sup.print( ) ;

SubClass sub = new SubClass(45,87,63) ;

91

sub.print( ) ;
sub.mean( ) ;
}
}

Multilevel Inheritance
In Java, hierarchies that consists of unlimited layers of inheritance can be created. So, you can create a
subclass of a class which is also a subclass of another class and so on. For example, if a class Childinherits
from class Parent, and class Parentinherits from class GrandParent, then theclass Child willacquire all
the members defined in class Parentas well as all the members declared in class GrandParent. The
multilevel inheritance is shown in Fig. 6.2 given below.

GrandParent
Parent
Child

Figure 6.2 Diagram showing multilevel inheritance

Hierarchical inheritance
In hierarchical inheritance, many subclasses inherit from a single superclass. For example, if classes
Child1, Child2 and Child3 inherit from same class Parent,thenclasses Child1, Child2 and Child3 will
acquire all the members from the class Parent. The hierarchical inheritance is shown in Fig. 6.3 given
below:

92

Parent

Child1

Child2

Child3

Figure 6.3 Diagram showing hierarchical inheritance

Check Your Progress / Self Assessment Questions


Ques 5. What is the use of inheritance?
Ques 6. What is the syntax of creating a subclass from a superclass ?

Overriding Methods
Method overriding occurs when a subclass method has the same name and type signature as a method
in its superclass. The return types of both methods must be the same. When an overridden method is
invoked by the object of subclass, it will always refer to the version of a method defined by the subclass.
This can be demonstrated with the help of an example.
class SuperClass
{
double a ;
double b ;
SuperClass(double m, double n)
{
a=m;
b=n;
}
void mean( )
{
double result ;
result = (a + b ) / 2 ;
System.out.println("SuperClass Mean = "+ result) ;
}

93

}
class SubClass extends SuperClass
{
double c ;
SubClass(double m, double n, double o)
{
super(m,n) ;
c=o;
}
{

void mean( )
double result ;
result = (a + b+ c ) / 2 ;
System.out.println("Sub Class Mean = "+ result) ;

}
class ConstructorDemo
{
public static void main(String args[])
{
SuperClass sup = new SuperClass(25,37) ;
sup.mean( ) ;
SubClass sub = new SubClass(45,87,63) ;
sub.mean( ) ;
}
}

Final Variables and Methods


A final variable is a named constant whose value cannot be modified during the execution of the
program. Thus, the final variables must be initialized at the time of declaration. Final variables do not
occupy memory upon creation of different objects. It is a common convention to use uppercase
identifiers to represent final variables. The variable can be declared final using the modifier finalbefore
the type specifier. For example final int MAX_MARKS = 1200.
Final methods cannot be overridden. It means when you define a final method in a superclass, its
subclass cannot override that method in its own class. Methods can be declared final using the modifier
final at the start of its declaration. For example
final void area( )
{

94

// Method body
}

Final Classes
Final classes prevent inheritance and thus, cannot be inherited. When a class is declared as final, all of its
methods are implicitly declared as final. To declare a final class, use the modifier at the beginning.

final class Test


{
void print( )
{
System.out.println(This is a final method by default) ;
}
}

Check Your Progress / Self Assessment Questions


Ques7.How it will decide, which version of method is to be invoked?
Ques8.Can we override the final methods?
Ques9.Which keyword is used to declare final variables?

Finalizer Methods
Finalizer Methods are used in a garbage collection mechanism, in which the objects are
automatically destroyed when no reference of that object exist and the memory occupied by that
object is reclaimed. Sometimes, an object eligible for garbage collection occupies some
resources such as file or database connection for reading or writing purpose, then those resources

95

must be released before the object is destroyed. For this purpose, Java provides a mechanism
called finalization. You can add a finalizer in your class by simply defining the finalize( )
method. Java run time calls this method automatically, whenever the object of that class is about
to destroy. The syntax of the method is:

protected void finalize( )


{
//code here
}

Wrapper Classes
Java uses simple data types such as byte, short, char, int, float, double and boolean that cannot be
treated as objects. Sometimes, an object representation of these types is required so as to perform
various operations. For this purpose, Java Provides wrapper classes corresponding to each of
these simple types. All the wrapper classes reside in java.lang package and its hierarchy is
depicted in Fig. 6.4.

96

Object

Number

Short

Byte

Character

Intege
r

Long

Float

Double

Boolean

Figure 6.4 Hierarchy of Wrapper classes

Autoboxing and Unboxing


The term boxing refers to automatic conversion of primitive type to an object of corresponding wrapper
class such as int to java.lang.Integer. Conversely, unboxing refers to conversion of wrapper object to its
equivalent primitive type such as Integer to int. The boxing and unboxing occurs in assignment
expressions, mathematical expressions and methods. For example:
public class BoxingDemo
{
public static void main(String args[ ])
{
double d = 15.25;

// boxes double to Double object

d = d + 20.20 ;

// unboxes the Double to a double

System.out.println("Double value : "+d);


}
}

Check Your Progress / Self Assessment Questions


Ques10.What is the use of finalize( ) method?
Ques11.What is the name of wrapper class for integer?

97

Static Classes
A static class is created inside another class is called static inner class. The static inner class can access
only static variable and methods of its outer class including private. We cannot create an object of static
inner class without the reference of outer class. This can be illustrated with the help of an example:
class Outer
{ static int i = 95;
static class Inner
{ void print( )
{
System.out.println("Value of i ="+i) ;
}
}
}
class Test
{ public static void main(String args[])
{ Outer.Inner ob = new Outer.Inner( ) ;
ob.print( ) ;
}
}
Abstract Classes
Abstract classes are partially completed classes and contain one or more abstract methods. The abstract
methods are non-implementing methods having no body. An object of an abstract class cannot be
created but we can declare a reference variable of an abstract class. Any subclass of an abstract class
must either implement all of the abstract methods from the abstract class or declare itself as an abstract
too. An abstract class may also contain non-abstract methods. To declare a class abstract, the abstract
modifier is used with the name of the class. The syntax is:
abstract class AbstractClassName
{

abstract void print( ) ;


void display( )
{
// code here
}

// abstract method

Check Your Progress / Self Assessment Questions

98

Ques12. Can a static class access non-static members?


Ques13.Can abstract class contain instance methods?
Enumerated types and annotations
Enumerated types are available in C and C++ also. In Java, they are used to create a new data type,
specifically a collection of constants. It is a special kind of Java class that may contain constants,
methods etc. This feature was added in Java with version Java 5. Java provides keyword, enum which is
used in place of class or interface to create an enumerated type. The Java enum keyword signals to the
Java compiler that this type definition is an enum.For example to create a new enum COLOR, we can
write :
public enum Color
{
RED,
GREEN,
BLUE,
}

Later, this can be referred like : Color c = Color.RED ;

Annotations
Feature of annotations were added to Java from Java version 5. In, Java language, annotations are used
to provide meta data. This meta data is special data that gives information about some other data.
Being meta data, annotations do not affect the execution of java program directly.
Annotations in java, are basically used for the purposes like, Compiler instructions, Runtime instructions
and Build-time instructions.
There are built-in java annotations which are predefined in java. these are : @Deprecated, @Override,
@SuppressWarnings
Broadly, there are three types of annotations as explained below :
1) Marker Annotation : This is type of annotation that does not have any method in its body. For
example:

99

@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations in Java.

2) Single-Value Annotation : This is type of annotation that has one method definition in its body. For
example:
@interface MyAnnotation
{

int value( );

}
It can be provide a default value also, like :
@interface MyAnnotation
{

int value( ) default 0;

}
Single annotaion can be used as : @MyAnnotation(value=33)

3) Mulit-Value Annotation : An annotation that has more than one method defined in its body, is called
Multi-Value annotation. For example:
@interface MyAnnotation
{

int val1( );
String val2( ); String val3( );

}
These can be provided default value also. For example :
@interface MyAnnotation

100

int val1( ) default 1;


String val2( ) default "";
String val3( ) default "xyz";

}
Method Overloading

In Java, different methods with the same name but different signature can be defined and is
known as method overloading. The signature of methods includes the number and/or type of
parameters. The difference in return types alone is not sufficient for the methods to be
overloaded. Method overloading implements polymorphism. Whenever, an overloaded method
is called, Java run time search for a matching method based on arguments supplied at the time of
the method call, to determine which version of the overloaded method is to be invoked. This can
be illustrated with the help of an example:

class Overloading
{
void max(int a, int b)
{
int big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two integer values = " + big) ;
}
void max(double a, double b)
{
double big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two double values = " + big) ;
}
}
class OverloadingDemo
{
public static void main(String args[])

101

{
Overloading ob = new Overloading( ) ;
ob.max(6,19);
ob.max(45.2, 34.5) ;
}
}
Nesting of Methods
When a method in a class invokes another method within the same class, it is known as nesting
of methods. In order to call a method in the same class, dot(.) operator is not required. It is
possible to call more than one method in the same class. This can be demonstrated with the help
of an example:
class NestingMethod
{
int a ;
int b ;
int big ;
void max(int a, int b)
{
if(a > b)
big = a ;
else
big = b ;
display( ) ;
}
void display( )
{
System.out.println("Maximun of two integer values = " + big) ;
}
}
class NestingMethodDemo
{
public static void main(String args[])
{
NestingMethod ob = new NestingMethod( ) ;
ob.max(16,19);
}
}
Methods with Varargs (Variablearguments)
Class methods can be defined with variable number of arguments also. An example of such a
method is println method that can print any number of values passed to it as arguments. Varargs

102

feature was added in Java version 5. To declare a method that may later take 0 or more
arguments, the syntax includes three dots (called ellipses).
Before the feature of variable arguments, either method overloading is used (it uses program
code larger) or method argument has to be an array of n elements but it makes little complicated
code.
While using a method with variable arguments, some rules have to be followed, otherwise
program code does not compile successfully.
There can be at maximum, only one variable argument in a method.
If used, the vararg must be the last argument in the method
Example.
public class Varargs
{ public static void main(String args[])
{ ShowMessage(5, "Hello", "Hi");
ShowMessage(3, "Hello", "Good Morning", "How are you?");
}
public static void ShowMessage(int x, String... args)
{ System.out.println("x =" + x) ;
for(String arg: args)
{
System.out.print(", " + arg);
}
}
}

Garbage Collection
Garbage collection is a mechanism of destroying objects automatically when no reference
variable exists containing the reference of that object and reclaiming the memory occupied by
the object. It provides optimum utilization of memory. The Java run time periodically initiate the
method void gc( ) of the class Runtime to initiate garbage collection to recycle unused objects.
Check Your Progress / Self Assessment Questions
Ques14.What is the difference between method overloading and method overriding?
Ques15.Which method is used to run a garbage collector?

103

Glossary

Class : a structure or template consisting of variables and methods.

Object: physical implementation of a class.

Abstract classes :partially implemented class containing abstract methods.

Method overloading :Methods having the same name but with different parameters

Method overriding :Methods with same name and parameters.

Garbage collection: Mechanism for destroying unused objects.

Constructor : a special method of a class, having same name as that of class, used to initialize an
object.

Inheritance : extending a new class from an existing class.

Base class : a class that acts like a parent or super class of another class.

Subclass : child class or derived class.

Multilevel inheritance : a type of inheritance whereby a class is derived from another derived
class.

Hierarchical inheritance : a type of inheritance where by multiple classes are derived from same
base or parent class.

Overriding Methods : defining same named method in child or derived class as that of parent
class.

Method Overloading: having multiple functions of the same name in one class.

104

Answers to Check Your Progress / Self Assessment Questions


Ans1.A class is a structure or blueprint of the object, whereas an object is the physical implementation
of a class.
Ans2. New operator
Ans3. Dot(.) operator
Ans 4. A constructor is used to initialize the state of an object.
Ans 5.Reusability of existing code.
Ans 6. class subclass extends superclass
{
}
Ans 7. With the help of actual arguments supplied at the time of method call.
Ans 8. No
Ans 9. Final
Ans 10.Perform tasks to release the resources captured by unused object.
Ans 11.Java.lang.Integer.
Ans 12. No
Ans 13. No
Ans 14.More than one method having same name but with different parameters is called method
overloading. More than one method with the same name and parameters is called method overriding.
Ans 15.voidgc( )

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.

105

2. Java A Beginner's Guide, Herbert Schildt Oracle Press


3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions

What is a class ? How a class is defined in Java ?


What is meaning of class variables ?
What is role of a constructor in a class ? which are various types of constructors ?
What is use of Inheritance in Java ?
Which are various types of inheritance in Java?
What is multilevel inheritance? Explain with an example.
What is hierarchical inheritance? Explain with an example.
What is method overriding? What is its advantage? Explain with an example.
What are final variables and methods in a class?
What are final classes ? Give an example.
What are wrapper classes in Java?
What is meaning of autoboxing and unboxing ?
What are static classes in Java ?
What is meaning of abstract classes ? how do they differ from static classes ?
What is meaning of method overloading? Give an example.
What is garbage collection ?

106

PDCA-201
Array, Vectors and String Handling
Unit-3. Lesson - 7

Chapter Index
Objectives
Introduction

Arrays

One Dimensional Arrays

Creating an Array

Two Dimensional Array

Vectors

Strings

Type Conversion

Command Line Arguments

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

107

Objectives

Understanding the concept of an array

Understanding theVectors concept

Understanding the concept of Strings

Learning Type Conversion

Understanding the concept Command Line Arguments

Introduction
Many a times in a program, we may need to work with large number of variables. Declaring
huge number of individual variables is very inconvenient. A very simple solution to this multiple
declaration problem is to use an array or a vector which is group of homogenous data elements.
A string is collection of characters. Array, Vector and Strings are topic of discussion in this
chapter.

108

7.1 Arrays
An Array is a indexed collection of homogenous elements i.e. same data type. Unlike, an
ordinary variable which store a single value, an array can hold numerous items. The position of
an element in the array is tracked by using non-negative integer values called index numbers.
Array index number always starts with zero. If an array has n elements then these n elements are
referenced using integer indices from 0 to n - 1, inclusive. The size of an array is fixed after its
declaration and cannot be modified later.
In Java, arrays are treated as objects. Arrays can be of primitive data types, in which case all
the elements stored in the array are of that type. Arrays can also be of reference types, in which
case all the elements in the array are references of a class or interface type. Thus, an array can
hold objects of a specific class or interface type. An array has a final variable called length,
which represents the size of an array. The size of an array means the maximum number of items,
an array can hold.
7.3 One-Dimensional Arrays
One dimensional array is a list of elements. Elements in the list have only one dimension, .i.e.
theyexpand in one direction only. A single index number is used to access each element. This
index number is like the serial number of the element in the list. In memory, they are stored in
contiguous memory locations.The storage of an array in memory is shown in Fig. 7.1.

Figure 7.1 Representation of an array in memory

In the above figure, each box represents the amount of memory needed to hold one array
element. Size of the box depends on the data type of the array. For int data type this is 4 bytes.
The array variable, a holds a memory address of memory that holds the actual array elements.
7.4 Creating an Array
Since arrays in Java are treated as objects, accordingly, the new operator is used to create an
array object just like object of user-defined or built-in classes.

109

7.4.1 Array Declaration


To create an array, declare a reference variable of a primitive or reference type. The primitive
data type such as int, float, double etc. specify the type of elements, the array can store. The
reference type is used to store the objects of that type in an array. The array variable can be
declared in two ways. The general syntax of declaring an array variable is:
dataType[ ] arrayReferenceVariable ;
or
dataType arrayReferenceVariable [ ] ;
For example.
int marks[ ] ;
double[ ] marks ;
Here marks is the name of reference variable that refers to an array.
As with variables of other types, the declaration does not actually create an array, it simply tells
the compiler that this variable is an array variable and will hold an array of the specified type. It
is important to understand that the above declaration does not actually construct an array. It only
declares a reference variable that will be later on refer to an array object. So it initially holds the
value null which means that it doesnt refer to any array object yet.

7.4.2 Creation of arrays


An array object is created using the new operator and store the reference of it in the reference
variable. Thus, after declaring reference variables, an array object has to be assigned to it using
the new operator as well as the length of the array is specified in the square brackets. You can
also create an array object by using the new operator with the following syntax:
The syntax is: arrayReferenceVariable = new dataType[size]
Here, dataType specifies the type of data being allocated and size specifies the maximum
number of elements in the array. The minimum value of [size] is 0, i.e. arrays with zero elements
can be constructed in Java. The new operator allocates memory for arrays. The reference variable
name contains the memory address of first element of the array and is used to iterate through the
array.
For example: marks = new double[50] ;

110

Here, an array marks of data type double is created to store marks of 50 students. The two steps
of creating an array can be combined into a single step using the syntax :
dataType arrayReferenceVariable= new dataType[size]
for example : double marks = new double[50] ;
The [ ] brackets tell the compiler that you are creating an array and not an ordinary variable. You
can also place the square brackets.
The use of an array is demonstrated with the help of an example:
class ArrayDemo
{
public static void main(String args[ ])
{
double marks[ ] ;
marks = new double[5] ;
marks[0] = 31.5;
marks[1] = 28.2;
marks[2] = 65.7;
marks[3] = 30.9;
marks[4] = 85.4;
System.out.println("Value of fourth element " + marks[3]);
}
}
Output
Value of fourth element 30.9
7.4.3 Initialization of arrays
Each variable of a primitive type array has a default value. For numeric types, the default values
equal zero (0 for integers, 0.0 for floating point). For boolean arrays the default value of each
element is false. For char array the default is '\u0000' and null for all object types.. Thus, when
an array is created, all its elements are set to an initial value. The array can be created and
initialized simultaneously in one step. For the initialization, a set of values are placed in the curly
braces and separated by comma. The size of the array will become equal to the number of
elements used for the initialization.
The syntax is:
type arrayReferenceVariable [ ] = { value_1, value_2, ,value_n } ;
For example:int week[ ] = { 1,2,3,4,5,6,7 } ;

The size of array week[ ] is 7.


double[ ] marks = {25.5, 15.5, 65.5, 85.5} ;

111

The size of array marks[ ] is 4.

7.4.4 Array Length


As objects, arrays also have a useful attributelength that gives the size of the array. The length
of an array is the maximum number of elements that an array can hold. To get the length of an
array, use the final variable length declared in the Array class with the array object whose
length you want to find out. This property is read-only, it can be read but cannot be modified.
Thelength variable is used as an upper bound of a loop in order to iterate through the array rather
than a constant value. It is useful in cases where the size of an array is known in advance. Also,
if the size of the array changes, you won't have to go through the program changing all the loops;
they will work correctly for any size array. This can be demonstrated with the help of an
example:
class ArrayDemo
{

public static void main(String args[ ])


{

double marks[ ] = { 31.5, 28.2, 65.7, 30.9, 85.4 } ;


double mean = 0.0 ;
double sum = 0.0 ;
for(int i=0 ; i < marks.length ; i++)
sum += marks[i] ;
mean = sum / marks.length ;
System.out.println("Mean value of marks " + mean);

}
}
Output
Mean value of marks 48.34
Check Your Progress / Self Assessment Questions

Ques. 1. Which variableholds the size of an array?


Ques. 2. Is it possible to create a zero length array?
Ques. 3. Can we create an array without new operator ?
Ques . 4. How an array is stored in memory?

112

7.5 Two-Dimensional Arrays


In arrays, an array element can be a reference to an object. Since, the arrays are objects, therefore
the array elements can themselves store the reference of other arrays. The two dimensional
arrays are actually arrays of arrays. Thus in each row the array may be of different sizes and each
row is an object (array) that can be used independently. To declare a two dimensional array, you
need to specify an array variable and append the appropriate number of [ ] pairs after its name.
You allocate a two dimensional array with new operator by specifying the appropriate number of
elements (between square brackets) for each dimension.
Syntax : type arrayReferenceVariable = new type[size1][size2];
For example : int arr2D[ ][ ] = new int[3][5];
The above statement declares a array variable arr2D of data type int[ ][ ] which means an arrayof-array of type int.The new operator dynamically allocates an array with 3 elements having
type int[ ][ ] and is assigned to the variable arr2D. Each element of this array is again an array
of typeint[ ]. It dynamically allocates 3 arrays of integers each of which stores 5 elements of type
integers. The array of 3 elements created in the previous step holds the references of these 3
arrays. The 5 elements in each of these 3 integer arrays are initialized to their default value of
0.The above steps are shown diagrammatically in fig. 7.2. In a two dimensional array, the
number of rows is given by arr2D.length and the number of values in each ithrow is given by
arr2D[i].length.
Arr2D

a[0]

a[1]

0 00

0 00

0 00

Figure 7.2 Representation of a two dimensional array


a[2]

The two dimensional arrays can be demonstrated with the help of an example:
class TwoDimArray
{
Grou
public static void main(String args[
])
p of
{
State
ments

113

int arr2D[][]= { {45, 55, 85, 44 }, {66,22,11}, {74, 19} } ;


for(int i=0; i < arr2D.length; i++)
{
for(int j=0; j < arr2D[i].length ; j++)
System.out.print(arr2D[i][j] + " ");
System.out.println( ); //line break
}
}
}
Output
45 55 85 44
66 22 11
74 19
Check Your Progress / Self Assessment Questions

Ques 5. Write a statement to create two dimensional array of dimension 4 X 5?

7.6 Vectors
A vector is a dynamic and resizable array. The size of an array can dynamically increase or
decrease as needed to accommodate addition or removal of elements after the vector has been
created. Vector is synchronized and thus is thread safe. Vector has many legacy methods that are
not part of the collection framework. Vector is very useful in situations where, the size of an
array is not known in advance.
Vector has the following constructors:

Vector( )

Vector(Int size)

Vector(int size, int increment)

Vector(Collection c)

The first default constructor creates a vector object having the initial size of 10. The second form
of constructors is used to specify the initial size of an array. The third constructor creates a vector
having initial size and increment value. The increment specifies the number of elements
allocated to vector when resized upward. The fourth constructor creates a vector that contains
the elements taken from the collection c. Whenever a vector is created, it starts with the initial
capacity. Once the initial capacity is full and the next time, an attempt is made to insert an object

114

in the vector, the vector automatically allocates space for that object plus extra space for
additional objects depending upon the value of increment.
The vector class of java.util package contains numerous methods that are used to manipulate
vector. Some of the methods are:

final void addElement(Object ob) : insert an object into the vector.

final boolean removeElement(Object ob) : remove an object from the vector and returns
true if removed successfully otherwise false.

final int capacity( ) : returns the capacity of the vector.

final int size( ) : returns the size of the vector in terms of number of elements currently
occupied by the vector.

final Object elementAt(int index) : return the element from the vector at the specified
location.

final Object firstElement( ) : return the first element from the vector.

final Object lastElement( ) : return the last element from the vector.

final void ensureCapacity( ) : sets the minimum capacity of the vector.

final Enumeration elements( ) : return an enumeration of the elements in the vector.

final Iterator iterator( ) : return an iterator of the elements in the vector.

The use of vector is demonstated with the help of an example:


import java.util.*;
class VectorDemo
{
public static void main(String args[ ])
{
Vector vob = new Vector(4, 3);
System.out.println("Initial size: " + vob.size( ));
System.out.println("Initial capacity: " +vob.capacity( ));
vob.addElement(new Integer(2));
vob.addElement(new Integer(4));
vob.addElement(new Integer(6));
vob.addElement(new Double(15.5));
System.out.println("Capacity after addition of four elements: " +
vob.capacity( ));
vob.addElement(new Double(25.45));
System.out.println("Current capacity: " +
vob.capacity( ));
vob.addElement(new Double(16.08));
vob.addElement(new Double(7.57));

115

System.out.println("Current capacity: " +


vob.capacity( ));
Iterator itr = vob.iterator( );
System.out.println("\\nElements in the vector are:");
while(itr.hasNext( ))
System.out.print(itr.next( ) + " ");
}
}
Output
Initial size: 0
Initial capacity: 4
Capacity after addition of four elements: 4
Current capacity: 7
Current capacity: 7
\nElements in the vector are:
2 4 6 15.5 25.45 16.08 7.57
To iterate through the elements of the vector, iterator contains two methods:
boolean hasNext( ) : return true, if the iterator has more element to read otherwise false.
void next( ) : return the next element in the vector.
Check Your Progress / Self Assessment Questions

Ques 5.Which method is used to insert an element in a vector?


Ques 6. Can a vector grow automatically upon reaching its capacity?

7.7 Strings
A string is a sequence of characters enclosed within the double quotes. In Java, strings are
treatedas objects of the built-in class String. Handling of strings in Java is very easy. Strings are
immutable. It means once a string object is created and initialized, it cannot be modified.
However, you can still perform all types of string operations. The reason is every time the string
is modified, a new string object is created which contains the modified string. In Java, immutable
strings can be implemented more efficiently than changeable ones. Strings can be created either
initializing a variable with the string literal enclosed inside double quotes or by using any of the
constructors defined in the String class. For Example:
String name = My name is Rajan

116

Since the string literals are treated as string objects. So, you can call the methods of the String
class with the string literal.
The class String contains several constructors to create string object:

String str1 = new String( ) ; Creates an empty string str1.


byte b[ ] = {65, 66, 67, 68} ;
String str2 = new String(b) ;
Creates a string str2 with string ABCD. Each byte value of array b[ ] is converted to its
equivalentcharacter value (by considering each b[i] as ASCII value)

byte b[ ] = {65, 66, 67, 68, 69} ;


String str3 = new String(b,1,2) ;
Creates a string str3 with string BC. Each byte value is converted to its equivalent character.

char c[ ] = { 'a', 'b', 'c' , 'd' };


String str4 = new String(c) ;
Creates a string str4 with string abcd.

char c[ ] = { 'a', 'b', 'c' , 'd', 'e' };


String str5 = new String(c,2,3) ;
Creates a string str5 with sub-string cde. Please note that index always starts from 0.

String str6 = new String(Java Language) ;


Creates a string str6 with string Java Language.

7.7.1 String Arrays

A string array contains a group of strings. Each string element stored in the array is an object.
String array is created using the new operator and declaring a reference variable of type String.
The syntax is:String ref[ ] = new String[5] ;
Once the string object is created. The next step is to initialize the array using the syntax:

117

ref[ i ] = Java
You can also create a string array using the declaration and initialization in one step:
String ref[ ] = { Java, is, an, Object, Oriented, Language) ;
Once the string array is created, it can be traversed using any loop. In Java 5, a new foreach loop
is introduced that is specifically used to iterate through an array or collection. It is simple and
concise that makes the program more readable. The syntax is:
for (type variable : array)
This can be demonstrated with the help of an example:
class StringArrayDemo
{
public static void main(String args[ ])
{
String[ ] student ={"Suresh","Ramesh","Rajan","Suraj","Chetan"};
for(String str : student)
System.out.print(str+ " ");
}
}
Output
Suresh Ramesh Rajan Suraj Chetan

7.7.2 String Methods


The String class contains several methods to manipulate the string. Some of the methods will be
discussed here:
int length( ) : Returns the length of a string. The length of a string is the number of
character contained in it.
There are two methods which are used to compare the two strings for equality, these are:
boolean equal(Object obj)

boolean equalsIgnoreCase(String anotherString)

The String class overrides the equal( ) method from the Object class and compares this string to
the specified object. The result is true if and only if the argument is not null and is a String
object that represents the same sequence of characters as this object. The equalsIgnoreCase( )
method does the same, but ignores the case of the characters.

int compareTo(String str2)

int compareToIgnoreCase(String str2)

118

In certain situations, it is not sufficient to compare two strings for equality. For example, when
you want to sort different strings, you need to know which string is less than, equal to or greater
than the other. For this purpose, Java provides the compareTo( ) method.

int compareTo(String str2)

int compareToIgnoreCase(String str2)

The first compareTo( ) method compares two strings based on the unicode value of each
character in the strings. The character sequence represented by this String object is compared
lexicographically to the character sequence represented by the argument string. The result is:

a negative integer if this String object is lexicographically less than the argument string.

a positive integer if this String object is lexicographically greater than the argument string.

a zero if the string is equal to the string argument.

Concatenation of two strings means joining the two strings, which represents first strings
characters followed by the second strings characters. The concatenation of two strings can be
performed using + operator and the concat( ) method defined in the String class. Both produce a
new string object as the result. The syntax of concat( ) method is:
String concat(str) : It returns a new string object by joining the invoking string and the string str
passed as an argument.

This can be explained with the help of an example:


class StringConcatDemo
{
public static void main(String args[ ])
{
String str1 = "Java ";
String str2 = "Runtime ";
String str3 = "Polymorphism";
String result = str1 + str2 + str3 ;
System.out.println(result) ;
String str = str1.concat(str2).concat(str3);
System.out.println(str) ;
}
}
Output
Java RuntimePolymorphism

119

Java RuntimePolymorphism
The String class provides methods used to convert values of primitive data types into strings. It
contains a static method valueOf( ) in overloading forms that operates on different data types to
create their equivalent strings. For example:
double d = 39.85 ;
String str = String.valueOf(d) ;

The String class offersseveral methods that are used to modify strings. Since string objects are
immutable, whenever you modify a string, a new string object is created containing a modified
string.

String replace(char old, char new) : Replace all occurrences of old character with new
character.
String replaceAll(String old, String new) : Replace all occurrences of the old string with
new string.
String replaceFirst(String old, String new): Replace only first occurrence of old string
with new string.
String substring(int start) : Returns a new substring object that begins with the character
at specified index and extends up to the end of the string.
String substring(int start, int end) : Returns a new substring object that begins with the
character at specfied index and extends to the character at index end-1.
String trim( ) : Returns a new string with the leading and trailing whitespace omitted.

The above methods can be demonstrated with the help of an example:

public class StringReplaceDemo


{
public static void main(String[ ] args)
{
String newStr = "Sunil";
String str = " Her name is Sheetal and Sheetal is a good girl.
String str2 = str.replaceFirst("Her", "His") ;
String str3 = str2.replaceFirst("girl", "boy") ;
String str4 = str3.replaceAll("Sheetal", newStr);
String result = str4.trim( ) ;
String subStr = result.substring(22) ;
System.out.println(result);
System.out.println(subStr);

120

";

}
}
Output
His name is Sunil and Sunil is a good boy.
Sunil is a good boy.

7.7.3 StringBuffer Class

Unlike the String class, the StringBuffer class are mutable strings.Thus, both the capacity
and contents of a StringBuffer Class can be modified dynamically. String buffers are used
where modification of strings like appending, inserting, deleting and modifying is
involved.Every string buffer has a capacity. The capacity of a string buffer is the
maximum number of characters that a string buffer can accommodate, before its size is
automatically increased. As the length of the character sequence contained in the string
buffer exceed the capacity, the string buffer will automatically grow to make room for
further additions.The final class StringBuffer provides three constructors used to create
StringBuffer objects:

public StringBuffer( ) : Constructs anempty string buffer and an initial capacity of 16


characters.

public StringBuffer(int capacity): Constructs anempty string buffer and the specified
initial capacity.

public StringBuffer(String str): Constructs a string buffer initialized with the contents of
the specified string. The initial capacity of the string buffer is 16 plus the length of the
string argument.

The following are some of the basic StringBuffer methods;

public int length( ): Returns the length of the sequence of characters of the string buffer.

public int capacity( ): Returns the current capacity.

public class StringBufferDemo


{
public static void main(String[ ] args)
{
StringBuffer sbuff = new StringBuffer("Indira Gandhi Open University New Delhi");

121

System.out.println("String Buffer= " +sbuff);


System.out.println("length= " +sbuff.length( ));
System.out.println("capacity= " +sbuff.capacity( ));
}
}
Output
String Buffer= Indira Gandhi Open University New Delhi
length= 39
capacity= 55
Check Your Progress / Self Assessment Questions

Ques5. Which method is used to retrieve the size of a string?


Ques6. Can a string literal be treated as an object?

7.8 Type Conversion


Java runtimechecks for compatibility whenever you assign a value of one type of variable to
another type.

If the two types are compatible, then Java will perform the conversion

automatically. For the primitive data types, a value of a narrower data type can be converted
automatically to a value of a broader data type without loss of information. This is called
widening conversion. Widening conversions to the next broader type for primitive data types are
summarized in Figure 3.6.
byte

shor
t

int

long

float

double

char

Figure 3.6 Widening Conversions


So for the automatic type conversions, following conditions have to be met :

The two types are compatible with each other.

The destination type is larger than the source type.

For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, the numeric types are not compatible with char or
boolean. Also, char and boolean are not compatible with each other. Conversion from broader

122

data type to a narrower data type is called a narrowing primitive conversion, which results in loss
of information. This kind of conversion will not be performed automatically and need a casting.
A castis simply an explicit type conversion. It has this general form: (type) operand
7.9 Command Line Arguments
Command Line arguments are used to pass information to the program at runtime. The java
program contains a method main( ) that is used to receive the command line arguments from the
outside. A command-lineargument is the input values that follow the program's name on the
command lineat runtime. A string array is used as a parameter to the main( ) method to retrieve
the command-line arguments inside a Java program
The following example displays all of the command-line arguments:
class CommandLineDemo
{ public static void main(String args[ ])
{ for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
At command prompt, execute the program along with the command line arguments such as:
Java CommandLineDemo Passing arguments at command line
Output
args[0]: Passing
args[1]: arguments
args[2]: at
args[3]: command
args[4]: line
Check Your Progress / Self Assessment Questions

Ques9. Which conversion is performed automatically?


Ques10. Which parameter of the main( ) method is used to retrieve command line
arguments?

Summary
An Array is a indexed collection of homogenous elements of the same type. Unlike, an ordinary
variable which store a single value, an array can hold numerous items. A vector is a dynamic and

123

resizable array. The size of an array can dynamically increase or decrease as needed to
accommodate addition or removal of elements after the vector has been created. Vector is
synchronized and thus is thread safe. A string is a sequence of characters enclosed within the
double quotes. In Java, strings are treatedas objects of the built-in class String. Handling of
strings in Java is very easy. Strings are immutable in Java.
Glossary

Array : An Array is a indexed collection of homogenous elements

Class : a structure or template consisting of variables and methods.

Object: physical implementation of a class.

Abstract classes : partially implemented class containing abstract methods.

Method overloading :Methods having the same name but with different parameters

Method overriding : Methods with same name and parameters.

Garbage collection: Mechanism for destroying unused objects.

Check Your Progress / Self Assessment Questions


Ans1. length
Ans2. Yes
Ans3. Yes
Ans 4. The elements of an array are stored in contiguous memory locations.
Ans 5.length( )
Ans 6. Yes
Ans7. String.concat( )
Ans 8. String is immutable and StringBuffer is mutable.
Ans 9.Widening convrsion
Ans 10.String args[ ]

124

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. What is an array ? What are its advantages ?
2. Write any five applications of arrays?
3. What is the difference between length variable and length( ) method?
4. What is a vector? How it differs from an array?
5. What is string in Java ? Why java strings are immutable?
6. Explain any five methods of string class.

125

PDCA-201
Programming in Java
Unit-3.

Lesson - 8.

Interfaces

Chapter Index
Objectives
Introduction

Defining Interfaces

Extending Interfaces

Implementing Interfaces

Accessing Interface Variables

Implementing multiple inheritance through interfaces

Check Your Progress / Self Assessment Questions

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

Differentiate between class and interface.

Explain the features of interfaces

How an interface is implemented

How multiple inheritance is achieved through interfaces

Accessing Interface Variables

126

Introduction
In this chapter we will study about another very important part of java i.e. interfaces. Interfaces
are different from classes. A class can be extended only from a single base class since java
doesnt support multiple-inheritance. But it does not decrease the power of Java. Java provides
an alternative way of implementing multiple inheritance and that is using interfaces. There are
many inbuilt interfaces in java, and java also allows users to create user defined interfaces also.

8.1 Defining Interfaces


A class contains data members and definition of member functions called methods whereas an
interface can have only method declarations, no definition or body of method is given inside an
interface, rather it is required from the class that extends an interface (actually the term
implements is used i.e. a class can extend another class, but it can implement an interface) to
provide the method definitions. All the methods declared inside interface body are said to be
abstract.
To define an interface in java, interface keyword is used. Definition or body of an interface
may contain constants and abstract method declarations only. All constants declared inside an
interface are public, static and final by default, and all methods declared inside an interface are
public and abstract by default.
Syntax to declare an interface is :
[public] interface InterFaceName

Interface header

{
// constants declarations
// abstract method declarations

Interface body

}
Where

public keyword is optional, if an interface is not defined as public then by default its
access level becomes class level and it can be accessed only within same class.If it is
defined as public then it can be accessed by any other class.

interface keyword is compulsory, and it indicates the compiler that an interface is


being defined.

127

InterFaceName is name of the interface, it is any valid java identifier and can be
given by user.

Within its body, many constants and methods can be declared in any order.

Example : Defining an Interface


Interface student

Interface header

Interface body starts


int SemesterFee=5000 ;

constant declarations

int findTotalMarks(int RollNo);

method declarations

int findLectureShortage(int RollNo);


}

Interface body end\

In this example, an interface student is being defined. A constant named SemesterFee is declared
and then two methods namely, findTotalMarks and findLectureShortage are also declared inside
body of this interface.

Comparison of a class and interface


An interface and a class has many similarities, some of these are :

Like a class body, an interface body may contain any number of constant declarations
and methods.

Just like a class, an interface body is also given in a file with a .java extension, with the
name of the interface matching the name of the file, and when compiled, it also creates a
.class file i.e. byte code each interface appears in a separate .class file.

Like classes, Interfaces may also appear in packages, and their corresponding bytecode
file must be placed in a directory structure that matches the package name.

However, there are many differencesbetween an interface and a class. Some of these are :

Though an object of a class may be created, an object of interface cannot be created, but
it is allowed to create a reference variable of an interface.

An interface body cannot have any constructor or destructor, since its object cannot be
created.

128

By default, all of the methods given in an interface body are abstract and public, interface
methods cannot be declared private.

Only static constants are allowed inside an interface body, it cannot contain instance
fields.

A class can be extended, whereas an interface can be implemented.

A class can extend only one class whereas, an interface can extend multiple interfaces.

Check Your Progress / Self Assessment Questions


Ques 1. Can a method be declared as private inside an interface?
Ques 2. How an interface differs from a class?
8.2 Extending Interfaces
One of basic characteristics of any object oriented programming language is that it supports
inheritance. Just like a class can be extended from an existing class, similarly an interface can
also extend an existing interface. Since all fields (constants) and methods declared in an
interface are by default public, when a new interface say, ChidInterface, is created using
existing interface say, ParentInterface, then ChidInterface gets all fields and methods
declared in its parent ParentInterface. Now if a class implements ChidInterface then it can
use all the fields and it will have to provide implementation details of all the methods.
Sytnax :
[public]

interface

ChidInterface

extends

ParentInterface1,

ParentInterface2,

ParentInterfaceN
{
//body of ChidInterface
}
Where

Public is keyword of java and is optional here.

Interface is keyword of java and indicates that an interface is being created.

ChidInterface is the user-defined name given to new interface being created,


ChidInterface must be a valid java identifier.

129

Extends is keyword of java and indicates that new interface is being inherited from
existing interface(s)

There is a major difference between class inheritance and interface inheritance in java. Since
java does not support multiple inheritance, a class can extend at maximum one class but an
interface can extend zero, one or multiple interfaces. This has been explained in section
8.5.1.
Example :
interface MyInterface1
{
final int num=10;
void fun( ) ;
}
interface MyInterface2 extends MyInterface1
{
final int length=10;
void gun( ) ;
}
class myClass implements MyInterface2
{
public void fun( )
{
System.out.println("This is fun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
}
public void gun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
}

130

}
In above example, first an interface MyInterface1 is created, then it is extended by another
interface MyInteface2. Fields and methods declared in MyInterface1 become available to
MyInterface2. In addition MyInterface2 can declare its own new methods and fields. Finally
a class myClass is created which implements interface MyInterface2. All the fields and
methods declared in MyInterface1 and MyInterface2 become available to class for
implementation via MyInterface2 only.
8.3 Implementing Interfaces
Since an interface merely declares methods, and does not provide method body or definition,
someone else has to provide method definition on the behalf of interface, otherwise methods
declared inside interface will not be useable. The task to define body of methods declared
inside interface is performed by the class which uses that interface i.e. the class which
implements that interface. It is said that a class implements an interface since class
provides the implementation details of the methods declared inside interface. It is the class
that decides how those methods will be implemented i.e. what exactly will be their working,
interface only imposes method signatures.
If one interface is implemented by multiple classes, each class may have its own
implementation of any methods of the interface. Further a concrete class that implements an
interface has to provide implementation part of all of the methods of the interface. If a class
does not provide the implementation part of all the methods then the class must itself be
declared as abstract.
Note that when a new class (child) is created from an existing class (parent), it is said that
(child) class extends (parent) class, but when a new class (child) extends an interface it is
termed that class implements interface.

131

Figure 8.1 Types of Single inheritance in java.


Syntax :
[accessSpecifier] [modifier] class className implements interfaceName
{
//body of class must now contain method body.
}
Where

accessSpecifier is optional and can be public or private or protected.

modifier is also optional and can be abstract or static.

class is keywords and indicates that a new class is being created.

className is any valid java identifier and user-defined name to be given to new class
being created.

implements is keyword and indicates that a new class is being created from an
existing interface, and class will provide the implementation details of the methods
declared inside interface.

interfaceName is name of the existing interface.

Example : Class implementing an interface


interface Employee
{
void calculateTotalSalary( ) ;
void calculateBonus( );
}
class regularEmp implements Employee
{
int empid, deptid;
long basicSalary;
int experienceInYears, SpecialIncrement ;
long totalsalary, long totalbonus ;

public void calculateTotalSalary()

132

totalsalary =(basicSalary + experienceInYears*2000 + SpecialIncrement );


return ;

}
public void calculateBonus()
{

totalbonus =(experienceInYears*1000) ;
return ;

}
}
public class interfaceExample
{
public static void main(String a[ ])
{
regularEmp e=new regularEmp ();
e.basicSalary=5000 ;
e.experienceInYears =5;
e.calculateTotalSalary() ;
System.out.println("Total Salary is " + e.totalsalary );
e.calculateBonus() ;
System.out.println("Total Bonus is " + e.totalbonus );
}
}
Output :
Total Salary is 15000
Total Bonus is 5000
In the above example, an interface Employee is created that declares two methods,
calculateTotalSalary( ) and calculateBonus( ), then a class regularEmp

is defined which

implements the interface Employee. Class regularEmp provides implementation details of the
methods. When above program is compiled it will create three class files, Employee.class,
regularEmp.class, interfaceExample.class.

133

One interface can be implemented by more than one class also. Each class can define
implementation details of the methods in its own way, but each class will have exactly same
signatures of those methods. This is actually main reasons behind having interfaces in Java.
This is explained with following example.

Example : One interface being implemented by two different classes


interface Employee
{
void calculateTotalSalary( ) ;
void calculateBonus( );
}

class regularEmp implements Employee


{
int empid ;
int deptid ;
long basicSalary;
int experienceInYears ;
long totalsalary, totalbonus ;
int SpecialIncrement ;
public void calculateTotalSalary()
{
totalsalary =(basicSalary + experienceInYears*2000 + SpecialIncrement );
return ;
}
public void calculateBonus()
{
totalbonus =(experienceInYears*1000) ;
return ;
}
}

134

public class interfaceExample


{

public static void main(String a[ ])


{
regularEmp e=new regularEmp ();
e.basicSalary=5000 ;
e.experienceInYears =5;
e.calculateTotalSalary() ;
System.out.println("Total Salary of Regular Employee is " + e.totalsalary );
e.calculateBonus() ;
System.out.println("Total Bonus of Regular Employee is " + e.totalbonus );

partTimeEmp t=new partTimeEmp( );


t.basicSalary=5000 ;
t.calculateTotalSalary() ;
System.out.println("Total Salary of Part Time Employee is " + t.totalsalary );
t.calculateBonus() ;
System.out.println("Total Bonus of Part Time Employee is " + t.totalbonus );
}
}
class partTimeEmp implements Employee
{

int empid, deptID ;


long basicSalary, totalsalary, totalbonus ;
public void calculateTotalSalary()
{

totalsalary=basicSalary + 4000 ;

public void calculateBonus()


{
totalbonus =2000 ;
}
}

135

Output :
Total Salary of Regular Employee is 15000
Total Bonus of Regular Employee is 5000
Total Salary of Part Time Employee is 9000
Total Bonus of Part Time Employee is

In this example we have two different classes regularEmp and partTimeEmp implementing
same common interface Employee. Both have different data members. Both classes define the
implementation of the methods declared in interface Employee in their own way.

Class

regularEmp calculates total salary of a regular employee on the basis of his/her experience in
number of years, but class part time employee calculates total salary of a part time employee
using a fix formula. A class can implement more than one interface also, this has been explained
in section 8.5.2

Check Your Progress / Self Assessment Questions


Ques 3. Can a class implement an interface without providing implementation of methods
declared in the class?
Ques 4. Can a class implement more than one interface?
Ques 5. Can a class extend from more than one class?
Ques 6. Can a class do both the things i.e. implement an interface and extend a class?

8.4 Accessing Interface Variables (and method)


Interface members (constants and methods declared inside a method) become class members
when a class implements an interface and they can be accessed just like class members using
dot operator.
8.5 Implementing multiple inheritance through interfaces
An interface can be used to implement multiple inheritance in java. There are different ways to
look at this. These are explained below.

136

8.5.1. An interface can extend multiple existing interfaces


Though it is not allowed for a class to extend from multiple base classes (this type of multiple
inheritance is not allowed in Java), but it is allowed for an interface to extend from multiple base
interfaces. Let us revisit syntax of creating an interface given in section 8.2. it is again given
below.
Sytnax :
[public]

interface

ChidInterface

extends

ParentInterface1,

ParentInterface2,

ParentInterfaceN
{
//body of ChidInterface
}
This syntax clearly shows that a new interface can be extended from multiple existing interfaces.
While doing so, all the members declared in existing interfaces ParentInterfaceName1,
ParentInterface2, , ParentInterfaceN are inherited by new interface (ChildInterface) being
created. When a class implements ChildInterface, all the methods will have to be implemented
by it.
Example : An interface extending multiple interfaces.
interface MyInterface1

Parent interface 1

{
final int num=10;
void fun( ) ;
}

interface MyInterface2

Parent interface 2

{
final int sum=0;
void gun( ) ;
}
i
interface MyInterface3 extends MyInterface1 child interface extending two interfaces

137

{
final int length=10;
void sun( ) ;
}
class myClass implements MyInterface2 class implements child interface.
{
public void fun( )
{
System.out.println("This is fun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
System.out.println("sum=" + sum) ;
}
public void gun( )
{

System.out.println("This is gun method") ;


System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
System.out.println("sum=" + sum) ;

}
public void sun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
System.out.println("sum=" + sum) ;
}
}
In above example, first an interface MyInterface1 is created, then it is extended by another
interface MyInteface2. Fields and methods declared in MyInterface1 become available to
MyInterface2. In addition MyInterface2 can declare its own new methods and fields. Finally
a class myClass is created which implements interface MyInterface2. All the fields and

138

methods declared in MyInterface1 and MyInterface2 become available to class for


implementation via MyInterface2 only.

8.5.2. A class can implement multiple interfaces


Though it is not allowed for a class to extend from multiple base classes (this type of multiple
inheritance is not allowed in Java), but it is allowed for a class to implement multiple base
interfaces. Let us revisit syntax of creating an interface given in section 8.2. it is again given
below.
Example : One class implementing more than one interface
interface MyInterface1
{
final int num=10;
void fun( ) ;
}
interface MyInterface2
{
final int length=10;
void gun( ) ;
}
class myClass implements MyInterface1, MyInterface2 //class implements two interfaces.
{
public void fun( )
{

System.out.println("This is fun method") ;


System.out.println("num=" + num) ;
System.out.println("length =" + length) ;

}
public void gun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;

139

}
}

8.5.4 Implementing run time polymorphism using interfaces.


Though it is not permitted in java to create objects of interface, it is permitted to create reference
variables of an interface. Interface being parent of a class, once interface reference variable is
created, later it can point to actual object of concrete class which implements that interface. This
helps in java to implement run time polymorphism.
When a variable of interface type is created, it can refer to objects of any of classes
implementing that interface. When an object is called on such a variable, method from the class
to which the variable refers is called. Method is called from a class depending upon the contents
of reference variable, not depending upon type of reference variable.
Example :
interface Employee
{
void calculateTotalSalary( ) ;
}
class regularEmp implements Employee
{
long empID, basicSalary, experienceInYears, totalSalary ;
public void calculateTotalSalary()
{
totalSalary =(basicSalary + experienceInYears*2000 );
System.out.print("Total Salary of Regular Employee With EmpId " + empID)
System.out.println (" is " + totalSalary );
return ;
}
regularEmp(long eid, long sal, long expr) //parameterized constructor
{
empID=eid;
basicSalary=sal;

140

experienceInYears=expr ;
}
}
class partTimeEmp implements Employee
{
long empID, basicSalary, totalSalary ;
public void calculateTotalSalary()
{
totalSalary =(basicSalary + 3000 );
System.out.print("Total Salary of Part Time Employee With EmpId " + empID)
System.out.println (" is " + totalSalary );
}
partTimeEmp (long eid, long bsal) //parameterized constructor
{
empID=eid;
basicSalary=bsal;
}
}
public class interfaceexample3
{
public static void main(String a[ ])
{
Employee e; // reference variable of interface type is created.

//create and initialize object using constructor


regularEmp r=new regularEmp (101, 5000, 5);
e=r ; //Reference variable of interface now points to object of type regularEmp
e.calculateTotalSalary( ) ; //will call method from regularEmp class
// create and initialize object using constructor
partTimeEmp p=new partTimeEmp(102, 2000);
e=p ; //Reference variable of interface now points to object of type partTimeEmp

141

e.calculateTotalSalary( ) ; // will call method from partTimeEmp class


}
}
Output :
Total Salary of Regular Employee With EmpId 101 is 15000
Total Salary of Part Time Employee With EmpId 102 is 5000

When a method is called on an reference variable (e, in above example) that refers to object r of
RegularEmp class, it calls or binds method in this class, and when reference variable e is
changed to point to object p of partTimeEmp and method is called on e, compiler binds method
available in partTimeEmp class. Method is called from a class depending upon the contents of
reference variable, not depending upon type of reference variable. This is called run time
polymorphism in java.

Check Your Progress / Self Assessment Questions


Ques 7. Which are two types of Polymorphism?

Summary
An interface is named block of code which may contain named constants and method
declarations (without their definition or implantation details). To define an interface in java,
interface keyword is used. Definition or body of an interface may contain constants and
abstract method declarations only. All constants declared inside an interface are public, static and
final by default, and all methods declared inside an interface are public and abstract by default.
Though an object of a class may be created, an object of interface cannot be created, but it is
allowed to create a reference variable of an interface
One interface can be implemented by more than one class also.
One class can implement more than one interface also.

142

Since java does not support multiple inheritance, a class can extend at maximum one class but an
interface can extend zero, one or multiple interfaces.
Polymorphism is the capability of a data member or field or variable of a particular class to be
used to reference objects of any of its descendent types in inheritance.
A class can extend another class, but a class can implement an interface.

Glossary

interface : an interface in java can be created which declares methods and variables.

extends : keyword of java, used when a derived class is created from base class or when
derived interface is created from base interfaces.

implements : keyword of java, used when a class is created base on an interface, class has
to provide implementation details of methods declared in the base interface.

static : keyword of java, used when a method of data member or field can be used without
an object of class.

abstract : keyword of java, used with a class, imposed on class when it cannot be
instantiated.

modifier : access modifiers like abstract and final.

inheritance : a feature of object oriented programming. Java supports inheritance via


classes and via interfaces.

multiple inheritance : a type of inheritance, though not allowed in java, but an interface
can be extended from multiple interfaces.

Polymorphism : a feature of object oriented programming, polymorphism is the


capability of a data member or field or variable of a particular class to be used to
reference objects of any of its descendent types in inheritance, it also means a class can
have multiple methods with same name but different method signatures.

run time polymorphism : a type of polymorphism. Possible using reference variables.

dynamic polymorphism : another term used for run time polymorphism.

143

Answers to Check Your Progress / Self Assessment Questions


Ans.1. No, each method must be public inside an interface. If tried, java compiler gives error :
modifier private not allowed here
Ans. 2. There are many differences between a class and an interface, some of these are :
All of the methods given in an interface body are abstract and public, this is not so in a class.
Only static constants are allowed inside an interface body, it cannot contain instance fields. A
class can have both.
A class can be extended, whereas an interface can be implemented.
A class can extend only one class whereas, an interface can extend multiple interfaces.
Ans. 3. Yes, but in that case class will become static and cannot be instantiated.
Ans 4. Yes.
Ans. 5. No, since multiple inheritance is not allowed in Java.
Ans 6. Yes.
Ans. 7. Static and dynamic (also known as compile time and run time).

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall
Model Questions
1. What is use of interfaces in Java ? how does an interface differ from a class?
2. Can an interface extend from multiple interfaces? Explain with an example.
3. Can a class implement multiple interfaces? Explain with an example.
4. What is polymorphism ? Which are its types?
5. What is run time polymorphism? How is it implemented in Java?

144

PDCA-201
Programming in Java
Unit-3.

Lesson - 9.

Packages

Chapter Index
Objectives
Introduction

System Packages

Using System Packages

Naming Conventions

Creating Packages

Accessing a Package

Using a Package

Adding a Class to a Package

Hiding Classes

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

Understanding the meaning and significance of packages.

Knowing system packages

Being able to create user defined packages.

Using inbuilt system and user defined packages.

Adding a class to an existing package.

145

Hiding classes in a package.

146

Introduction
Java provides a way to physically as well as logically create a group of related classes and
interfaces by using package. Packages enable a user to organize classes logically. A package is
just like a container and can have classes, interfaces and subpackages inside it. There are many
inbuilt system packages in Java and at the same time java enables its users to create user-defined
packages.

9.1 Introduction
Sometimes, it may be required to logically group some related classes. For example if multiple
team members are working on a common project and it may happen that every one may create
some classes and interfaces etc. Now, to avoid name conflicts, it may be required to place classes
and interfaces created by one team member at a common place but different from others. Java
solves this problem by providing packages. A Package is like a container and is a logical group
of related classes, interfaces and enumerations etc. providing both name-space management and
access protection.
There are broadly two types of package in java, these are system packages or built-in package
and user-defined packages. Java itself uses packages to group related classes. There are many
built-in java packages such as java, lang, util, awt, javax, swing, io, net and sql etc. To create a
package, package statement is used in Java.
Following figure (extracted from http://java67.blogspot.in/2012/08/What-is-package-in-javahow-to-use.html) shows some of predefined or inbuilt system packages available in java

147

Figure 91. Inbuilt or System packages in java


Advantage of Packages in Java
1.Package is used for categorization and grouping of classes and interfaces for their easy
management.
2.It also provides access protection, It can be restricted that which classes outside a package can
use package members.
3. They also help in avoiding naming conflicts.
4. Packages help us to find and locate our classes easily.

9.2 Using system packages


As shown in Figure1.9 there are many system packages in java. Each in-built package has related
classes in it. Some of these are :

java.lang package provides basic language functionality and fundamental types like
Thread, Math etc.

148

java.uti : collection data structure classes

java.io: file input/output operations

java.net : networking operations, working with sockets and DNS lookups etc.

java.security: many classes and methods for encryption and decryption related tasks.

java.awt:basic hierarchy of packages for many GUI components like Button etc.

java.applet:classes for creating an applet for example Applet class.

Any of these packages can be used in a program. Only java.lang is such a special package which
is included in our program by default. To use any other system package in a program, java
provides import statement. It is generally used at the top of the program. It has to be used once
for each package to be included. There are two ways in which import statement can be used.
First method is used when it is required to import all the classes built in a package and second
method is used when it is required to import only a specific class from a package.
Syntax of import statement is : Import PackageName ;
For example, to include or import every class of awt package, it can be written :
import java.awt.* ;
to include only Math class of java.lang package :
import java.lang.Math ;
Further, an import statement imports only classes and interface at outermost level from a
package, to import classes and packages from sub-packages available in a package, another
import statement is used for example :
import java.awt.* ; includes classes etc. only from outermost awt package.
import java.awt.event.* ; imports classes etc. from event sub-package of awt package.
Check Your Progress / Self Assessment Questions
Ques 1. Which package is included in every java program by default?
Ques 2. Which statement does java provide to include a package in java program?

149

Ques 3. Which statement is used in java to include a system package?


Ques 4. Which are various ways to use import statement?

9.3 Naming conventions


Java uses its own method of naming classes, interfaces, methods, packages, data members in a
class etc. These are collectively known as java naming conventions. For example, java has a
convention to name a package in lower case. So all java system packages like, lang, io, security
etc are accessible in lower case only.

A method is written in a different manner like

calculateTotalSalary( ). This is known as Camel Case. Since java is case sensitive


programming language, the upper and lower case identifiers are treated differently.
Naming conventions improve readability of programs and make them easily understandable.
They can also give information about the function of the identifier-for example, whether it's a
constant, package, or a class etc. , this can be helpful in understanding the code.
Some of the naming conventions used in java are :

Package: Package name should be mentioned in all lowercase letters e.g. java, lang, sql,
util etc.

Class: it should start with an uppercase letter and should be a noun, like, Employee,
Student, Thread, Applet, RegularEmployee etc.

Interface: Interface name should start with uppercase letter and should be an adjective
e.g. Runnable, WorkingEmployees, etc.

Method: Method name should start with lowercase letter and it should be a verb e.g.
calculateTotalSalary( ), main( ), println() etc.

Data member (variables) : Data member name should start with lowercase letter e.g.
totalSalary, circleArea etc.

Data member (constants) : These should be in uppercase letter. e.g. PIE.

9.4 Creating Packages

150

Apart from having inbuilt system packages in Java, user defined packages can also be created.
For this, java provides package statement. It can be used in a program when it is to be
specified that classes and interfaces created in the program will belong to which package. If
used, it must be the first executable statement of the program.
Syntax of Package statement is :
package UserDefinedPackageName ;
Where

package is keyword and statement of java, indicates that all classes, interfaces etc. in the
current program must belong to this package.

UserDefinedPackageName is any legal java identifier, and is given by user, it specifies


name of package.

It is important to note that all .class files must be placed in the folder that has same name as that
of the package.
Example :Creating first package. (Suppose program given below is saved in a file
MyFirstPackage.java)
package student ;
class MedicalStudent
{

MedicalStudent( ) // default constructor


{
}
// other class members.

}
class ArtsStudent
{

ArtsStudent( ) //// default constructor


{
}
// other class members.

151

}
Save above program in a file MyFirstPackage.java. Now there are two ways to compile above
program. First, compile it ordinarily using the command : javac MyFirstPackage.java. Compiler
will create two class files, MedicalStudent.class and ArtsStudent.class. To make these classes
usable, they must be stored in a folder named student. So create a student package and move
these two .class files in that package.
Second method is using -d option with javac command. This option tells the compiler to place
the .class files in the corresponding folder having same name as that of the package.
Corresponding folder is also created by the compiler itself.
Following figure shows that .class files are stored in the student folder.

Figure 9.2 : Organizing class files.

Check Your Progress / Self Assessment Questions


Ques 5. True / False : By convention, a class name starts with a lower case?
Ques 6. Which option is used with javac command to place class files in a particular folder?

9.5 Accessing a Package

152

Package statement can also be used to access a package. For example to add a new class to a
package that uses the classes already defined in the package, it can be referred in package
statement. All members of a package can access each other, as each member has a default
package level access.
Example : To access a package
In order to access a package i.e. to access classes that belong to student package created above,
we can write following program.
package student ;
class CollegeStudent
{

MedicalStudent ms= new MedicalStudent( ) ;


ArtsStudent as = new ArtsStudent( );

}
It will add another class CollegeStudent to the package, which accesses already defined classes
in the package.
After this contents of student folder are :

Figure 9.3
9.6 Using a Package
To use or access a user defined package, import statement is used in the same way as it is used
for system packages. But if any class is to be used outside the same package to which it belongs
then class must be declared as public. Only public classes and interfaces etc. are accessible

153

outside package. Any class or interface which has a default package level access can only be
accessed inside the package only, and cannot be accessed outside package.
Example : Using a Package
To use a class from a package, it must be declared as public in the package. So let us first create
a public class in the student package using following program.
package student;
public class NonMedicalStudent
{

public NonMedicalStudent( )
{
}
public showMessage( )
{
System.out.println(showMessage ( ) method of NonMedicalStudent class );
}

}
After this contents of folder student are as shown below :

Figure 9.4 : Contents of student folder


To use a public class inside a user defined package, import statement is used in the same way as
it is used to access a class from system packages. To import a specific class from a package,
import statement is used with package name as qualifier along with the class name.

154

Example : To access a public class from a package


import student.NonMedicalStudent ;

// NonMedicalStudent is public class inside student

package.
public class CollegeStudent2
{

//try to create an object of NonMedicalStudent class, using its default constructor.


NonMedicalStudent nms = new NonMedicalStudent( ) ;

}
Once an object of the class is created, it can easily use methods of the class defined in the
package.

9.7 Adding a Class to a Package


Each program (source file) when compiled creates a .class file. Each class file belongs to a
package. If no package is specified, default package is used which has no name, and .class file is
saved into current folder. To add a class to a package, package statement is used to use the
package. A new class is created in source file, when program is compiled using d option with
javac command, compiled code i.e. .class file is saved in the package folder and thus a new class
is added to the package.

9.8 Hiding Classes


Only classes that are declared as public in a package are visible and accessible outside package.
To hide a class from world outside package, it is created with default access specifier. Then it
can be used only by the classes which are its siblings, i.e. which belong to same package. Classes
inside a package can be package protected, so that only other members in the same package can
see it.
Within your classes you may also want to protect your methods and members by having their
access specifier as private, protected or default as required.

155

Access specifier private will allow access only from the containing class.

Access specifier 'default' (i.e. no modifier) allows access from within the containing class
and containing package.

Protected access specifier will allow access from within the same class, package and any
of its subclasses.

Check Your Progress / Self Assessment Questions


Ques 7. Which access specifier can be used to hide a class within a package.

156

Summary
Java provides a way to physically as well as logically create a group of related classes and
interfaces by using package.
A Package is like a container and is a logical group of related classes, interfaces and
enumerations etc. providing both name-space management and access protection.
java.lang package provides basic language functionality and fundamental types like Thread,
Math etc.
Some other java in-built packages are :

java.uti : collection data structure classes

java.io: file input/output operations

java.net : networking operations, working with sockets and DNS lookups etc.

Java uses its own method of naming classes, interfaces, methods, packages, data members in a
class etc. These are collectively known as java naming conventions.
Apart from having inbuilt system packages in Java, user defined packages can also be created.
For this, java provides package statement.
To use or access a user defined package, import statement is used in the same way as it is used
for system packages.
Each program (source file) when compiled creates a .class file. Each class file belongs to a
package. If no package is specified, default package is used which has no name, and .class file is
saved into current folder.

157

Glossary

Package : a way of logically grouping classes together.

package: a java keyword, and a statement used to create packages in java.

java.lang : only system package that gets imported by default in any package.

java.uti : an in-built or system package, it provides collection data structure classes

java.io: in-built or system package, it provides file input/output operations

import : import statement is used to include packages in a program.

Naming conventions: conventions used in java to name a class, interface, method etc.

interface : an interface in java can be created which declares methods and variables.

Answers to Check Your Progress / Self Assessment Questions


Check Your Progress / Self Assessment Questions
Ans1. Java.lang package is the only package that is included in every program by default.
Ans2. import statement.
Ans3. import statement.
Ans. 4. There are many ways in which import statement can be used, some of these are :
To import all classes of a package : import packagename.* ;
To import only a specific class of a package : import packagename.classname ;
To import all classes of a subpackage of a package : import packagename.subpackagename.* ;
Ans 5. False.
Ans 6. Option d is used with javac command to place class files in a particular folder
Ans 7. Private or default access specifiers.

158

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. What is use of packages in java?
2. How can system package used in java?
3. How can a user-defined package be created in java?
4. How can we hide some of the classes in a package?
5. What are various advantages of packages in java?

159

PDCA-201
Programming in Java
Unit-4.

Lesson-10.

Exception Handling

Chapter Index
Objectives
Introduction

Managing Errors And Exceptions An Introduction

Types of Errors (Compile-time error, Run-time error)

Exceptions, Syntax of Exception Handling Code

Multiple Catch Statements

Using finally Statement

Throwing Our Own Exceptions

Using Exceptions for Debugging

Handling System defined Exceptions

Creating and handling user defined exception

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

160

Objectives

To know about compile time and run time errors

To have the knowledge of Exception and Exception class in Java

Exploring exception handling feature of Java

Forcibly throwing exceptions in a Java program.

Learning about try-catch statements of Java.

Using finally and throw statements of Java

Learning to create user-defined exceptions in Java.

Introduction
One of the salient features of Java is exception handling. An exception is an exceptional event
that may cause a program to terminate without completing. But java provides exceptional
handling feature using which program can be terminated in a graceful manner even if an
exception occurs. Java provides various statements like, try, catch, finally, throw, throws etc. to
deal with exception handling.

Java API comes with inbuilt classes like Exception and

Throwable that provide various methods for exception handling. Java also enables a user to
define his own user-defined exceptions.

Managing Errors And Exceptions- An Introduction


When a program is developed it may have some errors in it. Those errors or bugs affect a
program in many ways. Some dont allow a program to run, and some produce wrong output.
Still some other types of error may cause a program to crash in between. First, let us study the
various types of errors and the difference between error and exception.

Types of Errors (Compile-time error, Run-time error)


An error is a bug in the program due to which program does not compile or run successfully.
There are different types of errors which occur at different times during the program
development.

161

Compile Time Error


Some errors are caught by the java compiler when a program is compiled. Compiler displays an
error message along with the line number having erroneous statement. An example of compile
time errors is syntax errors which occur when there is grammatical mistake in the program, for
example using an undeclared variable, missing semicolon at the end of a statement, misspelling a
java keyword etc.
But, compile time errors are not very risky, since compiler will not compile the program until it
is error free. In a way, compiler helps in finding and removing such errors.

Run Time Error


Sometimes some errors are not detected by compiler. A program with a run time error may
abruptly abort in between with only partial work done, and will have to be restarted after
modifications. Such errors pose a big problem. An example is dividing a number by zero,
calculating square root of a variable that has a negative number in it. An invalid input given by
the user may also cause run time errors to occur.

Check Your Progress / Self Assessment Questions


14 Ques 1. Which type of errors are easy to detect and debug?
15 Ques 2. Writing Float instead of float is which type of error ?

Exceptions, Syntax of Exception Handling Code

In Java, a run time error is called an exception. An exception indicates an exceptional event
or situation. It is basically, an abnormal event, that occurs in a program at run time i.e. when
a program is actually running or executing. There are two things that can be done when an
exception occurs. First, just ignore it and let the program abort. Second, do some efforts to
resolve the issue and let the program continue. First method is called uncaught exceptions
and second method that is more technical and requires some efforts at programmers level is
called exception handling.
Actually, unlike some other programming languages like C, Java does not let a program abort
abruptly in between due to run time error in it. A program that aborts in between creates a

162

bad impression about the developer. So, Java provides an elegant way of dealing with run
time errors called exceptions, it called exception handling.

An example of uncaught exception:


public class exception1
{

public static void main(String a[ ])


{

System.out.println(5/0); //this statement has an uncaught exception


System.out.println("hello");

}
}
Output :

It shows that program is compiled successfully. But when it is executed, it aborts at line
number 5 displaying a message that there is arithmetic type of exception at line 5.
Suppose, in above program, instead of 5/0, we were using 5/x, where x is given by user, then
for any non-zero value of x, program will run successfully, but if user gives x as zero, then
again, above program will generate run time error. This is why it is said that run time errors
depend on user input.
Exceptions in java are represented by an inbuilt class named Exception, and it has many
subclasses that represent a particular type of exception, like, ArithmeticException as shown
in the output of above program. Exception class is part of java.lang package (default package
automatically included inside every java program).

Exception handling
To handle exceptions in a program is called exception handling. For exception handling,
Java provides try catch finally statements and try catch blocks. These statements are used
in combination i.e. try cannot be used without catch and catch cannot be used without try.
But, a single try can have multiple catch blocks.

163

That part (or block) of Java program which may generate a run time error is written in pair of
curly braces under the heading try and it is called try block.
Another part which tells java compiler what to do if try block generates a run time error, is
written under heading catch, and it is called catch block.
Using this try block and catch block in Java program is known as exception handling. When
a run time error occurs in try block, it is termed as exception is raised or exception is
thrown.

Syntax of Exception Handling Code (Try block and Catch block)


Both try and catch are Java keywords and java statements, their syntax is :
try
{
//this is called try block.
//This is the code that may generate/throw run time error (exception)
}

Try block is followed by catch block, its syntax is :


catch(ExceptionType object)
{
//catch block handles the exception raised by try block.
//It runs only if an exception is generated by try block.
}
It is not necessary that code written inside try block will generate an exception, it may or may
not. This is called risky code. Statements written inside catch block are executed only if try
block generates an exception; otherwise statements written inside catch block are skipped.
Catch block is exception handler. One catch block can handle one type of exception only.
And it has to be specified at the start of catch block that what type of exception it will catch.
This is specified by creating an object of the exception type with catch keyword.

Example
public class exception1

164

public static void main(String a[ ])


{

try
{

System.out.println(5/0); //this statement has an uncaught exception


System.out.println("hello");

}
catch(Exception e)
{

System.out.println("Sorry, an exception occurred, Program terminating.");

}
System.out.println("Bye");
}
}
Output :
Sorry, an exception occurred, Program terminating.
Bye

In this program, when an exception occurs in try block (5/0), program does not terminate
abruptly, rather the control jumps to the catch block given below the try block. Given catch block
handles exception type Exception which is parent class of every exception in Java. So
exception raised in a try block matches object e of Exception type. Therefore code written inside
catch block is executed. After this remaining part of program, code given after catch block is also
executed and then the program ends. This example shows that program is not aborted in
between, rather it ends successfully.

Example 2
Find the output of program:
public class exception2
{

public static void main(String a[ ])


{

try
{

System.out.println(5/0); //this statement has an uncaught exception

}
catch(ArrayIndexOutOfBoundsException e)

165

System.out.println("Sorry, an exception occured, ");

}
System.out.println("Bye");
}
}

Multiple Catch Statements


One try block can have multiple catch blocks following it. This is logical and sometimes
necessary, because the risky code given inside try block may generate more than one type of
exception. To handle each type of exception that the code inside try block may generate, a
corresponding catch block is given, since one catch block can be used to catch and handle one
specific type of exception only. This is illustrated in example given below:
public class exception3
{

public static void main(String a[ ])


{

try
{

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


arr[2]=arr[1] / arr [4] ; //arr[4] does not exist.
System.out.println(arr[2]);

}
catch(ArithmeticException e)
{

System.out.println("Sorry,

an

exception

occurred,

Program

terminating....");
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("ArrayIndexOutOfBounds, Program terminating....") ;
}
System.out.println("Bye");
}
}
Output

166

ArrayIndexOutOfBounds, Program terminating....


Bye

Using finally Statement


When an exception occurs in try-block at a statement, say at statement-x, control transfers to the
corresponding catch-block (skipping the code below statement-x in try block), and then code
inside the given below catch-block is executed and finally program ends.
But, sometimes it is required to perform some necessary cleanup job before a program exits. This
code can be given in another special block called finally-block that is written with finally
keyword of java. For example, suppose code inside try block opens a file, start working with it
and in-between an exception occurs, that is handled inside catch-block and then program ends.
But, now before exiting it is necessary to close the file opened in try block.
The finally block always executes when a program exits from try-catch block. If no exception is
thrown or raised by the code given inside try-block, then catch-block is skipped but finally-block
is executed.

If an exception is thrown by try-block then, both matching catch block and

finallyblock are executed.


Example
import java.io.*;
public class trycatchfinally
{

public static void main(String a[ ])


{

FileReader reader = null;


try
{

reader = new FileReader("Output.txt");


int i=0;
while(i != -1)
{
i = reader.read();
System.out.println((char) i );
}

}
catch (IOException e)

167

{
}
finally
{

try
{

reader.close();

}
catch(Exception e)
{
}
}
System.out.println("--- File End ---");
}
}
This program, tries to open a text file Output.txt for reading its contents. In both cases i.e.
when program ends successfully or if any exception occurs in between, file must be closed
before program ends. This is achieved using finally block which closes the file using
reader.close( ). Note that finally block itself has a try catch block. It is required in this example
because reader.close( ) itself may throw an exception.
Output of above program depends on the contents of output.txt file.

Check Your Progress / Self Assessment Questions


16 Ques 3. True/False : One or Zero catch block may follow try block.
17 Ques 4. True/False : It is compulsory to write finally block with a try-catch block

Throwing Our Own Exceptions


Sometimes it may be required in a program to generate an exception forcibly. This is performed
in Java using throw statement. Throw statement uses an object of particular exception type of
which exception is to be thrown. Immediately after throw statement control is shifted to
matching catch block. If no matching catch block is found, program terminates.
Syntax of throw statement is :

168

Throw objectname ;
Where throw is keyword of java, and object name is new object of any exception type defined in
Java.
The code or method that throws an exception has to be specified using throws clause , throws
clause indicates that this code may generate a run time error.

Example
public class ThrowingException extends Exception
{

public static void main(String a[ ]) throws ArithmeticException


{

try
{

throw (new ArithmeticException( ) );

}
catch( ArithmeticException e)
{

System.out.println(e.toString( ) );

}
}
}
This program illustrates throwing an exception at our own. An exception of type
ArithmeticException is thrown from try block given inside main( ) method. Therefore, main is
said to be throws an exception. Exception thrown is caught inside catch block.

Using Exceptions for Debugging


Exception handling facility provided by Java can be used for debugging purpose also. It can be
used to ascertain where a bug has exactly occurred. So it can be of great help to java developers.
Java.lang.throwable provides a method printStackTrace( ).It helps to trace the exception
down the stack memory. If one of methods of a class causes a bug, then printstack helps to
identify which method has caused the bug. It works like this :

First of all in an program, main( ) method is called and is pushed on to stack, then the second
method, if any, is called and pushed on to the stack in Last In First Out (LIFO) order, and so on,

169

Now, if any error occurs somewhere inside any method then this stack information helps to
identify that method by displaying the stack contents from top to bottom, this is called stack
trace. In this way, printStackTrace() shows the location in the source code where the error or
exception occurred, thus allowing the developer who wrote the program to see what went wrong.
It actually, shows several lines on the output screen. First line consists of several strings. It
contains the name of the throwable sub-class and information about the package. From second
line onwards, it describes the error position/line number beginning with "at".

Example
class PrintStackTrace
{

public static void main (String[ ] a)


{

int x = 10;
try
{

x = x / 0;

}
catch(ArithmeticException e )
{

e.printStackTrace();
System.out.println(e);

}
System.out.println("Going Good");
}
}
Output :
java.lang.ArithmeticException : / by Zero
at PrintStackTrace.main(PrintStackTrace.java : 8)
java.lang.ArithmeticException : / by Zero
Going Good

Handling System defined Exceptions

170

There are two types of exceptions in Java. First type is JVM Exceptions which are exceptions
thrown exclusively by JVM. For example, all exceptions discussed in this lesson till now are
JVM

exceptions.

Examples

include:

NullPointerException,

Arithmetic

Exception,

ArrayIndexOutOfBoundsException etc. Second type is Programmatic exceptions, it includes


exceptions

thrown

explicitly

by

the

application

or

the

API.

These

include

IllegalArgumentException, IllegalStateException.

Creating and handling user defined exception


Java language enables a programmer to define his own exceptions called user defined
exceptions. This becomes necessary when we wish to have exception types which have a
behavior different from in-built exception types, for example, when it is required to have some
specific customized condition checking.
To create user-defined exceptions, our class must extend Exception class, and it must define
methods like getMessage( ), toString( ), printStackTrace( ) etc.
Example :
public class NotRectangle extends Exception
{
int l, b ; //l, b denote length and breadth.
NotRectangle( ) //default constructor of class
{

l=b=0 ;

}
NotRectangle(int x, int y) throws NotRectangle //parameterized constructor.
{

if(x<0 || y<0) // if length or breadth is ve then throw exception.


throw(new NotRectangle( )) ;
else
{

l=x ; b=y ;

}
}
public String toString( )
{
}

171

return "Error Occured" ;

public static void main(String a[ ])


{
try
{

NotRectangle r1=new NotRectangle ();

//r1 will have l=0, b=0;

NotRectangle r2=new NotRectangle (0, -1); //will throw exception.


}
catch (NotRectangle x)
{
System.out.println(x.toString( ));
}
}
}

172

Check Your Progress / Self Assessment Questions


Ques 5. Which class will be used as base class to define our own exceptions?
Ques 6. Which method can be used in a class to display exact location of an error?
Ques 7. True/False : It is compulsory to define toString( ) method in a user defined
exception.

Summary
When a program is developed it may have some errors in it. Those errors or bugs affect a
program in many ways. Some dont allow a program to run, and some produce wrong output.
Still some other type of error may cause a program to crash in between.
Complie time errors are caught by the java compiler when a program is compiled. Runtime
errors occur when a program actually runs. A program with a run time error may abruptly abort
in between with only partial work done, and will have to be restarted after modifying
In Java, a run time error is called an exception. An exception indicates an exceptional situation
or event. To handle exceptions in a program is called exception handling. For exception
handling Java provides try catch statements and try catch blocks.
One try block can have either one or more catch blocks following it. This is logical and
sometimes necessary, because the risky code given inside try block may generate more than one
type of exception. When an exception occurs in try-block at a statement, say at statement-x,
control transfers to corresponding catch-block (skipping the code below statement-x in try
block), and then code given below catch-block is executed and finally program ends.
Sometimes it may be required in a program to generate an exception forcibly. This is performed
in Java using throw statement. printStackTrace method of Exception handling facility provided
by Java can be used for debugging purpose also. It can be used to ascertain where a bug has
exactly occurred.

173

Java language enables a programmer to define his own exceptions called user defined
exceptions. This becomes necessary when we wish to have exception types which have a
behavior different from those provided by system exceptions.

174

Glossary

Error : a bug in the program.

Compile Time Error : a type of syntax errors, are caught by compiler.

Run time Error : occur at run time, are not detected by compiler.

Exception : Java name for a run time error.

Exception Handling : Java feature to deal with run time errors.

Debugging : Detecting and Correcting errors.

try : java statement and keyword that encloses a code that may generate an exception.

catch : Java statement and keyword, used to write exception handling part.

Final : Another java keyword, used to create literals.

Finally : java keyword, used to create finally block that always runs irrespective of
occurrence of exception.

System defined exceptions : Various in built exception types, like ArithmeticException.

User defined exceptions : exception classes defined by user.

Answers to Check Your Progress / Self Assessment Questions


Ans 1. Compile time errors.
Ans 2. Compile time error.
Ans 3. False. (there must be one or more catch blocks after try)
Ans. 4. False.
Ans. 5. Exception or Throwable.
Ans. 6. printStackTrace( ) method can be used to display exact location of a method.
Ans. 7. False. It is not compulsory, if not defined, it will be used from parent class.

175

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
Ques. 1. What is exception? How an exception is handled in Java?
Ques. 2. What is need of having multiple catch blocks with a single try block in Java? Give
example.
Ques. 3. Create a user defined exception, that does not allow a new student object with roll no of
three digits.
Ques. 4. What is use of printStackTrace ( ) method?
Ques. 5. Write a note on various system defined exceptions in Java?

176

PDCA-201
Applets
Unit-3. Lesson - 11

Applets

Chapter Index
Objectives
Introduction

How Applets differ from Applications

Preparing to write applets

Building Applet Code

Applet Life Cycle

Designing a Web Page

Applet Tag

Adding Applet to HTML File

Running the Applet

Types of Applets

Using Applet Applications

Passing Parameters to Applets

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

Understanding the meaning and significance of Applets.

177

To understand how to run applets in a web page.

Being able to create html document.

Using inbuilt java.awt and java.applet packages.

Creation of dynamic applets using parameter passing.

178

11.1 Introduction

Java provides another way of creating a special kind of GUI based programs that are embedded in a web
document called applets. The applets can run inside a web browser or by using utility appletviewer for
testing purpose. The applets can also be transported over the internet along with the web document
using the HTTP protocol. Different arguments can be sent to applets at run time making it dynamic and
flexible in nature.

11.2 How Applets differ from Applications


1.

Applets are executed as a part of a web page and its output is displayed within a Java-enabled
browser, whereas applications, are any general-purpose Java programs that donot need a Java
enabled web browser to execute.

2.

Applets are designed mainly for handling the client side problems while the Java applications are
designed to work with the client as well as the server.

3.

Applets usually don't have the main( ) method, whereas an application must have a main( )
method.

4.

An applicationcan be CUI (Character User Interface) or GUI (Graphical User Interface), whereas
applet must run within a graphical user interface environment.

5.

Applets have a limited access to the resources of the local machine, where the applets run. The
applications have full access to machine resources such as files or databases.

Check Your Progress / Self Assessment Questions


Ques 1. True / False : An applet does not require main( ) method?
Ques 2. True / False: Applets have limited access to the resources of the client machine?

11.3 Preparing to write Applets

179

To create an applet in Java, it is requiredto import two java inbuilt packagesjava.applet.Appletand


java.awt.* in a user defined class. These packages are necessary because the Applets are not consolebased programs rather it runs on Window-based environment and interact with the user through GUI
(Graphical User Interface). The access type of the class must be public to make it accessible from the
HTML document. The class must be inherited from the Applet class of the applet package using the
keyword extends. The paint( ) method provided by the AWTpackagecanbe overridden to display its
output.The syntaxof creating an applet is:
import java.applet.* ;
import java.awt.* ;
public class AppletName extends Applet
{
// Applet code
}

11.4 Building Applet Code


To build an applet code, two packages java.awt and java.applet are imported in an applet class. The
applet code is shown below. The drawString( ) methodin the program shows the message: "Hello
World, Form a Simple Java Applet !" at location 50,25 in the browser window.
import java.awt.* ;
import java.applet.* ;
public class MyApplet extends Applet
{
public void paint(java.awt.Graphics g)
{
g.drawString("Hello World, Form a Simple Java Applet !",50,25);
}
}

180

Output

Once the applet program is designed and ready to run, the following steps are required to build the
compile code:

Savesource file as MyApplet.java. The name of Java source file must be same as the applet class.

Compile the Java source file to create a class file.

Check Your Progress / Self Assessment Questions


Ques 3. Which packages are required to create an applet ?
Ques 4. Which class will be inherited to create an applet?

Applet Life Cycle

Every applet has five stages in this life cycle, each of which has a matching method. You can
override these methods to gain access to the life cycle of the applet's life. The five stages of an
applet's life cycle are shown in Fig. 11.1. The default implementation of these methods is
provided which does nothing. Applets need not to override all of the methods. Because applets
run in a web browser, therefore these methods are not called directly by the applet. The browser
or applet viewer calls these methods at appropriate times during the life cycle of an applet.

181

Figure 11.1. Life cycle of an applet.

Initialization State
In this phase, the applet is first initialized with values that are used by the applet later on.. The
method init( ) is overridden in the class for this purpose. This method is called by the web
browser when an applet is loaded first time or reloaded. It serves the same purpose as the
constructor in the console based program.

RunningState
The start phase occurs after the initialization phase when the web browser starts running the
applet or when the applet restarts again. The method start( ) is overridden in the class for this
purpose and is called automatically by the web browser every time the web page containing the
applet is revisited.
Stop State
The applet enters in this phase, when it is no longer visible on the screen such as when the user moves
to a different Web page. The stop( ) method used for this purpose, is automatically called by web
browser to tell the applet that it should stop its execution. It is called automatically by java when the
web page that contains current applet is replaced by another page.

DisplayState

182

The paint phase occurs whenever the applet's output is drawn on the screen for the first time as
well as whenever the applet's output must be restored or changed. For this purpose, the paint( )
method is used and is called once after start( ) method is called and again each time the web
browser is activated.
Whenever the applet needs to redraw its output, the paint( ) methodis called. The paint( ) method takes
one parameter of type Graphics. This parameter contains the graphics context, which provides the
graphical environment in which the applet is running. This context is used to draw output to the applet
window. The Graphicsclasscontains several methods which can be used to draw string, line, oval,
rectangle etc. Inside paint( ) method, the drawString( ) method is used that outputs a string starting at
the specified X,Y location. Its syntax is:
void drawString(String msg, int x, int y)

Here, msgis the string to be output beginning at position x,y. In a Java window, the upperleft
corner is at location (0,0).
DeadState
This phase occurs when an applet ends and the system is ready to deallocate memory, i.e. to remove
the applet from memory. Like the initialization phase, the destroy cycle occurs only once. If your applet
has captured resources that need to be cleaned up before the applet exits, this is the place to do it. The
destroy( ) method is called by the browser only once, when an applet shuts down.

The following example demonstrates the use of some of the applet life cycle methods:

import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
String msg = "" ;
public void init( )

183

{
msg += "Init method " ;
}
public void start( )
{
msg += "Start method " ;
}
public void paint(Graphics g)
{
msg += "Paint method " ;
g.drawString(msg,40,20);
}
}
Output

184

Creating an executable applet


To create an applet executable, the applet program needs to be compiled. After that a class file is
created using the java compiler javac. Create an HTML document and embed the class file in a web
document using an <applet> tag.Run the HTML document inside any Java enabled web browser.

Check Your Progress / Self Assessment Questions


Ques 5. Which method of the applet life cycle is used to draw output on the applet window?
Ques 6. Which method is used to initialize an applet?

Designing a web page


A web page is designed in HTML (Hyper Text Markup Language), and optionally with some scripting
language like Java script or VB Script to add some interactivity in web page. HTML provides many
commands called tags to control the layout of web page. A web page is run in a special software called
web browser. There are many web browsers available today, some more popular are Internet Explorer,
Google Chrome, Mozila Firefox etc. Due to their popularity and common use, sometimes a browser is
made an integrated part of Operating System.
Web pages are topic of study here because we can run applets as a part of web page, this is called
embedding an applet in a web page. HTML provides special tags for this purpose.
A web page is divided among different sections, as explained below.

Comment Section
The comment section is used to insert comments in the html code and makes the program more user
friendly. The comments are not executed by the browser and are not displayed in the browser. The <!-...--> tag is used to insert single or multiple line comments in the code. For example

185

<!-This is multiple lines


Comments used in the code
//-->

Head Section
The head section contains the information about the HTML document like title, styles, links, scripts, and
other meta information.

The <title> tag is used to define the title of the document.

The <style> tag is used to declare style information for an HTML document.

The <base> tag specifies the base URL of another document.

The <link> tag defines a link to external style sheets

The <meta> tag provides information about the HTML document. The contents of <meta> tag will
not be displayed on the page.

The <script> tag declares a clientside scripting languages such as a JavaScript or VBScript.

An example of using head section and its tags is given below:

<html>
<head>
<title>Web Site of PTU</title>
<style>
h1 {color:blue;}
p {color:red;}
</style>
<base href="http://http://www.ptu.ac.in//" target="Home Page">
<link rel="stylesheet" type="text/css" href="sheet.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
</head>

186

<body></body>
</html>

Body Section
The body section contains all the contents of the html document, such as texts, hyperlinks, images, lists,
tables, forms etc. HTML provides various tags to place these elements in the body of the document.
Tags with their attributes can also be used to control how the elements look on the page.
A very simple example of HTML code is given below. Type this code in notepad and save as Test.html.
After this, just double click on the icon where the file is saved. It will open in web browser.
<html>
<head><title>My first web page </title></head>
<body>
<b>Welcome !</b>
<br />
<b>This is body of web page containing main contents of the document.</b>
</body>
<html>

187

Applet Tag
HTML provides APPLET to embed applets in a web page. It is a paired tag (means, it opens with <applet>
and closes with </applet>). This tag is used to embed an applet in a web page and provides the
necessary information about the location of the appletss class file. Applet tag has many attributes that
can be used to provide some additional information about the applet being embedded.
The applet will be loaded and executed by a Javaenabled web browser when it encounters the applet
tag within the HTML file. The syntax of Applet tag is:
<APPLET code = appletName.class width=value height =value>
</APPLET>

Some of the attributes of Applet tag of HTML are:


code

It specifies the name of the .class file. If the .class file is in some other folder than
.html file, its path has to be mentioned.

width

The width of an applet in pixels is specified using integer value.

height

The height of an applet in pixels is specified using integer value.

When a Java-enabled browser encounters an <APPLET> tag, it performs the following operations:

Reserves a display area of the specified width and height for the applet.

Loads the bytecode for the specified applet class.

Creates an instance of anapplet.

Calls the applets methods such as init( ), start( ) methods etc.

Check Your Progress / Self Assessment Questions


Ques7.What is the use of <script> tag?
Ques 8. Which tag is used to insert an applet in a html document?

188

Adding Applet to HTML file


In order to run an applet in a Java enable web browser, the applet is included in a web page and is
treated as a part of webpage. For this purpose, create a web page using the minimum required HTML
tags as shown below:
<HTML><Head>
<Title>A Simple Applet </Title>
</Head>
<Body>
<Applet code="MyApplet.class" width="150" height="50">
</Applet>
</Body>
</HTML
In the above HTML code, the class file MyApplet.class is embedded using the applet tag. For
simplicity, the HTML file and applet class file should be saved in the same folder.

Running the Applet


We can run the applet simply by opening the HTML file containing the applet in the browser and will
display web page and the applet running under it. There are two ways to run an applet:
1.

Double click the HTML file and it will be loaded in a default web browser to display the output.

2.

An alternative way to run the applet is with the utility appletviewer using the following command
at the command prompt: appletviewer< html filename>. It will invoke a window with the applet
running inside it.

Types of Applets

189

In Java, applets are of two types: Signed and Unsigned. The unsigned applets are considered to be untrusted and operate within a security sandbox that allows only a set of safe operations. The unsigned
applet can only communicate with the server from which it was downloaded and cannot access the
resources of the local machine on which it is running.
On most browsers, unsigned applets cannot perform the following tasks:

Applets cannot access client resources such as the local file system and executable files.

Applets cannot communicate with any server other than the server from which they were
downloaded.

Applets cannot load native libraries.

Applets cannot initiate a printing job.

On the other hand, the signed applets require a digital certificate to indicate that they come from
atrusted site. Hence, they operate outside the security sandbox and have extensive capabilities to access
the client side resources.

Using Applet as Applications


The applet can be executed like an application by adding a main( ) method to the applet. There is no
need to create a new class. It may seem a little strange that adding a main( ) method to a class will make
it into an application, but that's the most common way of doing it. An application is any program that
has a main( ) method. To run an applet as an application, the following steps are required:
1.

Include main( ) method in an applet that will execute when you run applet as an application.

2.

Create a Frame window that is used to hold the applet.

3.

Create a new instance of an applet and insert it to the parent window.

4.

Start the applet by calling init( ) from the main( ) method and then start( ) if these methods are
overridden in applet.

5.

Finalize the layout.

6.

Make the frame window visible.

Lets take an example that illustrates the above concept.

190

import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
String msg = "Hello Everybody..." ;
public void paint(Graphics g)
{
g.drawString(msg,40,20);
}
public static void main(String args[ ])
{
Applet helloApplet = new HelloApplet( );
helloApplet.init( ) ;
Frame window = new Frame("Here it runs as an Application") ;
window.setSize(300, 200) ;
window.add(helloApplet) ;
window.setVisible(true) ;
// Make the window visible
}

}
Output

Passing Parameters to Applets


AJava applet has the capability of receiving the argument values passed from the html page using
parameter attribute of the applet tag as illustrated below:
<APPLET code = applet class name width = value height = value>
<param name = p1 value = "v1">

191

<param name = p2 value ="v2">

<param name = pn value = "vn">


</APPLET>

The parameter names used and their corresponding values are by default strings, whether or not they
are quoted. Therefore an applet checks that a valid string is returned as a parameter value. For each
parameter the NAME attribute must be specified, but the VALUE attribute is optional. The applet
should use a default value if no valid string is returned.The Applet class of the package java.awt.applet
contains a getParameter( ) method used to retrieve a value of the specified parameter as a String
object: public String getParameter(String name)
It returns the value of the named parameter in the HTML tag. The name argument is case
insensitive.The parameter passing mechanism can be illustrated with the help of an example:
import java.applet.*;
import java.awt.*;
public class parameterApplet extends Applet
{
String arg = "Welcom to Java Applet." ;
public void paint(Graphics g)
{
String msg = getParameter("Message");
if (msg == null)
msg = arg ;
g.drawString(msg, 50, 25);
}

192

Here is HTML code:


<HTML>
<HEAD>
<TITLE>Parameter Passing to Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="parameterApplet.class" width="350" height="200">
<PARAM name="Message" value="Welcome to Web Pages using Java Applets.">
</APPLET>
</BODY>
</HTML>

Output

Check Your Progress / Self Assessment Questions


Ques 9. Which utility is used to run an applet without embedding it in html document?

193

Ques 10. Which method is used to receive argument values from html document?

Summary
Java offers GUI based special programs called applets that are executed in a java enabled web browser
and can transport over the internet using Http protocol alongwith web document. The Applet class
contained in java .applet package is used to create an applet. The Applet class contains several methods
that are used to control the execution of an applet. An applet is a part of web documents and can be
inserted in an html page using <applet > tag. To run an applet, open the web page containingthe applet
in any Java enabled web browser or use the utility appletviewer. To create an applet, the following
inbuilt packages are used:

java.awt : provides GUI environment

java.applet: provides classes to create an applet

Applets are of two types: signed and unsigned. The unsigned applets are executed in a restricted
environment and cannot access the resources of the client machine, whereas, the signed applets can
access the resources. To make the applet dynamic in nature, an applet and html document can
communicate with others through the passing of parameters.

Glossary

Applet : a GUI based programs that runs in a web browser.

Application : a java program that does not need browser to run.

Life cycle : stages in the life of an applet.

Init: First stage in the life of an applet.

start( ) : start method is overridden used in java class, it provides what an applet will do.

194

Java.awt: abtract window toolkit package of java that provides window environment to an
application.

HTML : Hyper Text Markup Language, a language used to design web pages. Its commands are
called tags.

java.applet : Another builit in package of java that provides Applet class to create an applet.

<applet> tag : html tag used to insert an applet in html document.

Param : HTML tag, used to provide parameters to an applet.

appletviewer: Java built in utility to run and test an applet, without using browser.

Answers to Check Your Progress / Self Assessment Questions


Check Your Progress / Self Assessment Questions
Ans1. True
Ans2. True
Ans3. Java.awt and java.applet
Ans 4.Applet class
Ans 5.void paint( )
Ans 6. void init( )
Ans 7. The <script> tag is used to declare scripting languages such as JavaScript.
Ans 8. <applet> tag
Ans 9. AppletViewer utility
Ans 10. String getParameter(paramterName)

195

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. What is the difference between an application and an applet?
2. How can an applet be embedded in a web document.
3. Explain life cycle of an applet.
4. What is the use of <head> and <body>sections in HTML?
5. What is use of Applet tag in HTML ?
6. How can arguments be sent to an applet ?
7. What is the difference between signed and unsigned applets?
8. What are various advantages of applets in java?
9. How an applet can be used as an application ?

196

PDCA-201
Advanced Applet Programming
Unit-3. Lesson - 12

Chapter Index
Objectives
Introduction

More About Applet Tag

Passing Parameters to Applets

Aligning the Display

More about HTML Tags

Displaying Numerical Values

Getting Input from the User

Summary

Glossary

Answers to Check Your Progress / Self Assessment Questions

References / Suggested Readings

Model Questions

Objectives

Understanding in detail, how to manage the layout of an applet in a web page.

To discuss the passing of parameters to applet and using them in an applet.

Manage the alignment of an applet with in html page.

To discuss the input/output operations in applets

197

12.1 Introduction
If required, Java applets can be designed to communicate with a web page, this feature makes applets
interactive and dynamic in nature. Any number of values (called arguments) can be passed from the
webpage page to the applet.At runtime, the applet retrieves the arguments from the web page using
the PARAM attribute of the applet tag. The layout of an applet can be controlled by setting the different
attributes of an applet tag. Applets can perform input/output operations. For security reason, an applet
created in Java is executed inside a sandbox by a web browser. It prevents an applet from accessing
local file system or clipboard of the local machine.

More about Applet Tag


The APPLET tag in HTML is used to embed an applet in a webpage and provide all
necessaryinformation that the web browser uses to locate, display and run an applet in a web
page. Most of the web browsers like Netscape Navigator, Internet Explorer, Mozilla Firefox and
Google Chrome are Java enabled browser. Java enabled web browse means that the browse
engine has JVM built in it, that executes Java code. APPLET tag can be used within the BODY
section of HTML page to insert more than one applet. In the previous chapter, we have used only
a few attributes of the APPLET tag. Now, the APPLET tag will be studied in more detail.
The syntax of the APPLET tag is shown below with its various attributes alongwith the meaning
of each attribute. Some of the attributes are optional and are shown in square brackets.
< APPLET
CODE = applet class file
WIDTH = width of an applet
HEIGHT = height of an applet
[CODEBASE = URL directory]
[ARCHIVE = Name of the JAR files]
[ALT = alternate text message in case applet is not loaded]
[ Alternative HTML text]
[NAME = names of other applets on this HTML page]
[ALIGN = alignment]
[VSPACE = horizontal space]
[HSPACE = vertical space]
[< PARAM NAME = "AttributeName_1" VALUE = "AttributeValue_1>"]

198

[< PARAM NAME = "AttributeName_2" VALUE = "AttributeValue_2>"]


...
</APPLET>
Value of each attribute should preferably be written within double quotes.Now, meaning and
purpose of each attribute will be explained in detail.
CODE
CODE is a mandatory attribute that specifies the name of the file containing your
applet'sclassfile. The filename is interpreted relative to the directory containing an HTML page.
If CODEBASE attribute (explained below) is not specified, then both applet class file and an
HTML file must be stored in the same directory.

WIDTH and HEIGHT


These attributes are also mandatory and are used to specify the width and height of the applet in
pixels. In web browsers, the applet cannot be resized, only the HTML page window can be
resized. However, the appletviewer allows the user to change the size of the applet when the
applet is running. For example
<APPLET code = myApplet.class width = 200 height = 200>
</APPLET>

CODEBASE
This attribute is optional which inform the browser that the applet class file are found under the
directory URL specified in the CODEBASE tag. The CODE attribute is then interpreted relative
to this directory.
<APPLET codebase = projects/applets code = myApplet.class width = 200 height = 200>
</APPLET>

ARCHIVE
All classes and resources that are required by an applet can be bundled together in a JAR file.
(JAR is a compressed file, and can be created with jar utility of Java). The ARCHIVE attribute is
an optional, used to specify the JAR file. This file is fetched from the web server before the
applet is loaded. This technique is used to speedup the loading of an applet.
<APPLET archive = appletClasses.jar code = myApplet.class width = 200 height = 200>

199

</APPLET>
ALT
The ALT attribute is an optional attribute. It is used to specify a short text message that should
be displayed if the browser understands the APPLET tag but is currently unable to run Java
applets.
<APPLET code = myApplet.class alt = Java runtime is unable to run applet width = 200
height = 200>
</APPLET>

Alternate Text
In case, a browser does not support applets, then the optional alternative HTML text will be
displayed. This text is specified inside the <Applet> tag, in case browser is java enabled and can
run the applet then this text will be ignored by the browser.
<APPLET code = myApplet.class width = 200 height = 200>
Sorry, the browser cannot run the applet.
</APPLET>

NAME
This attribute can be used to assign a name to the applet within an HTML page. This name can
be used by applets to identify each other for inter-applet communication. Assigning a name to
the applet is useful in case, html page contains more than one applet.

ALIGN
This attribute specifies the alignment of the applet within the HTML page. This attribute can be
assigned to one of these possible values: LEFT, RIGHT, TOP, BOTTOM and MIDDLE.

VSPACE and HSPACE


The attribute VSPACE specifies the space, in pixels, above and below the applet. HSPACE
specifies the space, in pixels, on the left and right side of the applet.

200

<APPLET code = myApplet.class width = 200 height = 200 align = TOP hspace=20
vspace=25>
</APPLET>

The use of attributes in applet tag is demonstrated with the help of an example:
import java.awt.* ;
import java.applet.* ;
public class MyApplet extends Applet
{
public void paint(java.awt.Graphics g)
{
g.drawString("Applet Using different applet tags",50,25);
}
}
Here is corresponding html code to display applen in a web page.
<HTML>
<Head>
<Title>
A Simple Applet
</Title>
</Head>
<Body>
<Applet code="MyApplet.class" alt = "Browser is unable to run applet !"
width="350" height="150" align = BOTTOM vspace = 25 hspace = 25>
</Applet>
</Body>
</HTML
Output

201

The status bar is place at the bottom of the web browser or applet viewer which can be used to
display the message. The message can be displayed using the showStatus(String msg) method.
The status bar is used to display the information that is helpful to the users. There are two
additional methods of the AWT package that are commonly used to set the foreground and
background colors. The syntax is:

void setForeground(Color c)
void setBackground(Color c)

These methods takes a single argument, which is an instance of Java.awt.Color class. The calss
Color defines several constants such as Color.blue, Color.red, Color.gray, Color.darkGray etc. to
represent different colors that can be used to specify colors. The following program demonstrates
the use of showStatus( ) method:
import java.awt.*;
import java.applet.* ;
public class ShowStatusApplet extends Applet
{
String msg = "" ;
public void init( )
{
setBackground(Color.gray) ;
setForeground(Color.blue) ;
msg = "Applet setting the foreground and background colors" ;
}
public void paint(Graphics g)
{

202

g.drawString(msg,40,20);
showStatus("This message is displayed in the status window....") ;
}
}
Output

So far, we have only display text strings in the applet window. The class Graphics of the AWT package
defines several methods to draw different shapes like lines, rectangles, circles etc. Each shape can be
drawn filled or without filled having edges only. The following program shows the use of drawing
methods:

import java.awt.*;
import java.applet.*;
public class ShapeApplet extends Applet
{
public void init( )
{
setBackground(Color.white) ;
}
public void paint(Graphics g)
{

g.setColor(Color.black);

203

g.drawString("Draw Shapes",150,20);
g.drawRect(100,100,100,100);
g.setColor(Color.gray);
g.fillRect(110,110,80,80);
g.setColor(Color.black);
}
}

Output

Another example showing the use of different shapes with different color combinations.
importjava.awt.*;
importjava.applet.*;
public class FlagApplet extends Applet
{
public void init( )
{
setBackground(Color.gray) ;
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(100,40,10,150);

204

g.setColor(Color.orange);
g.fillRect(110,40,170,35);
g.setColor(Color.white);
g.fillRect(110,75,170,35);
g.setColor(Color.blue);
g.fillOval(175,77,30,30) ;
g.setColor(Color.green);
g.fillRect(110,110,170,35);
}
}
Output

Check Your Progress / Self Assessment Questions

Ques 1. Which attributes are used to specify the width and height of an applet?
Ques 2. Which term is used to measure the size and location of an applet?

Passing Parameters to Applets


If required, some arguments or parameters can be passed directly from web page to applet. These
parameters along with their values are specified in web page inside applet tag of HTML. Applet

205

is also instructed to fetch or read these parameter values from web page. A Java applet has the
capability of retrieving the parameter values passed from the html page. The argument values
stored in html code are passed to the applet at runtime. This feature of applets make them
interactive and dynamic in nature.
The <PARAM> attribute of the <applet> tag is used to specify the (name , value) pair.
<APPLET code=AppletClassName width=w height=h>
<param name="p1" value="v1">
<param name="p2" value="v2">

<param name="pn" value="vn">


</APPLET>
The parameter names used and their corresponding values are treated as strings, whether or not
they are enclosed in double quotes. Therefore an applet should check that a valid string is passed
as a parameter value. For each parameter the NAME attribute must be specified, but the
VALUE attribute is optional.

The applet should use a default value if no valid string is

returned.The package java.applet contains an Applet class that contains a getParameter() method
used to retrieve value of specified parameter as a String object. It syntax is :
public String getParameter(String pname) - Returns the value of the parameter pname defined
in the <applet> tag of HTML in a web page. The pname argument is case insensitive.
The parameter passing mechanism can be illustrated with the help of an example:
import java.applet.*;
import java.awt.*;
public class ParamApplet extends Applet
{
int rollno ;
String name ;
String class_name ;
String dept_name ;
public void init( )
{
String rno ;
rno = getParameter("prollno");
if(rno != null)
rollno = Integer.parseInt(rno) ;
name = getParameter("pname") ;

206

class_name = getParameter("pclass") ;
dept_name = getParameter("pdept") ;
}
public void paint(Graphics g)
{
g.drawString("Roll No = "+rollno, 0, 15);
g.drawString("Std Name = "+name, 0, 30) ;
g.drawString("Class = "+class_name, 0, 45) ;
g.drawString("Class = "+dept_name, 0, 60) ;
}
}
Here is the corresponding HTML Code
<HTML>
<HEAD>
<TITLE>Parameter Passing to Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="ParamApplet.class" width="550" height="200">
<PARAM name="prollno" value="201515089">
<PARAM name="pname" value="Rajan Malhotra">
<PARAM name="pclass" value="MCA Semester IV">
<PARAM name="pdept" value="Department of Computer Science & Engineering">
</APPLET>
</BODY>
</HTML>

Output

Aligning the Display


The display of an applet is aligned using the ALIGN attribute of the <applet> tag. This attribute
specifies the alignment of the applet within the html page. This attribute can be assigned with

207

one of the constants LEFT, RIGHT, TOP, BOTTOM and MIDDLE and align the display
towards left, right, top, bottom and middle of the available space reserved for the applet in a html
page.
Check Your Progress / Self Assessment Questions

Ques 3. Which attributes of an applet tag are used to send arguments to an applet?
Ques 4. Is there any limit to number of arguments send to an applet?

208

More about HTML Tags


Note that, <APPLET> tag of HTML is not supported in HTML5. Though it was supported till HTML4.
HTML 5 recommends Use of <embed> or <object> tags instead of <applet> tag.
Further, some browsers also do not support <applet> tag. Some browsers support <applet> tag but
require additional plug-ins/installations to work.
How you load an applet in a web page depends mainly on how your users access the Web page, do they
access it through world-wide Internet or through company-wide Intranet. It also depends on the type of
browser they use. First you need to study this information about your users and then follow the general
guidelines below.
Use the <applet> tag if user accesses web page via Internet, use the <object> or <embed> tag if the user
accesses web page via intranet. Further, for Internet Explorer users only, use the <object> tag and for
the users of Mozilla family of browsers only, use the <embed> tag.
But, if you have wide variety of users and need to deploy an applet in a mixed-browser environment
then you will have to detect at run time what each user is using and then load applets accordingly. But,
this is easy to accomplish at run time using scripting language like java script. First, use javascript to
detect each user's browser type and settings etc. using appName variable. Second, use method provided
by Java Script, document.write( ) to write a tag, based on the value of the appName variable, this may
require some decision making. For example, If user is using browser name "Mozilla" then write the
<embed> tag in document.write method. Otherwise if browser name detectedis "Microsoft Internet
Explorer" then write the <object> tag in document.write method.
Below, this technique is explained. Java script method document.write() outputs one of two tages,
either an <embed> or <object> tag for each user at run time.
<html>
<script language="JavaScript">
var browserUsed = navigator.appName;
if (browserUsed == 'Mozilla')
{

209

document.write('<embed code="MyApplet.class"', 'width="250"',


'height="100"','type="application/x-java-applet;version=1.5.0">');
}
else if (browserUsed == 'Microsoft Internet Explorer')
{
document.write('<OBJECT ', 'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"',
'height="100", 'width="250"'>',
'<PARAM name="code" value="MyApplet.class">',
'</OBJECT>');
}
else
document.write('<p>Sorry, Applet cannot be loaded.</p>');
</script>
</html>

Check Your Progress / Self Assessment Questions

Ques 5. In which version of HTML, the <applet> tag is deprecated?


Ques 6. Which other tag, apart from <applet> can be used to embed an applet in a web
page?

Displaying Numerical Values


Applets are the window based programs and a window is used to capture input and display the
output. The Graphics class of AWT package provides several methods to display the text or draw
shapes such as line, rectangle, arc, polygons, ellipse and Circle. To display a text string, the
method drawString( ) is used. Java does not provide a method to display numerical values. For

210

this purpose, the numerical values are first converted into strings and then call the drawstring( )
method . Any numeric value can be converted into string by using a static method of the class
String. The syntax is:
String String.valueOf(numeric value) ;

Example:
import java.awt.* ;
import java.applet.* ;
public class DisplayApplet extends Applet
{
public void paint(Graphics g)
{
double phy = 95.50, chem = 72.50, math = 66.0, result = 0.0 ;
String percent ;
result = ( phy + chem + math) / 300 * 100 ;
percent = String.valueOf(result) ;
g.drawString("The percentage is "+percent, 100,75) ;
}
}
Output

Getting Input from the User


The applets run in a graphical environment. The input that is entered by the user (numeric or
text) is treated as a text strings. Thus, the input operations must be accomplished through AWT
control components such as text field or text area. The text field is used to enter single line of
text and the text area is used to enter multiple lines of text. It is also possible to use console
based input operations using methods such as System.scanner( ) etc. The input in this case will
be received from AWT window. Instead, it will receive from the console session in which you
have started the appletviewer. This can be demonstrated with the help of an example:

211

import java.awt.* ;
import java.applet.* ;
public class InputApplet extends Applet
{
TextField txtRollno, txtPhy, txtChem, txtMath ;
public void init( )
{
txtRollno = new TextField(15) ;
txtPhy = new TextField(3) ;
txtChem = new TextField(3) ;
txtMath = new TextField(3) ;
add(txtRollno) ;
add(txtPhy) ;
add(txtChem) ;
add(txtMath) ;
}
public void paint(java.awt.Graphics g)
{
double phy = 0.0, chem = 0.0, math = 0.0, result = 0.0 ;
String strPhy, strChem, strMath, strResult ;
try
{
strPhy = txtPhy.getText() ;
phy = Double.parseDouble(strPhy) ;
strChem = txtChem.getText() ;
chem = Double.parseDouble(strChem) ;
strMath = txtMath.getText() ;
math = Double.parseDouble(strMath) ;
}
catch(Exception e) { }
result = ( phy + chem + math) / 300 * 100 ;
g.drawString("The percentage is "+result, 150,125) ;
}
}
Output

212

Check Your Progress / Self Assessment Questions

Ques 7. Which method is used to display text on an applet window?


Ques 8. Which method of the String class is used to convert a numeric value to a String?

213

Summary
Java provides static and dynamic applets. The static applets always run in the same fashion and display
the same results every time they run. The dynamic applets are flexible and run in a different fashion and
produce different outputs. Different inputs can be passed from html page to an applet at runtime and
the applet behaves accordingly. The layout of an applet can be controlled using different attributes of
applet tag. The input/output operations can also be performed on an applet window using the
drawstring( ) method of the Graphics class.

Glossary

Applet : a window based Java program that runs in a web browser.

Codbase : this is an optional attribute of applet tag and used to specify the location of .class file,
in case it is not in the same folder as .html file.

<applet> tag : is used to insert an applet in html document.

Param : this HTML tag is used to provide parameters to an applet.

<Name, Value> attributes <param> tag is used to specify a attribute name and its value. The
attribute name is used in applet to retrieve the its associated value from the html page.

AWT control components such as TextField and TextArea is used to capture input from the user
in an applet window.

drawstring( ) method is used to display numeric as well as text strings.

Answers to Check Your Progress / Self Assessment Questions


Check Your Progress / Self Assessment Questions
Ans1. Width and height
Ans2. Pixels
Ans3. <param> attribute
Ans 4. No

214

Ans 5. HTML5.
Ans 6. <object>
Ans 7. drawstring(String text)
Ans 8. String.valueOf(numeric value)

References / Suggested Readings


1. Complete Reference Java, Tata McGraw Hill.
2. Core Java Volume I Fundamentals (9th Edition), Prentice Hall

Model Questions
1. How applet and html page can communicate with each other?
2. What is the use of (name, value) attributes of the <PARAM> tag.
3. What are different layouts to align an attribute?
4. How can numeric values be displayed in an applet?
5. Explain various attributes of applet tag available in HTML?
6. How can an applet receive input from the user?
7. What is use of <object> in HTML 5?
8. What is use of code and codebase attributes of applet tag?

215

You might also like