313
Self Learning Material Programming in Java (BSBC 502) Course: Bachelor of Computer Applications Semester-V Distance Education Programme I.K. Gujral Punjab Technical University Jalandhar

Self Learning Material Programming in Java

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Self Learning Material Programming in Java

Self Learning Material

Programming in Java (BSBC 502)

Course: Bachelor of Computer Applications

Semester-V

Distance Education Programme

I.K. Gujral Punjab Technical University

Jalandhar

Page 2: Self Learning Material Programming in Java

Syllabus

I.K. Gujral Punjab Technical University

BSBC 502 Programming in Java

SECTION-A FUNDAMENTALSOFOBJECT–ORIENTEDPROGRAMMING: -Introduction; Object-Oriented

Paradigm; Basic Concepts of Object-Oriented Programming Benefits of OOP; Applications of OOP.

JAVAEVOLUTION:-Java History; Java Features; How Java Differs from C and C++;Javaand Internet, Java

and World Wide Web, Web Browsers; Hardware and Software Requirements; Java Support Systems, Java

Environment

OVERVIEW OFJAVALANGUAGE:-Introduction; Simple Java Program; Comments in java; An application

with Two Classes; Java Program Structure; Java Tokens; Java Statements; Implementing a Java Program; Java

Virtual Machine; Command Line Arguments; Programming Style.

CONSTANTS, VARIABLES AND DATA TYPES:- Introduction; Constants; Variables; Data Types;

Variables, Constants, Standard Default Values.

OPERATORS AND EXPRESSIONS:- Introduction to Operators, Expressions; Operator Precedence;

Mathematical Functions.

DECISION MAKING, BRANCHING AND LOOPING: - Decision making and Branching Statements, Looping Statements, Labeled loops,Jumping Statements

SECTION-B

CLASSES, OBJECTS AND METHODS:-Introduction; Defining a Class; Adding Variables; Adding

Variables; Adding Methods; Creating Objects; Accessing ClassMembers; Constructors; Methods Overloading;

Static Members; Nesting of Methods;

Inheritance: Extending a Class; Overriding Methods; Final Variables and Methods; Final Classes; Finalizer

Methods; Abstract Methods and Classes; Visibility Control.

ARRAYS,STRINGSANDVECTORS: Arrays; Zagged Arrays:; Strings; String functions: Vectors; Wrapper

Classes.

INTERFACES: Introduction; Defining Interfaces; Extending Interfaces; Implementing Interfaces; Accessing

Interface Variables, Implementing Multiple Inheritence using Interfaces.

Page 3: Self Learning Material Programming in Java

PACKAGES: Introduction; SystemPackages; Using System Packages; Naming Conventions;

Creating Packages; Accessing a Package; Using a Package; Adding a Class to a Package; Hiding Classes.

SECTION-C MANAGING ERRORS AND EXCEPTIONS:- Introduction; Types of Errors; Exceptions; Exception

Handling using Try, Catch and Finally block: Throwing Our Own Exceptions; Using Exceptions for Debugging.

APPLET PROGRAMMING:- Introduction; How Applets Differ from Applications; Applet Life Cycle;

Creating an Executable Applet; Passing Parameters to Applets; Aligning the Display; More about HTMLTags;

Displaying Numerical Values; Getting Input from the User.

GRAPHICS PROGRAMMING:-Introduction;The Graphics Class; Lines and Rectangles; Circles and Ellipses; Drawing Arcs; Drawing Polygons; Line Graphs; Using Control Loops in Applets; Drawing Bar Charts.

SECTION–D

JAVA AWT: -Java AWT package Containers; Basic User Interface components; Layouts. EVENT HANDLING:- Event delegation Approach; Action Listener; AdjustmentListener, MouseListener;

MouseMotionListener; Window Listener; Key Listener; Item Listener

JAVA I/O HANDLING: I/O File Handling (InputStream & Output Streams, File Input Stream & File Output Stream, Data I/P and O/P Streams, File Class, Reader and Writer Streams, Random Access File).

SuggestedBook:

1. Programming InJava, E-Balagurusami, Fourth Edition,TataMcGraw Hill

2. MasteringJava, Second Edition, BPBPublications

3. AdvanceJava, Ivan Bayross, BPBPublications

Page 4: Self Learning Material Programming in Java

Table of Contents

ChapterNo. Title Written By Page No.

1. Fundamentals of Java

Mr. Hardeep Singh, BBK

DAV College, Amritsar

1

2. Java evolution Aarti, ACET Amritsar

13

3. Overview of Java Language Aarti, ACET Amritsar

33

4. Java building blocks Mr. Hardeep Singh, BBK

DAV College, Amritsar

54

5. Operators

Mr. Hardeep Singh, BBK

DAV College, Amritsar

69

6. Control structures – branching

Mr. Hardeep Singh, BBK

DAV College, Amritsar

84

7. Control structures – looping

Mr. Hardeep Singh, BBK

DAV College, Amritsar

99

8. Classes and wrapper classes

Mr. Hardeep Singh, BBK

DAV College, Amritsar

117

9.

Array, Vectors and string handling

Mr. Avtar Singh Sidhu, Guru

Gobind Singh Khalsa

College, Sarhali

143

10.

Interfaces

Mr. Avtar Singh Sidhu, Guru

Gobind Singh Khalsa

College, Sarhali

162

11.

Packages

Mr. Avtar Singh Sidhu, Guru

Gobind Singh Khalsa

College, Sarhali

182

12.

Exception handling

Mr. Avtar Singh Sidhu, Guru

Gobind Singh Khalsa

College, Sarhali

195

13.

Applet Programming

Mr. Avtar Singh Sidhu, Guru

Gobind Singh Khalsa

College, Sarhali

210

Page 5: Self Learning Material Programming in Java

14.

Graphic Programming

Mr. Rupesh Gupta, ACET

Amritsar

244

15.

Java AWT and Event Handling

Mr. Rajeev Kumar,

DAVIET, Jalandhar

258

16.

Java I/O Handling

Mr. Rajeev Kumar,

DAVIET, Jalandhar

291

Reviewed By Pankaj Deep Kaur, GNDU Regional Campus,

Jalandhar

©IK Gujral Punjab Technical University Jalandhar

Page 6: Self Learning Material Programming in Java

All rights reserved with IK Gujral Punjab Technical University Jalandhar

Page 7: Self Learning Material Programming in Java

1

BSBC-502

Programming in Java

Unit-I Lesson 1 Fundamentals of Java

Chapter Index

1.0 Objectives 1.1 Introduction 1.2 Introduction to Java

1.2.1 Features of Java

1.2.2 Relation between C, C++ and Java

1.2.3 Important Java Terminology

1.2.3.1 Bytecode

1.2.3.2 JDK

1.2.3.3 JVM

1.2.3.4 JRE

1.3 Object Oriented Paradigm

1.4 Basic Concepts of Object Oriented Programming

1.5 Benefits of OOP

1.6 Applications of OOP

1.7 Summary

1.8 Glossary

1.9 Answers to Check Your Progress / Self Assessment Questions

1.10 References / Suggested Readings

1.11 Model Questions

Page 8: Self Learning Material Programming in Java

2

1.0 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.

1.1 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.

1.2 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 applet can 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).

Page 9: Self Learning Material Programming in Java

3

Figure 1.1 a. James Gosling. 1. b Java Logo used by Sun Microsystems. 1.c Java logo

by Oracle

1.2.1 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 achieves this independence using its virtual machine called JVM (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.

3. 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.

4. 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.

5. 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.

Page 10: Self Learning Material Programming in Java

4

6. 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.

7. 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?

1.2.2 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?

Page 11: Self Learning Material Programming in Java

5

Que. 4.Outline major differences between C++ and Java?

1.2.3 Important Java Terminology:

These are some very common terms in Java. Let’s read about these.

1.2.3.1 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.

1.2.3.2 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)

1.2.3.3 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

Page 12: Self Learning Material Programming in Java

6

concentrate on developing software without worrying about how and where the software is to be

used finally.

1.2.3.4 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:

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

/* 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 !”) ;

}

}

Page 13: Self Learning Material Programming in Java

7

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?

1.3 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.

Page 14: Self Learning Material Programming in Java

8

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)

1.4 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.

Page 15: Self Learning Material Programming in Java

9

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.

1.5 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?

1.6 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.

Page 16: Self Learning Material Programming in Java

10

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)

1.7 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.

1.8 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.

Page 17: Self Learning Material Programming in Java

11

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.

1.9 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.

Page 18: Self Learning Material Programming in Java

12

Ans. 8.An array of String type.

Ans. 9.Data Abstraction, Inheritance, Polymorphism and Encapsulation.

Ans. 10.Inheritance.

1.10 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

1.11 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?

Page 19: Self Learning Material Programming in Java

13

BSBC-502

Programming in Java

Unit-I Lesson – 2 Java Evolution

Chapter Index

2.0 Objective

2.1 Overview

2.2 Java history

2.3 Java features

2.4 Java and Internet

2.5 Java and World Wide Web

2.6 Web Browser

2.6.1 Hardware and Software Requirements

2.7 Java Support Systems

2.8 Java Environment

2.9 Summary

2.10 Glossary

2.11 Answers to check your progress/ self assessment questions

2.12 References/Suggested readings

2.13 Model Questions

Page 20: Self Learning Material Programming in Java

14

2.0 Objective

After studying this lesson, student will be able to:

Understand the history of java

Understand the Java features

Learn the Java and WWW

Understand the Java environment

Understand the Java support systems

2.1 Overview

The release of initial version of java was short of revolutionary. Java evolved at an explosive

pace when most of the other software systems were settling into a format of small and

incremental updations. Java 1.1 was created by the designers immediately after the release of

java 1.0. Java 1.1added more significant features to Java 1.0 like many new library elements

that redefine the way of event handling by applets. Many features defined originally in java 1.0

are now obsolete. Java 1.1 adds and subtracts the attributes of its original identification. Java 2

was the next major release of java where “2” denotes second generation.

Java 2 creation was treated as a watershed event which indicates the java’s modern age

beginning. The version number 1.2 carried by the first release of java 2 which seems odd that

the 1.2 version number is used by the first release of java 2. The internal version number of the

Java libraries was originally referred as the reason. But to refer to the entire release it was

generalized. The repackaging of the java product as Java 2 Platform Standard Edition with java

2 is done by Sun. The version numbers began to be applied to that product. The support has

been added by java 2 for a number of new features like the Collections Framework and Swing.

Moreover, Java Virtual Machine and various programming tools have been enhanced by java 2

which also constitutes a few deprecation methods like suspend( ), resume( ), and stop( ). The

Thread class was the most important whose methods are affected. J2SE 1.3 was the next major

release of java. J2SE 1.3 was the first major upgrade to the original Java 2 release. The

development environment for the most part was tightened up and existing functionality was

added to it. Programs written for version 1.2 and version 1.3 are source-code compatible. It was

further enhanced by the release of J2SE 1.4. There were several important upgrades, additions

Page 21: Self Learning Material Programming in Java

15

and improvements in J2SE 1.4. For an instance, the new keywords assert, channel based I/O

subsystems and chained exceptions were added to the version 1.4. Also modifications were

made to the networking classes and collections of framework. Moreover, many small

modifications were made throughout. Nearly 100 percent source-code compatibility was

maintained with prior versions. Even though there were significant numbers of new features,

version 1.4. J2SE 5 is the latest release of Java.

2.2 Java history

JAVA is a new object oriented programming language and has its foundation in C++. With a

perfect fit in the Internet's multi-platformed environment, the next step from C++ was java. The

roots of java came from the portable electronic device industry which makes extremely portable

from one device to another device and platform to platform in case of Net. James Gosling has

written java programming language in June 1991 along with two other person ‘Mike Sheridan‘

and ‘Patrick Naughton‘ while working at Sun Microsystems. Java was named "Oak"

programming language. The implementation of virtual machine and a language which had

similar C-like notation but with greater uniformity and simplicity than C/C++ were the goals of

James Gosling. Java 1.0 was the first public implementation in 1995. The advantages include

security, allowing limited access for network and file. With free runtimes on popular platforms,

the promise was made of "Write Once, Run Anywhere". All the major web browsers

incorporated it into their standard configurations get popular quickly in a secure ‘applet’

configuration. With the advent of "Java 2", new versions for small and large platforms J2ME

and J2EE were designed soon. The famous software developer James Gosling has an

association with Sun Microsystems since 1984 developed java programming language in 1991.

He also developed many compilers and mail systems. It is a high level programming language

released in 1995 . It runs on various platforms like Windows, Mac OS, and different versions

of UNIX.

Page 22: Self Learning Material Programming in Java

16

Release date –January 23,1996

Originally called Oak

Release date – February 19,1997

Release date –December 8,1998

Codename = Playground

Release date –May 8,2000

Codename = Kestrel

Release date – February 6,2002

Codename = Merlin

Different versions

of java

Release date –September 30,2004

Codename = Tiger

Release date –December 11,2006

Codename = Mustang

Release date –July 28 ,2011

Codename = Dolphin

Release date –March 18 ,2014

Codenames have been discontinued ,

But the codename Spider is common

among java developers

2.3 Java features

Another name is java buzzwords. They are simple and easy to understand. They are as follows:

a) Object Oriented: JAVA is an object oriented programming language in which an object is

everything. As it is based on Object model so that it can be easily extended. The development

JDK 1.0

JDK 1.1

J2SE 1.2

J2SE 1.3

J2SE 1.4

J2SE 5.0

Java SE 6

Java SE 7/Java 7

Java SE 8/Java 8

Page 23: Self Learning Material Programming in Java

17

of small, modular and self contained units is enabled by the design. It allows 'plug-and-play'

feature, in which the distribution of reusable software components can easily takes place

across various platforms. A programming language which is object oriented in nature should

support a minimum of four characteristics as given below: Encapsulation – Encapsulation

in Java is a way of wrapping the data and code acting on the data, together as a single unit.

In encapsulation, the variables of a class will not be visible to other class. Also, it can be

accessed through the methods of their recent class. Hence , it is popularly known as data

hiding. It also implements modularity.

For achieving encapsulation in Java.

Declaration of the class variables as private.

Setter and getter methods are publically provided to modify and view the variables values.

b) Polymorphism – The capability of an object to take many forms is called polymorphism.

Polymorphism is most commonly used in OOPs when a parent class reference is used to

refer to a child class object. Any java object is said to be polymorphic if it can pass more

than one IS-A test in java.

c) Inheritance - It can be defined as the process where one class takes the properties of another.

Manageable information is made by using inheritance in a hierarchy form. The class who

acquires the properties of other class is known as subclass, derived or child class and the

class whose properties are inherited is known as super, base or parent class.

d) Dynamic binding - Without having to know the specific type at the time one writes the code.

One needs to be able to send messages to objects. While a program is executing, dynamic

binding gives maximum flexibility.

2. Platform independent: There are two types of platforms i.e. Software-based and hardware-

based. Software-based platform is provided by java which differs from most of the other

platforms. It runs on top of other hardware based platforms. It has two components which

are Runtime environment and Application programming interface. Java code can run on

multiple platforms like windows, linux, Sun solaris, Mac/OS etc. Compiler compiled the

java code and converts into bytecode. As it can run on multiple platforms so it is a platform

independent code i.e. Write Once and Run Anywhere.

Page 24: Self Learning Material Programming in Java

18

3 Simple and Small: Java designing is easy to learn and used effectively. To learn java,

understanding of the basic concepts of object-oriented programming is must which makes

learning easier. Java requires minimum training for programming. C++ is its base. Java has

a concise, cohesive set of features which makes it easy to learn and use. The development

tools are large in size and complexity requires powerful platform for development. But java's

components are comparatively very small in size.

4 Secure: JAVA is a secure language. Its secure feature enables tamper free systems and also

to develop virus-free. Java is secured because

Java program cannot harm other system

It provides a secure way of creating internet applications.

There is no explicit pointer.

It also provides a secure means to access web based applications.

Their programs run inside the virtual machine sandbox.

Class loader- adds security by separating the package.

Security manager

Bytecode verifier- It checks the code fragments for illegal code that can violate access right

to objects.

UU

Uses runtime environment of

Operating System

C++

application

Uses runtime

environment of its own

Java

application

OS

JVM

OS

Page 25: Self Learning Material Programming in Java

19

5 Architectural-neutral: There is no implementation dependent feature. JAVA is not fixed to a

specific machine or operating system architecture. The java Compiler generates an object file

which is architecture-neutral, 'generic' Bytecode instructions. They have nothing to do with

specific computer architecture. Java is independent of hardware i.e. machine independent.

6 Portable: Features like architectural-neutral and having no implementation dependent aspects

of the specification makes java portable. Java programs can be executed in any environment

for which there is a java run-time system JVM. It can run on any platform like linux, windows

and mac. It can be transferred over world wide web for e.g applets. A software application may

be a word-processor or spreadsheet which is written in java can run properly on any computer

or platform.

7 Robust: Error prone situations are eliminated by emphasizing runtime checking and compile

time error checking by java’s effort. Strongly typed, automatic garbage collection, no pointer

that avoids security problem and exception handling like unsafe constructs are eliminated by

it which encourages error-free programming. Java also uses strong memory management.

8 Multithreaded: Many tasks can be done simultaneously by this feature which makes possible

to write programs. Construction of smoothly running interactive applications is allowed by

developers. Application with multiple processes is built by it. Multithreading support the

efficient execution of programs. It is supported through inheritable thread class libraries.

Integrated support is provided by java for multithreaded programming.

9 Interpreted: Combination of compiled and interpreted language is a Java application. Cross-

platform code is supported by java through the use of java bytecode that can be interpreted by

java virtual machine on any platform. The source code is first compiled into bytecode that is

written by a programmer is common for all machines. Java Virtual Machine is termed as the

compatible Byte Code with the Java interpreter. The byte Code is converted by interpreter for

direct execution into specific machine code.

Page 26: Self Learning Material Programming in Java

20

10 High Performance: Java enables high performance using Just In Time compiler. Due to

closeness of byte code to native code, java becomes faster than traditional interpretation but

slower than a compiled language i.e. C++. Byte codes are highly optimized.

11 Distributed: Due to handling of Transmission Control Protocol /Internet Protocol, designing

with the distributed environment of the internet is done by it which can be transmitted and run

over internet.

12 Automatic memory management: JAVA garbage collector contains record of all the object

that are generated which frees the memory automatically that have no further use and it is used

by objects and also they are not referring to other existing objects.

13 Dynamic: Run-time information is carried out by java programs which is used for verification

and resolve the access to objects. Due to adaptation in an evolving environment, it is considered

dynamic. Their applications are always ready for execution, without any side-effects,

irrespective of modifications that may take place in those external components.

Check your progress/ Self assessment questions

Q1. What is a java?

Q2. What are the features of java?

Q3. Java was first developed in?

a) 1991 b) 1990 c) 1993 d) 1996

b) Java and Internet

The first application program which is written in java was Hot java so that Java has a strong

association with the internet. Delivery of small application programs by the Web documents

authors to anyone who browses the pages of the html documents is enabled by the Java

programming language. Animated cartoons, creation of game score boards, audio files and

video clippings can be executed by the page that makes them alive. With this, it also changed

Page 27: Self Learning Material Programming in Java

21

the way of working of Internet and WWW which allows architecturally neutral compiled code

to be dynamically loaded in the network of heterogeneous systems from anywhere.

The twin staples of computing data and programs with Java are not needed to be stored on

computer. It can reside on the internet anywhere, so that it can be called up by whosoever and

whenever needs them.

The World Wide Web introduced many users to the internet world. But most of the web pages

are static as their book or magazine counterparts. To supply video and sound, the web is

technically equipped. For this the user required to have the correct software to make proper

use of them.

Server 2 Solaris

Client 2

Windows XP

Desktop

Server 1

Linux

Server 3

Windows

Internet Clie

nt

3

An

dro

id

Mo

bile

Client 1

Windows 7

Laptop

Client 4

Mac

Tablet PC

Page 28: Self Learning Material Programming in Java

22

Java comes to the front with the help of Internet. In turn, Internet is affected by java with good

effects. The universe of objects is expanded by java which move freely in cyberspace is the

main reason. Transmission between the server and personal computer takes place by two

categories of objects in a network. The two broad categories are passive and dynamic

information, active programs. Reading an e-mail is an example of viewing passive data. While

downloading, the program’s code is passive data until it is not executed. A dynamic, self-

executing program is a second type of object which can be transmitted to computer. But this

type of program behaves like an active agent on the client computer and initiated by the server.

To display the data properly, a program is provided by the server which the server is sending.

The Java run-time system is implemented by the Web browser which can incorporate Java

applets as executable content. Web pages cannot contain only static hypertext information.

But it can contain full-fledged interactive applications. The potential required in using the

world wide web is large. A user can retrieve and simply use the software by web browser

navigation. Static information can be paired with portable software for interpretation and using

the information. Java influenced Internet by simplifying the web programming and inventing

applets. Applets expanded the scope of internet. Java also addressed two other important

issues of internet, which are security and portability.

Java Applets

A special type of program which is designed to transmit over the internet. It is automatically

executed by a java compatible web browser. On demand it is downloaded, like an image,

video clip or sound file. It is an intelligent program that reacts to user input and changed

dynamically without running the same animation or sound effects again and again. To

generate the dynamic content, it is embedded in the webpage. It works at client side and runs

inside the browser.

Page 29: Self Learning Material Programming in Java

23

Advantages of applet :

There are many advantages of applet which are as follows:

Less response time as it works at client side.

Secure

It can be executed by browsers running on many platforms which include linux,

windows, mac os etc.

Disadvantage of applet :

Plugin is needed at client browser for execution.

Figure 2.1 Downloading of applets via internet

c) Java and world wide web

World Wide Web is an open ended information retrieval system which is designed to use in

the Internet's distributed environment. It contains web pages which are created by using

HTML. It provides both information and controls. The web system is open ended which is

used to navigate a new document in any direction, unlike a menu driven system in which a

decision tree is used to guide to a particular direction. Web pages contain HTML tags that

Page 30: Self Learning Material Programming in Java

24

enable us to find, retrieve, manipulate and display documents worldwide. Java was meant to

be used in distributed environments such as Internet. Since, both the Web and Java share the

same philosophy, Java could be easily incorporated into the Web system. Before Java, the

World Wide Web was limited to the display of still images and texts. However, the

incorporation of Java into Web pages has made it capable of supporting animation, graphics,

games, and a wide range of special effects.

Figure 2.2 Java’s interaction with the web

d) Web Browser

1. Hardware and Software Requirements

Following is the list of requirements that must be met before installing the Sun Java

System.

Application Server Platform Edition 8.2 product.

Platform is Required

Page 31: Self Learning Material Programming in Java

25

Support of System Virtualization

Patch Information is important

JDBC Databases and Drivers

Use of Bundled Derby Database

Web Browser

Up gradation of the Sun Java System Application Server

Platform Requirements

The following table lists the operating systems which are supported by Sun Java System.

Operating system Minimu

m

Memory

Recommend

ed Memory

Minimu

m Disk

Space

Recommend

ed Disk

Space

JVM

Sun Solaris

9,10(SPARC),

Solaris 9,10(x86)

512 MB 512 MB 250 MB

Free

500 MB Free J2SE

1.4.2_10,J2

Se 5_06

Sun Java Desktop

System

512 MB 1 GB 250 MB Free

500 MB Free J2SE 1.4.2_10

Redhat Enterprise

Linux 3.0 U1,4.0

512 MB 1 GB 250 MB Free

500 MB Free J2SE 1.4.2_10

Windows Server

2000 SP4+

Windows 2000

Advanced Server

SP4+

Windows Server

2003

Windows XP Pro

SP1+

1 GB 2 GB 500 MB

Free

1 GB Free J2SE

1.4.2_10,J2

Se 5_06

Support of System Virtualization

It is a technology which allows the execution of multiple operating system instances

independently on shared hardware. Software deployed to an operating System is generally

Page 32: Self Learning Material Programming in Java

26

unaware applied in a virtualized environment which underlying that the platform has been

virtualized.

JDBC Databases and Drivers

JDBC Vendor JDBC Driver

Type

Supported Database Server

i-net Software Type 4 Oracle (R) 8.1.7,9i, 9.2.0.3+,10.1.x ,

10.2.x Sybase ASE 12.5

Microsoft SQL Server 2000 4.0 Service

Pack 1

IBM Type 2 IBM DB2 8.1 Service Pack 3+

Derby Type 4 Apache Derby 10.1.2.1

PointBase Type 4 PointBase Network Server 5.2

MySQL Type 4 5.x

DataDirect Type 4 Oracle (R) 8.1.7,9i, 9.2.0.3+,10.1.x ,

10.2.x Sybase ASE 12.5.2

Microsoft SQL Server

IBM DB2 8.1 Service Pack 3+

Oracle Type 4 , Type 2 Oracle (R) 9.2.0.3+, 10.1.x,10.2.x

Use of Bundled Derby Database

Instructions for using the Derby database implementation are :

Start and Stop of the Derby Database

Utility Scripts of Derby

Export of Tables from Point base to Derby

Browsers

Browser Version Mozilla 1.4,1.5,1.6,1.7x

Netscape Navigator 6.2,7.0 Internet Explorer 5.5 Service Pack 2,6.0

Firefox 1.x

Page 33: Self Learning Material Programming in Java

27

e) Java Support Systems

It includes :

Applets : Applets are usually small programs and these helped in moving some user

interactive programs from server to client, hence improving the usability of the web

application. It is automatically executed by the Java-compatible web browser. The typical

examples of applets are tax calculator or some forms with input fields having lots of

interaction between them. Applets are designed to be embedded within an HTML page. It is

a Java class which extends the java.applet.Applet class. An applet class will not define

main() method . A main () method is not invoked by an applet.

Servlets : It is contained by java which are useful in dynamically extending the functionality

of web browser. With Servlets, both sides of client server system are spanned by the Java.

They can be used to generate web content dynamically. The information stored in database

tables can be retrieved and shown as a web page on a browser. Typically, this involves

reading the database tables using JDBC and converting them into formatted HTML and

sending it to the browser for display. For example, depending upon the user search request,

the matching items from the catalog are shown along with the prices and their availability.

Most of the web page is constructed dynamically and has details for a specific user search

request. Servlets like all Java programs are portable and can run on any server that supports

JVM and has a servlet container. e.g., They can run on IBM Websphere, Tomcat or Web

Logic.

Page 34: Self Learning Material Programming in Java

28

Java Beans EJB JSP XML SOAP CORBA

Check your progress/ Self assessment questions

Q4. What is web?

Q5. Which command is used to compile a java program ?

a) java b) javad

c) javac d).javadoc

Q6. What are servlets ?

f) Java Environment

Java environment includes a large number of development tools and hundreds of classes and

methods. The development tools are part of the system known as java development kit and the

classes and methods are part of the Java standard library also known as the application

programming interface. The creation of java environment is supported by the compiler class in

which java byte code is compiled into executable code rather than interpreted. It is not for

normal programming use.

Java Development Kit : It is a program development environment for writing java applets and

applications.It comes with a collection of tools that are used for developing and running java

programs It consists of a runtime environment that ‘sits on top’ of the operating system layer

Page 35: Self Learning Material Programming in Java

29

as well as the tools and programming that developers need to compile, debug, and run applets

and applications written in the java language. javaprof - Java profiler

Tool Description

appletviewer Enables us to run Java applets.

java Java interpreter, which runs applets and

application by reading and interpreting

bytecode files.

javac The java compiler, which translates java

sourcecode to bytecode files that the interpreter

can understand.

javadoc Creates HTML-format documentation from

java source code files.

javah Produces header files for use with native

methods.

javap Java disassembler ,which enables us to convert

bytecode files into a program description.

jdb Java debugger, which helps us to find errors in

our programs

Java development tools

Application Programming Interface

In java, an application programming interface is a collection of prewritten packages, classes and

interfaces with their methods, constructors and fields. It facilitates interaction between humans

and computers which is similar to a user interface. An application programming interface treated

Page 36: Self Learning Material Programming in Java

30

as an interface for software program which facilitates the interaction. Most of the basic

programming tasks in java are performed by the application programming interface packages and

classes helps to minimize the number of lines which is written within piece of code.

JDK consists of three basic components. They are as follows:

Java compiler

Java Virtual Machine

Java Application Programming Interface

The Java Application Programming Interface with Java Development Kit shows each component

function. Many of these components are commonly used and pre-created in Java programming.

Prewritten code is applied via the Java Application Programming Interface by the programmer.

The necessary code classes and packages for implementation can be easily invoked by the

programmer after referring the available Application Programming Interface classes and packages.

The API is a library of available packages, java classes and interfaces. The three Application

Programming Interface types are as follows:

Official Java core Application Programming Interface, which is bundled with the Java

Development Kit download.

Optional official Java Application Programming Interface’s, which may be downloaded if

needed

Unofficial Application Programming Interfaces , which are third-party APIs that can be

downloaded from source websites

To determine package functions or class, parameters and other necessary information, the

Application Programming Interfaces help the programmers. The official API which includes

packages is graphics, Applet packages, input/output packages, GUI swing packages and Abstract

Windows Toolkit.

g) Summary

A brief history of java and its features are discussed in it. A derivative of C and C++ language

is a java. It is simple, fewer complex features and familiar syntax. With the help of web

browsers, it can be incorporated into the WWW system. There number of characteristics

makes it compatible for internet programming. To implement java programs, various tools

and environment is required.

Page 37: Self Learning Material Programming in Java

31

h) Glossary

Applet: Applets are usually small programs and these helped in moving some user interactive

programs from server to client.

Java : A high-level programming language which is developed by Sun Microsystems.

Java Development Kit: It is a collection of tools which are used to develop and run java

programs.

Multithreaded: Possibility of writing the programs which can perform many tasks

simultaneously is through it.

Servlets : Servlets are useful in dynamically extending the functionality of web browser.

Web : It is an open-ended information retrieval system designed for usage in the internet wide

distributed system.

i) Answers to check your progress/ self assessment questions

1. JAVA is a new object oriented programming language and has its foundation in C++.

2. They are as follows:

Object Oriented

Platform independent

Simple

Secure

Architectural-neutral

Portable

Robust

Multithreaded

Interpreted

3. a)

4. It is an open-ended information retrieval system designed for usage in the Internet wide

distributed system. It contains web pages which are created by using HTML which

provides information and controls.

5. c)

Page 38: Self Learning Material Programming in Java

32

6. Servlets can be used to dynamically generate web content. The information stored in

database tables can be retrieved and shown as a web page on a browser.

2.12 References/Suggested readings

1. Java Network Programming, Elliotte Rusty Harold, 4th Edition

2. Programming with Java: A Primer, Balagurusamy, Tata Mcgraw Hill, New Delhi, India

3. Introduction to Java Programming, Y. Daniel Liang, Prentice Hall

2.13 Model Questions

Q1.What is java? Discuss its history.

Q2. Explain various java features in detail.

Q3. What are the various java support systems?

Q4. Explain java and internet in detail.

Q5. Discuss java environment.

Page 39: Self Learning Material Programming in Java

33

BSBC-502

Programming in Java

Unit-I Lesson – 3 Overview of Java Language

Chapter Index

3.0 Objective

3.1 Introduction

3.2 Simple Java Program

3.3 Comments in Java

3.4 An Application with two classes

3.5 Java Program Structure

3.5.1 Java tokens

3.5.2 Java Statements

3.5.3 Implementing a Java Program

3.6 Java Virtual Machine

3.7 Command Line Arguments

3.8 Programming Style

3.9 Summary

3.10 Glossary

3.11 Answers to check your progress/ Self assessment questions

3.12 References/ Suggested readings

3.13 Model Questions

Page 40: Self Learning Material Programming in Java

34

3.0 Objective

After studying this lesson, student will be able to:

Understand the basics of java

Understand the Java Program Structure

Learn the programming style of java

Understand the Java virtual machine

Understand the command line arguments

3.1 Introduction

Java is a multithreaded object-oriented programming language. It was developed by Sun

Microsystems. It is a new programming language with complete functionality like that of C++. To

view Java applets on the Net, a Java-compliant browser is required. It supports two most prominent

browsers on the internet supported by java are Internet Explorer (as of version 3.0) and Netscape

Navigator (as of version 2.0). Java is platform independent, general purpose, architecturally

neutral, distributed, portable and dynamic programming language.

3.2 Simple Java Program

Syntax of a java Program:

Definition of a java program is done by a public class whose format is as follows:

public class program-name

{

optional variable declarations and methods

public static void main(String[] args)

{

statements

}

optional variable declarations and methods

}

Let’s understand a “simple “ java program example

Page 41: Self Learning Material Programming in Java

35

A java program file is created using text editor like Notepad ,vi and is saved with name simple.java.

The contents of the java file are as below:

import java.io.*;

class simple

{

public static void main (String args[])

{

System.out.println("Hello World");

}

}

The above given program illustrates the text type output function of the Java programming

language. It displays “Hello world". Matching the name of file with the name of class is expected

by the Java compiler.

Compiling a java program

For compiling the Java code, the 'javac' tool is used. The command used to compile the java

program is:

javac simple.java which operates from a command line. Shell's path contains the tool to the

program. The path can be specified explicitly like c:\j2se\bin\javac simple.java for compiling the

java code. When compilation is done, it will be ended and returned to a command prompt. In

directory, there will be a compiled version of the program in .class file extension. Once a program

is available in this form, it is ready to run. Then checking is done to find about the creation of a

class file takes place or not. If it is not, or an error message is received then check for typing error

in code. After all these, a java program is ready to run.

To run the program, java command is required: java simple.

Page 42: Self Learning Material Programming in Java

36

Running a java program

Hello world

During compilation, full name with extension is used . While running a program, only class

name is used.

Compiling/Executing a java program

3.3 Comments in Java

They are non executable type of statements for the programmers. It contains information

about the java code. Three types of comments are supported by the java programming

language.

Their types are as follows:

a) Single line comment

b) Multi line comment

c) Documentation comment

a) Single line comment

Only one line is allowed in it. It begins with double slash i.e. ‘//’. Compiler ignores everything

from the occurrence of // to the end of the line.

Syntax: // text

Eg : int i=5; // Set the value of i variable to 5

Page 43: Self Learning Material Programming in Java

37

b) Multi line comment

It is used when comment spans across more than one line. It starts with /* and ends with */.

The compiler ignores everything from /* to */.

Syntax: /* text */

Begins with slash-asterisk (/*) then the commented text and ends with asterisk-slash (*/) .

Eg : /*

Set the value of j variable to 3

*/

int j=3;

3. Documentation comment

Documents are generated automatically in it. It starts with /** and ends with */.

Syntax: /** documentation */

It indicates a documentation comment. This kind of comments are ignored by the compiler,

just like it ignores comment that use /* and */. When automatically generated documentation

is prepared then it is used by javadoc tool.

Eg : /**

Initialization of variable

*/

int p=2;

Slash-double asterisk (/**) & and asterisk-slash(*/) is matched for Javadoc automatic

hypertext documentation, as in. /**..*/ comment style is used by the javadoc, when it

produces hypertext pages for the description of a class.

3.4 An Application with two classes

The following is a java program file named as Box.java which contains two classes.

public class Box

{

public static void main(String[] args)

{

Square jack; jack = new Square();

jack.side = 6; System.out.printf("Area of jack is %d%n", jack.area());

Page 44: Self Learning Material Programming in Java

38

}

}

class Square

{

public int side;

public int area()

{

return this.side*this.side;

}

}

3.5 Java Program Structure

It consists of different sections. Some sections are mandatory but some are optional. The

optional section depends upon the requirements of the programmer which can be excluded from

the program.

Documentation Section Suggested

Package Statement Optional

Import Statements Optional

Interface Statements Optional

Class Definitions Optional

Main Method Class

{ Essential

Main Method Definition

}

class Classname

{

public static void main (String[] arguments)

{

Statements

} }

Page 45: Self Learning Material Programming in Java

39

Documentation Section

This section contains the comments that describe the purpose of the program, author name, date

and time when a program is created. Program readability is improved by it. A non-executable

statement that helps to read and understand a program is a comment . It is simply a message

that exists only for the programmer. It is ignored by the compiler. This section is optional and

comments may appear anywhere in the program.

Java programming language supports three types of comments.

Single line (or end-of line) comment: It starts with a double slash symbol (//) and terminates

at the end of the current line. The compiler ignores everything from // to the end of the line.

For example: // Calculate sum of two numbers

Multiline Comment: Java programmer can use C/C++ comment style that begins with

delimiter /* and ends with */.All the text written between the delimiter is ignored by the

compiler. This style of comments can be used on part of a line, a whole line or more commonly

to define multi-line comment.

For example : /*calculate sum of two numbers */

Comments cannot be nested.

For example : /* x = y /* initial value */ + z; */ is wrong.

Documentation comments: This comment style is new in Java. Such comments begin with

delimiter /** and end with */. The compiler also ignores this type of comments just like it

ignores comments that use / * and */. The main purpose is to automatically generate program

documentation. The java doc tool reads these comments and uses them to prepare your

program's documentation in HTML format.

For example: /**The text enclosed here will be part of program documentation */

Package Statement

It includes a statement that provides a package declaration. Java allows to group classes in a

collection known as package. It must appear as the first statement in the source code file before

any class or interface declaration. This statement is optional.

Page 46: Self Learning Material Programming in Java

40

For example: Suppose you write the following package declaration as the first statement in the

source code file.

package employee;

This statement declares that all classes and interfaces defined in this source file are part of the

employee package. Only one package declaration can appear in the source file.

Import statement

It includes statements which are used for referring classes and interfaces that are declared in

other packages. The import statement is written after a package statement but before any class

definition. You can import a specific class or all the classes of the package. Java contains many

predefined classes that are stored into packages. In order to refer these standard predefined

classes in your program, use of fully qualified name is needed. (i.e. Packagename.className).

But this is a very tedious task as one need to retype the package path name along with the

classname. So a better alternative is to use an import statement.

For example : If you want to import Day class of java.util package using import statement then

write

import java.util.Day;

Use of simple classname Day rather than fully qualified classname java.util.Day is allowed to

the programmer by this statement. Specification of more than one import statement is allowed

in a program.

For eg:

import java.util.Day;

import java.applet.*;

Interface Section

It is similar to a class which includes constants, method declaration. It specifies the interfaces.

Interfaces cannot be instantiated. They can only be implemented by classes or extended by other

interfaces. It is an optional section and is used when we wish to implement multiple inheritance

feature in the program.

interface stack

{

Page 47: Self Learning Material Programming in Java

41

void push(int item); // Insert item into stack

int pop(); // Delete an item from stack

}

Class Section

Information is described about user- defined classes which is available in the program. A

collection of methods and data variables which operate on the data variables is known as class.

A Java program consists of at least one class definition. Main method is declared by this class

definition. A program execution starts from the main () method and the statements are followed

in the order specified. Creation of objects, evaluation of expressions and invoking of other

methods can be done by the main method. The program is terminated at the end of main and

control is passed back to the operating system. This section is compulsory.

// Program to print message on the screen

class Hello

{

public static void main (String args[])

{

System.out.println("Hello Java");

} }

3.5.1 Java tokens

Collection of methods and classes made a java program. Methods are the container of the

various statements. A Statement is made up of operators, variables, constants etc. Tokens

are the elements of java program identified by the compiler. It is the smallest element of a

program which has some useful meaning to the compiler. Variables, constants, keywords,

special characters, operations are the tokens which is supported in java.

Page 48: Self Learning Material Programming in Java

42

The text of source code is scanned by the compiler and individual tokens are extracted

during compilation. When tokenizing is performed on the source file then the compiler

recognized and subsequently removed whitespaces and the text which is enclosed within

comments.

Eg :

//Print Hello Java

public class HelloJava

{

public static void main (String args[])

{

System.out.println(“Hello Java”);

} }

Tokens such as public, class, HelloJava , {, public, static, void, main, (, String, [], args, {,

System, out, println, (, "Hello Java", }, } are contained by the source code. Java byte codes

are the compiled form of the resulting tokens that is capable to run from an interpreted java

environment. Tokens are useful in detecting errors for compiler. Generation of an error

message will take place by compiler, when tokens are not arranged in a particular sequence.

When all characters are grouped into symbols in a java program, they are known as tokens.

Language features are built from these tokens. Smallest unit of program is the token.

Different types of tokens in java are:

1) Keywords: names already available in the programming language. These java tokens

have predefined meaning. Java consists of 50 keywords like break, int, class, continue

etc.

Page 49: Self Learning Material Programming in Java

43

2) Identifier: name chosen by the programmer. These java tokens are designed and

decided by the java programmer. They are used for class names, method names, and

variable names. It may be any descriptive sequence of uppercase and lowercase letters,

numbers, or the underscore and dollar-sign characters. Eg of identifiers are: class name,

temporary variables in class methods and members name of the class.

3) Literals: They are java tokens specified by their type consists a set of characters. They

are used to represent a constant. Variable is used for storage purpose.

Example: 12, 4,3.6,”shyam”,’p’ etc.

4) Operators: symbols that operate on arguments and produce results. Operators are java

tokens containing a special symbol and predefined meaning in Java. Operators can be used

with one or more operands to achieve a result. Eg unary,binary,ternary operators.

Java operators can be divided into the following groups:

a) Arithmetic Operators: They are used in mathematical expressions in the same way

that they are used in algebra. E.g. +,-,*,/ ,%, ++, -.

b) Relational Operators: There are following relational operators supported by Java

language à ==, !=, <=, >=, < ,>.

c) Bitwise Operators: Java defines several bitwise operators, which can be applied to the

integer types, long, int, short, char, and byte. It works on bits and performs bit-by-bit

operation.

d) Logical Operators: The following are the logical operators: &&, ||, !.

e) Assignment Operators: There are following assignment operators supported by Java

language: +=, =, *=, /+, -=,%=.

f) Misc Operators:

i. Conditional Operator ( ? : ): It is also known as the ternary operator. This operator

consists of three operands and is used to evaluate Boolean expressions. The goal of

the operator is to decide which value should be assigned to the variable.

Page 50: Self Learning Material Programming in Java

44

ii. Instance of Operator: It is used only for object reference variables. The operator

checks whether the object is of a particular type(class type or interface type).

5) Separators (also known as punctuators): punctuation characters and paired-delimiters.

The most commonly used separator in Java is the semicolon.

3.5.2 Java Statements

The statements in java are like sentences in natural languages. It is an executable

combination of tokens ending with a semicolon mark. They are usually executed in

sequence in the order in which they appear.

Package Statement

It provides a package declaration. Grouping of classes in a collection is allowed by java

known as package. Before any class or interface declaration, it can be appeared as the first

statement in the source code file. It is optional.

For example: Package declaration as the first statement in the source code file.

package department;

The interfaces and classes which are defined in this source file are part of the department

package declared by the above statement. A single package declaration is allowed in the

source file.

Import Statement

It is used for referring interfaces and classes which is declared in other packages. Predefined

classes are stored into packages which are contained by java. To refer to these predefined

classes fully qualified name is required to be used in a program. Instead of retyping the

package path name with the classname its better to use an import statement. It is used for

Page 51: Self Learning Material Programming in Java

45

referring classes which are declared in other packages. It is written before any class definition

but after a package statement. A specific class or all the classes of the package can be

imported.

For eg : Import statement is used to import Day class of java.util package.

import java.util.Day;

The above statement allows the programmer to use the simple classname Day rather than

fully qualified classname java.util.Day in the code.

More than one import statement can be specified in a program.

For example:

Import java.util.Day;

import java.applet.*;

Some other java Statements are:

3.5.3 Implementing a Java Program

It involves a series of steps which includes

Page 52: Self Learning Material Programming in Java

46

Creation of program

Compilation of program

Running of program

Creation of program

class Abc

{ public static void main(String args [ ])

{

System.out.println(" hi");

System.out.println(" welcome");

}

}

Compilation of program

For compiling the Java code, the 'javac' tool is used. The command used to compile the

java program is:

javac Abc.java which operates from a command line.

When compilation is done, it will be ended and returned to a command prompt. In

directory, there will be a compiled version of the program in .class file extension i.e

Abc.class containing the bytecodes of the program. Once a program is available in this

form, it is ready to run.

Running of program

While running a program, only class name is used. Type Abc on command prompt. On

execution it will displays the following

hi

Page 53: Self Learning Material Programming in Java

47

welcome

Check your progress/ Self assessment questions

Q1. What are comments in a java ?

Q2. What are java tokens ?

Q3. Command to execute a compiled java program is

a) execute b) javac c) java d) run

3.6 Java Virtual Machine

It is an abstract machine. Java Virtual Machine is a specification which provides runtime

environment for the execution of java byte code to take place. Many hardware and software

platforms are available for them. Configuration of each OS is different so Java Run time

Environment, Java Virtual Machine and Java Development Kit are platform dependent. Java is

platform independent. It acts as an interpreter for the byte code, which takes the byte codes as

input and executes as if it was a physical process executing machine code. It is a component of

the Java system which helps in execution and interpretation of the instructions in class files.

One heap, one method area and one or more stacks i.e. one for each thread is contained by each

instance of the Java Virtual Machine.

It performs following main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment

Java Virtual Machine is:

1. A specification: Working of JVM is specified by a specification. Selection of an algorithm

is done independently by implementation provider. Sun and other companies provide its

implementation.

2. An implementation: Its implementation is known as Java Runtime Environment.

3. Runtime Instance: An instance of JVM is created to write java command to run the java

class on the command prompt.

Page 54: Self Learning Material Programming in Java

48

Internal Architecture of JVM

1) Class loader: Class loader is a subsystem of Java Virtual Machine which is used in loading

class files.

2) Class Area: Per-class structures like field, runtime constant pool, code for methods and

method data is stored by it.

3) Heap: Objects are allocated in the runtime data area i.e. Heap.

4) Stack: Frames are stored in it which holds partial results and local variables. It also plays a

part in method invocation and return. Each thread has a private java virtual machine stack which

is created at the thread time. Whenever a method is invoked, a new frame is created. On

completion of method invocation, a frame is destroyed.

5) Program Counter Register: The address of the currently executed java virtual machine

instruction is contained by it.

6) Native Method Stack: All native methods are contained by java virtual machine which is

used in the application.

7) Execution Engine: It contains a virtual processor, an interpreter which read byte code stream

and then execute the instructions, Just-In-Time compiler which is used to improve the

performance. The parts of the byte code that have similar functionality are compiled by it.

3.7 Command Line Arguments

Page 55: Self Learning Material Programming in Java

49

It is an argument which is passed during the run time of the java program. Console receives the

arguments passed in the java program which can be used as an input. With this, the behaviour

of the program can be checked conveniently for the different values. Numbers of arguments

can be passed like N (1,2,3) from the command prompt.

Eg : One argument is required to be passed from the command prompt to run the java program.

class CL

{

public static void main(String args[])

{

System.out.println ("First argument is: "+args[0]);

}

}

compile by > javac CL.java

run by > java CL abc

Output: First argument is: abc

Check your progress/ Self assessment questions

Q4. What are command line arguments?

Q5. Java uses __ to represent characters.

b) Byte code b) ASCII c) Unicode d) None of the above

Q6. What is java virtual machine?

3.8 Programming Style

For consistency, maintenance and easy reading, a map is given for the code generated by a

group of programmers.

Page 56: Self Learning Material Programming in Java

50

1. Formatting

1.1 Indentation: It can be done with the help of spaces. Tabs are not used for it. In

structure, braces always line up vertically for matching in the same column.

1.2

1.2 Spacing: Space on either side is available in binary operators. In case of unary

operators should be operands immediately precede or follow. Whitespace follow commas

and semicolons. With no spaces, casts are written. The keywords like for, while, if, switch,

and catch can be followed by a space.

1.3 Class Member Ordering

class Order

{

// fields

// constructors

// methods

}

1.4 Maximum Line Length : Making of lines longer than 120 characters is avoided in it.

1.5 Parentheses: Expressions use parentheses to specify order of precedence. It is also used

for simplification of an expression.

2 Identifiers:

Letters 'A' - 'Z' and 'a' - 'z' and numbers '0' - '9' are used for it. Dollar signs, underscores or

non-ascii

characters are not used as identifiers.

Page 57: Self Learning Material Programming in Java

51

2.1 - Classes and Interfaces

Mixed case will use interface and class identifiers. Uppercase is required for each word in

the name which includes the first letter of the name. Lowercase is required for rest of the

other letters. But acronym will be all in upper case.

2.2 - Packages

Lower case characters are used for their names. Length should be under eight characters.

Multi-word is avoided for package names.

2.3 - All Other Identifiers

It includes methods, fields, parameters and local variables. It will use the following

naming convention. It includes identifiers used for constants. Uppercase is required for

each word in the name except the first letter of the name. Lowercase is required for rest

of the other letters. But embedded acronym will be all in upper case.

3 Coding

3.1 Constructs to Avoid

Use of do..while

Use of return in the middle of a method

Use of continue

Use of break other than in a switch statement

3.2 Do Not Compound Increment Or Decrement Operators

Separate line is used for an increment or decrement

Avoid using pre-increment or pre-decrement

3.3 Initialization

Declaration of variables as close as possible to where they are

used.

Page 58: Self Learning Material Programming in Java

52

3.4 Access

All fields must be private, except for some constants.

3.9 Summary

Java is a programming language used to develop software applications as well as applets that

run on webpages. Java program has first statement as package statement. It is a general

purpose, class based, platform independent, portable, architecturally neutral, dynamic,

distributed, portable and robust interpreted programming language. Java is very flexible. One

Java file can have multiple classes declared in it but there is only one public class which should

be same as file name. Java class can have instance variable such as methods, instance variable.

3.10 Glossary

Java- It is a multithreaded object-oriented programming language developed by Sun

Microsystems.

Java Virtual Machine – It is a specification that provides runtime environment in which the

execution of java bytecode can takes place.

Tokens – It is the smallest element of a program that is meaningful to the compiler.

Command Line Argument - It is an argument i.e. passed at the time of running the java

program. The arguments passed from the console can be received in the java program and it

can be used as an input.

Package Statement: It includes statement that provides a package declaration. Java allows to

group classes in a collection known as package

3.11 Answers to check your progress/ self assessment questions

1. They are non executable type of statements for the programmers. It is an explanation of

the statement. Three types of comments are supported by the java programming language.

Their types are as follows:

a) Single line comment

b) Multi line comment

c) Documentation comment

Page 59: Self Learning Material Programming in Java

53

2. Tokens are the elements of java program identified by the compiler. It is the smallest

element of a program which has some useful meaning to the compiler. Variables, constants,

keywords, special characters, operations are the tokens which is supported in java.

3. c)

4. It is an argument which is passed during the run time of the java program. Console receives

the arguments passed in the java program which can be used as an input.

5. c)

6. It is an abstract machine. Java Virtual Machine is a specification which provides runtime

environment

for the execution of java byte code to take place. Many hardware and software platforms

are available

for them.

3.12 References/Suggested readings

1. The Java Language Specification, Java SE 8 Edition, James Gosling, Bill Joy, Guy L. Steele

Jr., Gilad

Bracha, Alex Buckley

2. Java Programming, Joyce Farrell, 8th Edition.

3. The Java Programming Language, Ken Arnold, David Holmes, 3rd Edition.

3.13 Model Questions

Q1. Discuss java program structure.

Q2. Explain an application with two classes.

Q3. What are the various java statements? Explain.

Q4. Explain the programming style of java.

Q5. What is command line argument? Explain.

BSBC-502

Programming in Java

Page 60: Self Learning Material Programming in Java

54

Unit-1 Lesson-4 Java Building Blocks

Chapter Index

4.0 Objectives

4.1 Introduction

4.2 Java Differs from C and C++

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

4.4 Data types

4.5 Constants

4.6 Variables and Scope of variables

4.7 Operators

4.8 Expressions

4.9 Flow Control statements

4.10 Summary

4.11 Glossary

4.12 Answers to Check Your Progress / Self Assessment Questions

4.13 References / Suggested Readings

4.14 Model Questions

4.0 Objectives

To know the differences between C++ and Java.

Page 61: Self Learning Material Programming in Java

55

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.

4.1 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.

4.2 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.

Page 62: Self Learning Material Programming in Java

56

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.

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 multi-

dimensional 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.

Page 63: Self Learning Material Programming in Java

57

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?

4.3 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

Page 64: Self Learning Material Programming in Java

58

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.

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.

Page 65: Self Learning Material Programming in Java

59

Java Separators

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.

4.4 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 4.1: Java data types

Primitive Data types

Page 66: Self Learning Material Programming in Java

60

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 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

Page 67: Self Learning Material Programming in Java

61

is 15 digits after decimal. Examples of use of double data type are : radius of earth in

inches, area of a nano organism etc.

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?

4.5 Constants

Page 68: Self Learning Material Programming in Java

62

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.

4.6 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, that’s 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.

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.

Page 69: Self Learning Material Programming in Java

63

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?

4.8 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 created using only arithmetic operations and operands. For

example, num1+num * 5.

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.

Page 70: Self Learning Material Programming in Java

64

4.9 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 4.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 are the three types of flow control statements?

Ques12. Array is _____________ data type in Java

a. boolean

b. numeric

c. integral

d. non-primitive

Page 71: Self Learning Material Programming in Java

65

Ques 13. A char in Java is used to represent ________________ character

a. 16-bit unsigned Unicode

b. 32-bit unsigned Unicode

c. 64-bit unsigned Unicode

Ques 14. An array is an collection of _________________ data elements in memory.

a. spaced

b. contiguous

c. sparse

Ques 15. An expression is a combination of

a. operands

b. operators

c. operands and operators

4.10 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.

Page 72: Self Learning Material Programming in Java

66

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.

A special type of statements called flow control statements are used to control the flow of

execution of a program.

4.11 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.

4.12 Answers to Check Your Progress / Self Assessment Questions

Ans 1.C++ uses preprocessor directives #include, and java uses import statement.

Page 73: Self Learning Material Programming in Java

67

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

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.

Ans 12. d

Ans 13. a

Ans 14. b

Ans 15. c

4.13 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

Page 74: Self Learning Material Programming in Java

68

4.14 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?

Page 75: Self Learning Material Programming in Java

69

BSBC - 502

Programming in Java

Unit-2 Lesson-5 Operators

Chapter Index

5.0 Objectives

5.1 Introduction

5.2 Operators, Operands and Expressions

5.3 Unary, Binary and Ternary Operators

5.4 Precedence and Associativity

5.5 Java Operators

5.5.1 Arithmetic Operators

5.5.2 Relational Operators

5.5.3 Logical Operators

5.5.4 Assignment Operator

5.5.5 Increment / Decrement Operators

5.5.6 Bitwise Operators

5.5.7 Shift Operator

5.5.8 Conditional Operator

5.5.9 Other operators 5.5.9.1 new operator 5.5.9.2 instanceof operator 5.5.9.3 dot operator

5.6 Writing mathematical expressions in Java

5.7 Operator Precedence Chart

5.8 Summary

5.9 Glossary

5.10 Answers to Check Your Progress / Self Assessment Questions

5.11 References / Suggested Readings

5.12 Model Questions

Page 76: Self Learning Material Programming in Java

70

5.0 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

5.1 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.

5.2 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.

Figure 5.1: Expression, Operand, Operator.

Page 77: Self Learning Material Programming in Java

71

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

5.3 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.

5.4 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.

Check Your Progress / Self Assessment Questions

Page 78: Self Learning Material Programming in Java

72

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?

5.5 Java Operators :Various types of operators available in Java will be explained now, along

with their associativity.

5.5.1 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

Symbol

Name

Purpose Associativity

Multiplication * Asterisk Multiplies x by y, written

as x * y

Left to Right

Division / Slash Gives quotient when x is

divided by y, written as

x/y.

Left to Right

Remainder % Percentage Gives remainder when x

is divided by y, written as

x % y

Left to Right

Addition + Plus Adds x and y, written as

x+y

Left to Right

Subtraction - Minus Subtracts y from x,

written as x-y

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 :

Page 79: Self Learning Material Programming in Java

73

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 xy

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 ?

5.5.2 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 Symbol Used

Symbol Name

Purpose Associativity

Less than < Less than Checks if x is less than y, written as x<y

Left to Right

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

Left to Right

Less than or equal to

<= Less than, equal to

Checks if x is less than or equal to y, written as x <=y

Left to Right

Greater than or equal to

>= Greater than, equal to

Check if x is greater than or equal to y, written as x>=y

Left to Right

Page 80: Self Learning Material Programming in Java

74

Comparison = = double equal to

Checks if x is equal to y, written as x = = y

Left to Right

Not equal to != Sign of exclamation, equal to

Checks if x is not equal to y, written as x != y

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.

5.5.3 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 Symbol Used

Symbol Name

Purpose Associativity

Logical And && Double ampersand

Checks if both conditions are true, written as condition1 && condition2.

Left to Right

Logical OR | | Double pipe sign

Checks if one or both conditions are true, written as condition1 | | condition2.

Left to Right

Logical NOT ! Sign of exclamation

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

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.

Page 81: Self Learning Material Programming in Java

75

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 )?

5.5.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 Symbol Used

Symbol Name

Purpose Associativity

Assigning value to a variable

= Equal to Assigns a value to a variable used on left side.

Right to Left

Example : 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 ;

5.5.5 Increment/Decrement Operators

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 Symbol Used

Symbol Name

Purpose Associativity

Increment value of a variable

++ plus plus Add one to existing value of a variable

Right to Left

Page 82: Self Learning Material Programming in Java

76

Decrement value of a variable

-- 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.

5.5.6 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 Symbol Used

Symbol Name

Purpose Associativity

bit wise and & Ampersand To perform ANDing of bits of two numbers

Left to Right

bitwise or | Pipe To perform ORing of bits of two numbers

Left to Right

bitwise not ~ Tilde sign To perform complement of bits of a number. It unary operator.

Left to Right

bitwise exclusive or

^ Caret To perform bitwise exclusing oring of bits

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.

Page 83: Self Learning Material Programming in Java

77

Ques 9. Which are various bit-wise operators?

5.5.7 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 Symbol Used

Symbol Name

Purpose Associativity

Left shift << less than symbol used twice

To shift bits of a number towards left once.

Left to Right

Right shift >> Greater than symbol used twice

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.

5.5.8 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 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 Symbol Used

Symbol Name

Purpose Associativity

Page 84: Self Learning Material Programming in Java

78

If then else ? : Question mark and colon

To evaluate one of two operands on the basis of a condition given by first operand.

Right to Left

5.5.9 Other Operators

Apart from above there are some other special operators available in Java. These are :

5.5.9.1 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

5.5.9.2 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.

5.5.9.3 dot operator (.)

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.

5.6 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.

Page 85: Self Learning Material Programming in Java

79

Mathematical expression Java Expression

(x+y)/z

�(� + �) Math.sqrt(x+y)

x2+y2 x*x + y*y

disc = b2 – 4 a c disc=b*b -4 * a *c

(� + �)� Math.pow(x+a, n)

ci=p*Math.pow(1+r/100, t)

x<y<z x<y && y<z

5.7 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.

Page 86: Self Learning Material Programming in Java

80

Fig. 5.1 : Operator precedence chart [source:

http://www.tutorialspoint.com/java/java_basic_operators.htm]

Page 87: Self Learning Material Programming in Java

81

5.8 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.

5.9 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.

Page 88: Self Learning Material Programming in Java

82

5.10 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.

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 (^)

5.11 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

5.12 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;

Page 89: Self Learning Material Programming in Java

83

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 ;

Page 90: Self Learning Material Programming in Java

84

BSBC-502

Programming in Java

Unit-2 Lesson-6 Control Structures – branching

Chapter Index

6.0 Objectives 6.1 Introduction 6.2 Flow Control

6.2.1 Control Structures 6.2.2 Branching (Selection) 6.2.3 Simple if 6.2.4 if else 6.2.5 Nested if 6.2.6 if else ladder 6.2.7 switch

6.3 Summary 6.4 Glossary 6.5 Answers to Check Your Progress / Self Assessment Questions 6.6 References / Suggested Readings 6.7 Model Questions

Page 91: Self Learning Material Programming in Java

85

6.0 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.

6.1 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. It

changes the default behavior of the Java program whereby it executes each and every statement

of program from top to bottom.

6.2 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.

6.2.1 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.

6.2.2 Branching Statements (or Selection Statements)

Page 92: Self Learning Material Programming in Java

86

The selection statements interrupt the normal flow of the program and makes selectionbetween

alternative paths depending upon the condition’s 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

6.2.3 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 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. 6.1.

Figure 6.1 Flow chart of simple if statement

The use of simple-if statement is demonstrated with the help of an example:

Condition

al

Group of statements

true

Page 93: Self Learning Material Programming in Java

87

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 ; netPay = pay - taxded ; } //System.out.println("Income Tax : " + incomeTax) ;

System.out.println("Net Pay : " + netPay) ; } } Output Enter Basic Pay :42750 Net Pay : 29925.0 6.2.4 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. 6.2.

Condition

al

<Statement Group 2 >

True False

<Statement Group 1 >

Page 94: Self Learning Material Programming in Java

88

Figure 6.2 Flow chart of if-else statement Program to check if a number is even or odd import java.util.* ; class IfElseDemo { 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 6.2.5 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

Page 95: Self Learning Material Programming in Java

89

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. 6.3.

Figure 6.3 Flow chart of nested if…else 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();

True

True

Statement

True

False

Condition1 Statement Group-1

False

Condition Statement Group-2

False

Condition Statement Group-3

Next Statement

Page 96: Self Learning Material Programming in Java

90

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 ) { 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 6.2.6 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

Page 97: Self Learning Material Programming in Java

91

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. 6.4.

Figure 6.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 ;

Condition1

-

Condition2

-

Condition3

-

Statement Group 4

False

True

Next Statement

False

True

False

Statement Group 1

Statement Group 2

Statement Group 3

True

Page 98: Self Learning Material Programming in Java

92

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

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

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

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

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

6.2.7 Switch Statement

Page 99: Self Learning Material Programming in Java

93

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. 6.5.

Figure 6.6 Flow chart of switch statement

Default Statement block Statement block 1

Nextstatement

= Value_1

Expression

No match

. . .

= Value 2 = Value n

Statement block 2 Statement block n

Page 100: Self Learning Material Programming in Java

94

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[ ]) { int month ; Scanner sc = new Scanner(System.in) ; System.out.print("Enter a month (1-12) : ");

Page 101: Self Learning Material Programming in Java

95

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 ; default : System.out.println("Default case of Nested Switch !!") ; } break ;

Page 102: Self Learning Material Programming in Java

96

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

Ques 5.Can we use float or double variable or expression in a switch statement?

Ques 6. Can we attach more than one label with the switch block?

Ques 7. What is the use of break statement in the switch block?

Ques 8. What is the role of default statement block in a switch statement?

6.3 Summary

In this lesson, we have studied the different flow control statements such as simple if, if else,

nested if, if else ladder and switch statements

6.4 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.

Page 103: Self Learning Material Programming in Java

97

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.

6.5 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.

6.6 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

Page 104: Self Learning Material Programming in Java

98

6.7 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.

Page 105: Self Learning Material Programming in Java

99

BSBC-502

Programming in Java

Unit-2 Lesson-7 Control structures – Looping

Chapter Index

7.0 Objectives

7.1 Introduction

7.2 Looping

7.3 The while Statement

7.4 The do-while Statement

7.5 The for Statement

7.6 Additional features of for loop

7.7 Nesting of for loops

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

7.9 Labeled Loops

7.10 Summary

7.11 Glossary

7.12 Answers to Check Your Progress / Self Assessment Questions

7.13 References / Suggested Readings

7.14 Model Questions

Page 106: Self Learning Material Programming in Java

100

7.0 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.

7.1 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.

7.2 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

7.3 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 condition evaluates to false the loop will not execute at all. The

Page 107: Self Learning Material Programming in Java

101

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> } The flow chart of the while loop is shown in fig. 7.1.

Figure 7.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 ;

condition Body of Loop True

Next Statement

False

Page 108: Self Learning Material Programming in Java

102

i++ ; } mean = sum / n ; System.out.println("Value of Mean = " + mean); } } Output

Value of Mean = 3.0

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.

Page 109: Self Learning Material Programming in Java

103

7.4 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) ;

Figure 7.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

-

Next

condition

Group of Statementsfalse

trueNe

False

Page 110: Self Learning Material Programming in Java

104

{ sum += i ; 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);

7.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.

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

Page 111: Self Learning Material Programming in Java

105

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. 7.3.

Figure 7.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); System.out.print("Enter a Number : " ) ; n = sc.nextInt( ); for(int i=1 ; i <= 10 ; i++)

-

False condition

initialization

True

Group of

statements

update expression

Next Statement

Page 112: Self Learning Material Programming in Java

106

{ System.out.println(n+" X "+i+" = "+(n*i)) ; } } }

Output

Enter a Number : 7 7 X 1 = 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

7.6 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) ; } }

Output

Enter a Number : 75

Page 113: Self Learning Material Programming in Java

107

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

i = 5, j = 6

Page 114: Self Learning Material Programming in Java

108

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:

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( ; ; ) { }

Page 115: Self Learning Material Programming in Java

109

7.7 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, 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 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101 106 111 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++) {

Page 116: Self Learning Material Programming in Java

110

j=j + i ; j- - ;

} System.out.println(“J=” + j ) ;

7.8 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 7.4 demonstrates the use of break.

statement1 statement2 : : if (<condition>) break ; : Statement outside loop body

Figure 7.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) {

Normal flow

Flow when break

start of loop

end of loop

Loo

p b

od

y

Page 117: Self Learning Material Programming in Java

111

if(i == 10) break ; System.out.println("I = " + i); } System.out.println("Statement after loop"); } }

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 : : if (condition) continue ; : Figure 7.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++)

Normal flow

Flow when continue

start of loop body

end of loop

Loo

p b

od

y

Page 118: Self Learning Material Programming in Java

112

{ 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); } }

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.

7.9 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;

Page 119: Self Learning Material Programming in Java

113

continue label ;

where, the label is a name that identifies the block of code.

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.

Page 120: Self Learning Material Programming in Java

114

Example:

classLabeledContinueDemo {

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....

7.11 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.

Page 121: Self Learning Material Programming in Java

115

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.

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.

7.12 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

7.13 References / Suggested Readings

1. Complete Reference Java, Tata McGraw Hill.

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

7.14 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.

Page 122: Self Learning Material Programming in Java

116

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?

Page 123: Self Learning Material Programming in Java

117

BSBC-502

Programming in Java

Unit-2 Lesson – 8 Classes and Wrapper Classes

Chapter Index

8.0 Objectives 8.1 Introduction 8.2 Defining a Class

8.2.1 Adding Variables 8.2.2 Adding Methods 8.2.3 Creating Objects 8.2.4 Accessing Class Members

8.3 Constructors 8.4 Inheritance 8.5 Extending a Class 8.6 Defining a subclass 8.7 Subclass constructor 8.8 Multilevel inheritance 8.9 Hierarchical inheritance 8.10 Overriding Methods 8.11 Final Variables and Methods 8.12 Final Classes 8.13 Finalizer Methods 8.14 Wrapper Classes 8.15 Autoboxing and Unboxing 8.16 Static Classes 8.17 Abstract Classes 8.18 Annotations 8.19 Method Overloading 8.20 Nesting of methods 8.21 Methods with varargs 8.22 Garbage Collection 8.23 Summary 8.24 Glossary 8.25 Answers to Check Your Progress / Self Assessment Questions 8.26 References / Suggested Readings 8.27 Model Questions

Page 124: Self Learning Material Programming in Java

118

8.0 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.

8.1 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.

8.2 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 ;

……………….

Page 125: Self Learning Material Programming in Java

119

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>

}

}

As shown in the above class definition, the body of a class usually consists of instance variable

and methods.

8.2.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:

Page 126: Self Learning Material Programming in Java

120

class Employee

{

int empNo ;

String EmpName ;

double basicSal ;

}

The class Employee declared above contains three instance variables, empNo, EmpName and

basicSal.

8.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 user-defined 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 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:

Page 127: Self Learning Material Programming in Java

121

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) ;

}

}

8.2.3 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.

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

Page 128: Self Learning Material Programming in Java

122

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?

8.2.4 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.

{

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

Page 129: Self Learning Material Programming in Java

123

ob.rollno = 1001;

ob.marks = 567;

double result ;

result = ob.marks / 600 * 100 ;

System.out.println("The percentage is "+result) ;

}

}

8.3 Constructor

An object should be first initialized before using it in a program. 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 method and 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.

For example:

class Student

{

int rollno ;

String name ;

double marks ;

Page 130: Self Learning Material Programming in Java

124

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 ;

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 ( )) ;

}

}

Page 131: Self Learning Material Programming in Java

125

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?

8.4 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. 8.1 using the UML class diagram using a solid

line with an arrow head pointing towards super class name.

Figure 8.1 UML diagram showing inheritance

8.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

Superclass

Subclass

Page 132: Self Learning Material Programming in Java

126

{

// members that are specific to subclass and are not persent in superclass

}

Here, the superclass is parent class that already exists.

8.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.

Let’s take an example to illustrate the use of constructors in inheritance:

class SuperClass

{ double a, b ;

SuperClass(double m, double n)

{ a = m ;

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) ;

Page 133: Self Learning Material Programming in Java

127

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) ;

sub.print( ) ;

sub.mean( ) ;

}

}

8.8 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. 8.2 given below.

Page 134: Self Learning Material Programming in Java

128

Figure 8.2 Diagram showing multilevel inheritance

8.9 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. 8.3 given below:

Figure 8.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 ?

8.10 Overriding Methods

GrandParent

Child

Parent

Parent

Child2 Child1 Child3

Page 135: Self Learning Material Programming in Java

129

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) ; } } 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) ;

Page 136: Self Learning Material Programming in Java

130

sub.mean( ) ; } }

8.11 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( )

{

// Method body

}

8.12 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( )

Page 137: Self Learning Material Programming in Java

131

{

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?

8.13 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 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 }

8.14 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

Page 138: Self Learning Material Programming in Java

132

simple types. All the wrapper classes reside in java.lang package and its hierarchy is depicted in

Fig. 8.4.

Figure 8.4 Hierarchy of Wrapper classes

8.15 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);

}

}

Object

Number

Byte Short Intege

r

Long Float Double Character Boolean

Page 139: Self Learning Material Programming in Java

133

Check Your Progress / Self Assessment Questions

Ques10.What is the use of finalize( ) method?

Ques11.What is the name of wrapper class for integer?

8.16 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( ) ; } }

8.17 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:

Page 140: Self Learning Material Programming in Java

134

abstract class AbstractClassName

{ abstract void print( ) ; // abstract method void display( ) { // code here

} }

Check Your Progress / Self Assessment Questions

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

Ques13.Can abstract class contain instance methods?

8.18 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 ;

8.18 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.

Page 141: Self Learning Material Programming in Java

135

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:

@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:

Page 142: Self Learning Material Programming in Java

136

@interface MyAnnotation

{ int val1( );

String val2( ); String val3( );

}

These can be provided default value also. For example :

@interface MyAnnotation

{ int val1( ) default 1;

String val2( ) default "";

String val3( ) default "xyz";

}

8.19 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) ;

}

Page 143: Self Learning Material Programming in Java

137

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[]) { Overloading ob = new Overloading( ) ; ob.max(6,19); ob.max(45.2, 34.5) ; } } 8.20 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

Page 144: Self Learning Material Programming in Java

138

{ public static void main(String args[]) { NestingMethod ob = new NestingMethod( ) ; ob.max(16,19); } }

8.21 Methods with Varargs (Variable arguments)

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

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); } } }

8.22 Garbage Collection

Page 145: Self Learning Material Programming in Java

139

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?

Ques 16. A class consists of

a. variables

b. methods

c. variables and methods

Ques 17. An object is an _________________ of a class

a. instance

b. designing

c. debugging

Ques 18. _________________ is used to initialize of variables upon creation of an object

a. destructor

b. constructor

c. Integer

Ques 19. Inheritance relationship can be described using

a. UML class diagram

b. Images

c. Objects

8.23 Summary

This lesson describes the class, subclass in detail. The different types of inheritance, overriding

and overloading methods are discussed.

8.24 Glossary

Page 146: Self Learning Material Programming in Java

140

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.

8.25 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.

Page 147: Self Learning Material Programming in Java

141

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( )

Ans 16. c

Ans 17. a

Ans 18. b

Ans 19. a

8.26 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

8.27 Model Questions

Page 148: Self Learning Material Programming in Java

142

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 ?

Page 149: Self Learning Material Programming in Java

143

BSBC - 502

Programming in Java

Unit-3 Lesson - 9 Array, Vectors and String Handling

Chapter Index

9.0 Objectives 9. 1 Introduction 9.2 Arrays 9.3 One Dimensional Arrays 9.4 Creating an Array 9.4.1 Array Declaration 9.4.2 Creation of arrays 9.4.3 Initialization of arrays 9.4.4 Array length 9.5 Two Dimensional Array 9.6 Vectors 9.7 Strings 9.7.1 String Arrays 9.7.2 String methods 9.7.3 StringBuffer Class 9.8 Type Conversion 9.9 Command Line Arguments 9.10 Summary 9.11 Glossary 9.12 Answers to Check Your Progress / Self Assessment Questions 9.13 References / Suggested Readings 9.14 Model Questions

Page 150: Self Learning Material Programming in Java

144

9.0 Objectives

Understanding the concept of an array

Understanding theVectors concept

Understanding the concept of Strings

Learning Type Conversion

Understanding the concept Command Line Arguments

9.1 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.

9.2 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.

9.3 One-Dimensional Arrays

Page 151: Self Learning Material Programming in Java

145

One dimensional array is a list of elements. Elements in the list have only one dimension, .i.e. they

expand 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. 9.1.

Figure 9.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.

9.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.

9.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

Page 152: Self Learning Material Programming in Java

146

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 doesn’t refer to any array object yet.

9.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] ;

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]);

Page 153: Self Learning Material Programming in Java

147

} } Output Value of fourth element 30.9 9.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} ; The size of array marks[ ] is 4. 9.4.4 Array Length As objects, arrays also have a useful attribute length 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.

The length 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 ;

Page 154: Self Learning Material Programming in Java

148

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 variable holds 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?

9.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 array-

of-array of type int.The new operator dynamically allocates an array with 3 elements having type

Page 155: Self Learning Material Programming in Java

149

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.

Figure 9.2 Representation of a two dimensional array

The two dimensional arrays can be demonstrated with the help of an example: class TwoDimArray { public static void main(String args[ ]) { 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?

Arr2D

a[0]

a[1]

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

Page 156: Self Learning Material Programming in Java

150

9.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 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.

Page 157: Self Learning Material Programming in Java

151

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)); 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

Page 158: Self Learning Material Programming in Java

152

\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?

9.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”

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) ;

Page 159: Self Learning Material Programming in Java

153

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”.

9.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:

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 {

Page 160: Self Learning Material Programming in Java

154

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 9.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)

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.

Page 161: Self Learning Material Programming in Java

155

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 string’s

characters followed by the second string’s 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

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) ;

Page 162: Self Learning Material Programming in Java

156

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); } } Output

His name is Sunil and Sunil is a good boy. Sunil is a good boy. 9.7.3 StringBuffer Class

Page 163: Self Learning Material Programming in Java

157

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 an empty string buffer and an initial capacity of 16

characters.

public StringBuffer(int capacity): Constructs an empty 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"); 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

Page 164: Self Learning Material Programming in Java

158

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?

9.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

9.3.

Figure 9.3 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 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

9.9 Command Line Arguments

long int float double

shorbyte

char

Page 165: Self Learning Material Programming in Java

159

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?

Ques 11. An array is a collection of

a. heterogenous elements

b. homogenous elements

c. sparse elements

Ques 12. Array in Java are created using

a. delete operator

b. enum

c. new operator

Ques 13. A vector is a ______________ array

Page 166: Self Learning Material Programming in Java

160

a. dynamic

b. resizeable

c. dynamic and resizeable

Ques 14. A string is a sequence of characters enclosed within ________________ quotes

a. single

b. double

c. triple

9.10 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 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.

9.11 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.

9.12 Answers to Check Your Progress / Self Assessment Questions

Ans1. length

Ans2. Yes

Page 167: Self Learning Material Programming in Java

161

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[ ]

Ans 11. b

Ans 12. c

Ans 13. c

Ans 14. b

9.13 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

9.14 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.

BSBC - 502

Programming in Java

Unit-3 Lesson - 10 Interfaces

Page 168: Self Learning Material Programming in Java

162

Chapter Index

10.0 Objectives

10.1 Introduction

10.2 Defining Interfaces

10.3 Extending Interfaces

10.4 Implementing Interfaces

10.5 Accessing Interface Variables

10.6 Implementing multiple inheritance through interfaces

10.6.1. An interface can extend multiple existing interfaces

10.6.2. A class can implement multiple interfaces

10.6.3 Implementing run time polymorphism using interfaces

10.7 Summary

10.8 Glossary

10.9 Answers to Check Your Progress / Self Assessment Questions

10.10 References / Suggested Readings

10.11 Model Questions

10.0 Objectives

Differentiate between class and interface.

Page 169: Self Learning Material Programming in Java

163

Explain the features of interfaces

How an interface is implemented

How multiple inheritance is achieved through interfaces

Accessing Interface Variables

10.1 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 doesn’t

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.

10.2 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

Page 170: Self Learning Material Programming in Java

164

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.

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 differences between an interface and a class. Some of these are :

Page 171: Self Learning Material Programming in Java

165

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.

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?

10.3 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.

Page 172: Self Learning Material Programming in Java

166

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

ChidInterface must be a valid java identifier.

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 10.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) ;

Page 173: Self Learning Material Programming in Java

167

}

}

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.

10.4 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.

Page 174: Self Learning Material Programming in Java

168

Figure 10.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

{

Page 175: Self Learning Material Programming in Java

169

int empid, deptid;

long basicSalary;

int experienceInYears, SpecialIncrement ;

long totalsalary, long totalbonus ;

public void calculateTotalSalary()

{ 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

Page 176: Self Learning Material Programming in Java

170

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.

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 ;

}

Page 177: Self Learning Material Programming in Java

171

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 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 ;

}

Page 178: Self Learning Material Programming in Java

172

public void calculateBonus()

{

totalbonus =2000 ;

}

}

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?

Page 179: Self Learning Material Programming in Java

173

10.5 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.

10.6 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.

10.6.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( ) ;

}

Page 180: Self Learning Material Programming in Java

174

interface MyInterface2 Parent interface 2

{

final int sum=0;

void gun( ) ;

}

i

interface MyInterface3 extends MyInterface1 child interface extending two interfaces

{

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) ;

Page 181: Self Learning Material Programming in Java

175

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 methods

declared in MyInterface1 and MyInterface2 become available to class for implementation via

MyInterface2 only.

10.6.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") ;

Page 182: Self Learning Material Programming in Java

176

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) ;

}

}

10.6.3 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 );

Page 183: Self Learning Material Programming in Java

177

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;

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.

Page 184: Self Learning Material Programming in Java

178

//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

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?

Ques 8. An interface can have

a. method defination

b. body of the method

c. method declaration

Ques 9. In syntax of interface, public keyword is

Page 185: Self Learning Material Programming in Java

179

a. mandatory

b. optional

c. necessary

Ques 10. One interface can be implemented by

a. only one class

b. only two classes

c. more than one class

Ques 11. Implement is a

a. key

b. keyword

c. None of the above

10.7 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.

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.

Page 186: Self Learning Material Programming in Java

180

10.8 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.

10.9 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.

Page 187: Self Learning Material Programming in Java

181

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).

Ans 8. c

Ans 9. b

Ans 10. c

Ans 11. B

10.10 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

10.11 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?

Page 188: Self Learning Material Programming in Java

182

BSBC - 502

Programming in Java

Unit-3 Lesson - 11 Packages

Chapter Index

11.0 Objectives 11.1 Introduction 11.2 System Packages 11.3 Using System Packages 11.4 Naming Conventions 11.5 Creating Packages 11.6 Accessing a Package 11.7 Using a Package 11.8 Adding a Class to a Package 11.9 Hiding Classes 11.10 Summary 11.11 Glossary 11.12 Answers to Check Your Progress / Self Assessment Questions 11.13 References / Suggested Readings 11.14 Model Questions

Page 189: Self Learning Material Programming in Java

183

11.0 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.

Hiding classes in a package.

11.1 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.

11.2 System Package

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 other’s. 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-java-

how-to-use.html) shows some of predefined or inbuilt system packages available in java

Page 190: Self Learning Material Programming in Java

184

Figure 11.1. Inbuilt or System packages in java

Advantage of Packages in Java

Package is used for categorization and grouping of classes and interfaces for their easy

management.

It also provides access protection, It can be restricted that which classes outside a

package can use package members.

They also help in avoiding naming conflicts.

Packages help us to find and locate our classes easily.

11.3 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.

java.uti : collection data structure classes

java.io: file input/output operations

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

Page 191: Self Learning Material Programming in Java

185

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?

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

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

Page 192: Self Learning Material Programming in Java

186

11.4 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.

11.5 Creating Packages

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.

Page 193: Self Learning Material Programming in Java

187

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.

}

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

Page 194: Self Learning Material Programming in Java

188

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 11.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?

Page 195: Self Learning Material Programming in Java

189

11.6 Accessing a Package

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 11.3

11.7 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 outside

Page 196: Self Learning Material Programming in Java

190

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 11.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.

Page 197: Self Learning Material Programming in Java

191

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.

11.8 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.

11.9 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.

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.

Page 198: Self Learning Material Programming in Java

192

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.

11.10 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.

11.11 Glossary

Package : a way of logically grouping classes together.

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

Page 199: Self Learning Material Programming in Java

193

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.

11.12 Answers to 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.

Page 200: Self Learning Material Programming in Java

194

11.13 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

11.14 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?

Page 201: Self Learning Material Programming in Java

195

BSBC - 502

Programming in Java

Unit-3 Lesson-12 Exception Handling

Chapter Index

12.0 Objectives

12.1 Introduction

12.2 Managing Errors And Exceptions –An Introduction

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

12.4 Exceptions, Syntax of Exception Handling Code

12.5 Multiple Catch Statements

12.6 Using finally Statement

12.7 Throwing Our Own Exceptions

12.8 Using Exceptions for Debugging

12.9 Handling System defined Exceptions

12.10 Creating and handling user defined exception'

12.11 Summary

12.12 Glossary

12.13 Answers to Check Your Progress / Self Assessment Questions

12.14 References / Suggested Readings

12.15 Model Questions

Page 202: Self Learning Material Programming in Java

196

12.0 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.

12.1 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.

12.2 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 don’t 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.

12.3 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.

Compile Time Error

Page 203: Self Learning Material Programming in Java

197

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

6 Ques 1. Which type of errors are easy to detect and debug?

7 Ques 2. Writing “Float” instead of “float” is which type of error ?

12.4 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 programmer’s 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 bad

Page 204: Self Learning Material Programming in Java

198

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).

12.4 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.

Page 205: Self Learning Material Programming in Java

199

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

Page 206: Self Learning Material Programming in Java

200

{ 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)

Page 207: Self Learning Material Programming in Java

201

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

}

System.out.println("Bye");

}

}

12.5 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

Page 208: Self Learning Material Programming in Java

202

ArrayIndexOutOfBounds, Program terminating....

Bye

12.6 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)

Page 209: Self Learning Material Programming in Java

203

{

}

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

8 Ques 3. True/False : One or Zero catch block may follow try block.

9 Ques 4. True/False : It is compulsory to write finally block with a try-catch block

12.7 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 :

Page 210: Self Learning Material Programming in Java

204

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.

12.8 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,

Now, if any error occurs somewhere inside any method then this stack information helps to

Page 211: Self Learning Material Programming in Java

205

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

12.9 Handling System defined Exceptions

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

Page 212: Self Learning Material Programming in Java

206

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.

12.10 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( )

{ return "Error Occured" ;

}

public static void main(String a[ ])

{

try

Page 213: Self Learning Material Programming in Java

207

{ 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( ));

}

}

}

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.

12.11 Summary

When a program is developed it may have some errors in it. Those errors or bugs affect a program

in many ways. Some don’t 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

Page 214: Self Learning Material Programming in Java

208

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.

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.

12.12 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.

12.13 Answers to Check Your Progress / Self Assessment Questions

Ans 1. Compile time errors.

Page 215: Self Learning Material Programming in Java

209

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.

12.14 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

12.15 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?

Page 216: Self Learning Material Programming in Java

210

BSBC - 502

Programming in Java

Unit-4 Lesson - 13 Applet Programming

Chapter Index

13.0 Objectives 13.1 Introduction 13.2 How Applets differ from Applications 13.3 Preparing to write applets 13.4 Building Applet Code 13.5 Applet Life Cycle 13.6 Designing a Web Page 13.7 Applet Tag 13.8 Adding Applet to HTML File 13.9 Running the Applet 13.10 Types of Applets 13.11 Using Applet Applications 13.12 Passing Parameters to Applets 13.13 More About Applet Tag 13.14 Passing Parameters to Applets 13.15 Aligning the Display 13.16 More about HTML Tags 13.17 Displaying Numerical Values 13.18 Getting Input from the User' 13.19 Summary 13.20 Glossary 13.21 Answers to Check Your Progress / Self Assessment Questions 13.22 References / Suggested Readings 13.23 Model Questions

Page 217: Self Learning Material Programming in Java

211

13.0 Objectives

Understanding the meaning and significance of Applets.

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.

13.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.

13.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.

Page 218: Self Learning Material Programming in Java

212

Check Your Progress / Self Assessment Questions

Exercise - I

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?

13.3 Preparing to write Applets

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

console-based 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

}

13.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)

Page 219: Self Learning Material Programming in Java

213

{

g.drawString("Hello World, Form a Simple Java Applet !",50,25);

}

}

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

Exercise - II

Ques 3. Which packages are required to create an applet ?

Ques 4. Which class will be inherited to create an applet?

13.5 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. 13.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

Page 220: Self Learning Material Programming in Java

214

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.

Figure 13.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

Page 221: Self Learning Material Programming in Java

215

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( )

{

Page 222: Self Learning Material Programming in Java

216

msg += "Init method " ;

}

public void start( )

{

msg += "Start method " ;

}

public void paint(Graphics g)

{

msg += "Paint method " ;

g.drawString(msg,40,20);

}

}

Output

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.

Page 223: Self Learning Material Programming in Java

217

Check Your Progress / Self Assessment Questions

Exercise - III

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

13.6 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

<!--

This is multiple lines

Comments used in the code

//-->

Head Section

Page 224: Self Learning Material Programming in Java

218

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>

<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

Page 225: Self Learning Material Programming in Java

219

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>

13.7 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 applets’s 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.

Page 226: Self Learning Material Programming in Java

220

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 applet’s methods such as init( ), start( ) methods etc.

Check Your Progress / Self Assessment Questions

Exercise - IV

Ques7.What is the use of <script> tag?

Ques 8. Which tag is used to insert an applet in a html document?

13.8 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.

Page 227: Self Learning Material Programming in Java

221

13.9 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.

13.10 Types of Applets

In Java, applets are of two types: Signed and Unsigned. The unsigned applets are considered to

be un-trusted 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.

13.11 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

Page 228: Self Learning Material Programming in Java

222

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.

Let’s take an example that illustrates the above concept.

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

Page 229: Self Learning Material Programming in Java

223

13.12 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">

<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:

Page 230: Self Learning Material Programming in Java

224

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);

}

}

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>

Page 231: Self Learning Material Programming in Java

225

Output

Check Your Progress / Self Assessment Questions

Exercise - V

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

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

13.13 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.

Page 232: Self Learning Material Programming in Java

226

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>"] [< 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

Page 233: Self Learning Material Programming in Java

227

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>

</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

Page 234: Self Learning Material Programming in Java

228

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.

<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>

Page 235: Self Learning Material Programming in Java

229

</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

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

Page 236: Self Learning Material Programming in Java

230

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) { 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

Page 237: Self Learning Material Programming in Java

231

{

public void init( )

{

setBackground(Color.white) ;

}

public void paint(Graphics g)

{

g.setColor(Color.black);

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

Page 238: Self Learning Material Programming in Java

232

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); 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

Page 239: Self Learning Material Programming in Java

233

Check Your Progress / Self Assessment Questions

Exercise - VI

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?

13.14 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

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">

Page 240: Self Learning Material Programming in Java

234

…………………

<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") ; 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) ; } }

Page 241: Self Learning Material Programming in Java

235

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

13.15 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 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

Exercise - VII

Ques 3. Which attributes of an applet tag are used to send arguments to an applet?

Page 242: Self Learning Material Programming in Java

236

Ques 4. Is there any limit to number of arguments send to an applet?

13.16 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">

Page 243: Self Learning Material Programming in Java

237

var browserUsed = navigator.appName;

if (browserUsed == 'Mozilla')

{

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

Exercise - VIII

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?

Page 244: Self Learning Material Programming in Java

238

13.17 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 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

13.18 Getting Input from the User

Page 245: Self Learning Material Programming in Java

239

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:

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) ; }

Page 246: Self Learning Material Programming in Java

240

}

Output

Check Your Progress / Self Assessment Questions

Exercise - IX

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?

13.19 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

Page 247: Self Learning Material Programming in Java

241

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.

13.20 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.

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.

13.21 Answers to Check Your Progress / Self Assessment Questions

Check Your Progress / Self Assessment Questions

Exercise I-V

Ans1. True

Ans2. True

Ans3. Java.awt and java.applet

Ans 4.Applet class

Ans 5.void paint( )

Page 248: Self Learning Material Programming in Java

242

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”)

Exercise VI-IX

Ans1. Width and height

Ans2. Pixels

Ans3. <param> attribute

Ans 4. No

Ans 5. HTML5.

Ans 6. <object>

Ans 7. drawstring(String text)

Ans 8. String.valueOf(numeric value)

13.22 References / Suggested Readings

1. Complete Reference Java, Tata McGraw Hill.

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

13.23 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 ?

Page 249: Self Learning Material Programming in Java

243

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?

Page 250: Self Learning Material Programming in Java

244

BSBC-502

Programming in Java

Unit-4 Lesson - 14 Graphics Programming

14.0. Objectives

14.1. Introduction

14.2.Two-Dimensional objects

11.5.1. Drawing lines

11.5.2. Drawing rectangles

11.5.3. Drawing circle & ellipse

11.5.4. Drawing Arc

14.3 Drawing Polygons

14.4 Line Graphs

14.5 Using Control Loops in Applets

14.6 Drawing Bar Charts

14.7. Summary

14.8. Answers to self- assessment questions

14.9 References

14.10 Model questions / Self Answering Questions

14.0. Objectives:-

In this lesson, we will study:

How to create graphics in java

How we can make a good user interface so that the software products look attractive.

14.1.Introduction: -

The Applet window toolkit supports a lot of graphics methods. These graphics can be created on

the main window of an Applet or on a child window of an Applet or may be on a standalone

applications.

Graphics starts from the top left corner of the window & its co-ordinates are (0, 0). However when

the graphics exceeds the limits of the window they are automatically clipped. We can draw lines,

rectangles, ellipse, circles, arc or any other graphics component using various methods.

In the next topics we will study two dimensional transformation & its methods.

14.2.Two-Dimensional objects:-

Page 251: Self Learning Material Programming in Java

245

In this topic we are going to learn how we can draw lines, rectangles, ellipse, circles and arcs using

various methods.

14.2.1. Drawing lines:-

Lines can be created in AWT using drawLine () method like

voiddrawLine (intstartX, intstartY, intendX, intendY)

Here startX and startY are the coordiantes of the startof the lines and endX&endY are the

coordinates of the end of line.

Example: -

//Program to create lines

importjava.awt.*;

importjava.applet.*;

/*

<applet code="lines" width =300 height=200>

</applet>

*/

public class lines extends Applet

{

public void init()

{

}

public void paint (Graphics g)

{

g.drawLine (0,0,100,120);

g.drawLine (0,100,130,0);

g.drawLine (10,20,200,180);

g.drawLine (65,90,500,300);

}

}

Output: -

Page 252: Self Learning Material Programming in Java

246

Figure 11.1

14.2.2. Drawing rectangles: -

Rectangles can be drawn on AWT using

drawRect ()

fillRect ()

Methods as shown below

voiddrawRect (int top, int left, int width, int height)

voidfillRect (int top, int left, int width, int height)

Here the upperleft corner is the topleft specified in height and width

However, we can also create Round Rectangle using Draw RoundRect ()

fillRoundRect ()

methods like

voiddrawRoundRect (int top, int left, int width, int height, intXdiam, intYdiam)

voidfillRoundRect (int top, int left, int width, int height, intXdiam, intYdiam)

Here Xdiam and Ydiam are diameters of the rectangular circles.

Example: -

//Program to create rectangles

importjava.awt.*;

Page 253: Self Learning Material Programming in Java

247

importjava.applet.*;

/*

<applet code="rectangles" width =400 height=500>

</applet>

*/

public class rectangles extends Applet

{

public void init()

{

}

public void paint (Graphics g)

{

g.drawRect (20,20,65,70);

g.fillRect (90,70,120,130);

g.drawRoundRect (10,20,200,180,30,30);

g.drawRoundRect (90,100,250,300,20,20);

}

}

Output: -

Figure 11.2

14.2.3. Drawing circle & ellipse: -

Two draw ellipse in Java we use

drawOval ()

fillOval ()

Page 254: Self Learning Material Programming in Java

248

Methods are shown below

voiddrawOval (int top, int left, int width, int height)

voidfillOval (int top, int left, int width, int height)

Here the dimensions top, left, width and height are same as we have discussed in previous topics.

To draw circle we use square as bounding rectangle.

Example: -

//Program to create Circles and Ellipse

importjava.awt.*;

importjava.applet.*;

/*

<applet code="CircleAndEllipse" width =300 height=300>

</applet>

*/

public class CircleAndEllipse extends Applet

{

public void init()

{

}

public void paint (Graphics g)

{

g.drawOval (15,15,50,50);

g.fillOval (100,10,80,70);

g.drawOval (10,20,200,180);

g.fillOval (30,80,150,150);

}

}

Output: -

Page 255: Self Learning Material Programming in Java

249

Figure 11.3

As shown in example we have mentioned the co-ordinate same as.

drawOval (15,15,50,50) the oval forms to be circle.

14.2.4. Drawing Arc:-

Arcs can be drawn like

drawArc ()

fillArc ()

Methods are shown below

Void drawArc (int top, int left, int width, int height, intstartAngle, intsweepAngle)

Void fillArc (int top, int left, int width, int height, intstartAngle, intsweepAngle)

Here the angular distance is represented by sweepAngle& Arc is drawn from angular distance

specified by start angle.

Example: -

//Program to create Arcs

importjava.awt.*;

Page 256: Self Learning Material Programming in Java

250

importjava.applet.*;

/*

<applet code="Arc" width =300 height=300>

</applet>

*/

public class Arc extends Applet

{

public void init()

{

}

public void paint (Graphics g)

{

g.drawArc (15,15,50,50,0,40);

g.fillArc (100,10,80,70,0,30);

g.drawArc (10,20,200,180,0,15);

g.fillArc (30,80,150,150,0,45);

}

}

Output: -

Figure 11.4

As shown in example when we mention the same co-ordinates in oval method,

drawOval(15,15,50,50) then oval turns to a circle.

Page 257: Self Learning Material Programming in Java

251

Check your progress/ Self-assessment questions

Exercise-I

Q1. Write methods to draw lines.

___________________________________________________________________________

___________________________________________________________________________

_________________________________________________________________________

Q2.Write two methods to draw ellipse.

___________________________________________________________________________

___________________________________________________________________________

_________________________________________________________________________

Q3.Write two methods to draw Arcs.

___________________________________________________________________________

___________________________________________________________________________

_________________________________________________________________________

Q4. What is the difference between drawOval() and fillOval() methods?

___________________________________________________________________________

___________________________________________________________________________

__________________________________________________________________________

14.3 Drawing Polygons

The drawPolygon() method draws a path of numPoints nodes by taking one element at a time out

of xPoints and yPoints to make each point. The path is drawn in the current color. If either

xPoints or yPoints does not have numPoints elements, drawPolygon() throws a run-time

exception.

Syntax

public abstract void drawPolygon (int xPoints[], int yPoints[], int numPoints)

Program to draw a polygon

import java.awt.*; import java.applet.*; /* <applet code="HourGlass" width=230 height=210> </applet> */ public class HourGlass extends Applet

Page 258: Self Learning Material Programming in Java

252

{ public void init() { setBackground(Color.black); setForeground(Color.green); } public void paint(Graphics g) { int xpoints[] = {30, 200, 30, 200, 30}; int ypoints[] = {30, 30, 200, 200, 30}; int num = 5; g.drawPolygon(xpoints, ypoints, num); } }

14.4 Line Graphs

A line graph is a graphical display of information that changes continuously over time. A line graph may also be referred to a line chart. Within a line graph, there are points connecting the data to show a continuous change. A line graph has two axes. The x-axis of a line graph shows the occurrences and the categories being compared over time and the y-axis represents the scale, which is a set of numbers that represents the data and is organized into equal intervals.

You can draw XY line charts using JFreechart- the most popular chart generation framework in Java.

You can use JFreechart in your project by adding the following JAR files to the project’s classpath:

jcommon-VERSION.jar

jfreechart-VERSION.jar

Program to draw line graph using JFreechart

public class XYLineChartExample extends JFrame {

public XYLineChartExample() { super("XY Line Chart Example with JFreechart"); JPanel chartPanel = createChartPanel(); add(chartPanel, BorderLayout.CENTER);

Page 259: Self Learning Material Programming in Java

253

setSize(640, 480); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } private JPanel createChartPanel() { // creates a line chart object // returns the chart panel } private XYDataset createDataset() { // creates an XY dataset... // returns the dataset } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new XYLineChartExample().setVisible(true); } }); } }

14.5 Using Control Loops in Applets

Following program I used to draw 4 consecutive circles using a ‘for’ loop. The methods used are drawOval( ), fillOval( ) and setColor( ). PROGRAM

import java.awt.*;

import java.applet.*;

public class ControlLoopApplet extends Applet

{

public void paint(Graphics g)

{

Page 260: Self Learning Material Programming in Java

254

for(int i=1;i<=4;i++)

{

if(i%2==0)

{

g.fillOval(90,i*50+10,50,50);

g.setColor(Color.black);

}

else

{

g.drawOval(90,i*50+10,50,50);

g.setColor(Color.red);

}

}

}

}

/* <applet code=ControlLoopApplet width=300 height=300>

</applet> */

Drawing a bar chart

Page 261: Self Learning Material Programming in Java

255

In this section, you will learn how to draw simple bar chart in Java. A bar chart (bar graph) is a way of comparing two or more values using rectangular bars of lengths. The bars can be horizontally or vertically oriented.

14.6 Program to draw a bar chart

import java.applet.*; import java.awt.*; /* <applet code = "BarChart.class" width=400 height=400> <param name="year0" value="2001"> <param name="year1" value="2002"> <param name="year2" value="2003"> <param name="year3" value="2004"> <param name="year4" value="2005"> <param name="result0" value="80"> <param name="result1" value="90"> <param name="result2" value="100"> <param name="result3" value="100"> <param name="result4" value="98"> </applet> */ public class BarChart extends Applet { int n; String year[]; int value[]; public void init() { n = 5; year = new String[n]; value = new int[n]; year[0] = getParameter("year0"); year[1] = getParameter("year1"); year[2] = getParameter("year2"); year[3] = getParameter("year3"); year[4] = getParameter("year4");

Page 262: Self Learning Material Programming in Java

256

value[0] = Integer.parseInt(getParameter("result0")); value[1] = Integer.parseInt(getParameter("result1")); value[2] = Integer.parseInt(getParameter("result2")); value[3] = Integer.parseInt(getParameter("result3")); value[4] = Integer.parseInt(getParameter("result4")); } public void paint(Graphics g) { Font font = new Font("Arial",Font.BOLD,15); g.setFont(font); for(int i = 0; i < n; i ++) { g.setColor(Color.BLUE); g.drawString(year[i], 20, i * 50 + 30); g.setColor(Color.RED); g.fillRect(70, i * 50 + 10, value[i], 40); g.drawString(String.valueOf(value[i]) + "%", 180, i * 50 + 35); } String msg = "Bar Chart from Year 2001 - 2005"; g.setColor(Color.darkGray); font = new Font("Arial",Font.BOLD,20); g.setFont(font); g.drawString(msg, 50, 300); } } The labels for the bar chart are placed in a HTML file as <param> attributes and then used in Applet for displaying bar-chart. The method getParameter() is used to fetch data values (strings) from the html file. The parseInt() function is used to convert strings to integer values.

14.7. Summary:-

In this lesson, we have learnt about graphics which includes drawing lines, circles, ellipse, Arcs

and rectangles. We have also learnt the concept of event handling and its various classes that

handle mouse, keyboard & other GUI components. In addition to that we taught layout manager

that makes GUI components attractive. Menus and Popup Menus are the major part of softwares

these days. To sum up, this chapter helps us to understand various GUI components.

14.8. Answers to self-assessment questions

Page 263: Self Learning Material Programming in Java

257

Exercise-I

Answer 1.voiddrawLine (intstartX, intstartY, intendX, intendY)

Answer 2. voiddrawOval (int top, int left, int width, int height)

voidfillOval (int top, int left, int width, int height)

Answer 3.

Void drawArc (int top, int left, int width, int height, intstartAngle, intsweepAngle)

Void fillArc (int top, int left, int width, int height, intstartAngle, intsweepAngle)

Answer 4. drawOval() method draw an oval on specified co-ordinates whereas fillOval() method

fills that oval with a color.

14.9 References / Suggested Readings

1. Complete Reference Java, Tata McGraw Hill.

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

14.10. Model questions

Q1. Explain graphics in AWT class.

Q2. Write a program to draw a circle exactly in center of an applet window.

Q3. Write a program to draw bar charts?

Q4. Write a program to draw arcs?

Q5. Write a program to draw polygons?

Page 264: Self Learning Material Programming in Java

258

Chapter-15 Java AWT and Event Handling

Structure of the Chapter

15.0 Objective

15.1 Introduction to AWT

15.2 AWT package Containers

15.2.1 Container and Components

15.2.2 Container classes

15.3 Basic User Interface components

15.3.1 Label

15.3.2 Button

15.3.3 CheckBox

15.3.4 Choice

15.3.5 TextField

15.3.6 TextArea

15.3.7 Menu, MenuBar, MenuItem

15.4 Layouts

15.4.1 Border Layout

15.4.2 Grid Layout

15.4.3 Flow Layout

15.4.4 Card Layout

15.5 Event delegation approach

15.5.1 Event

15.5.2 Event Source

15.5.3 Event Listener

15.6 Action Listener

15.7 Adjustment Listener

15.8 Mouse Listener

15.9 Mouse Motion Listener

15.10 Window Listener

15.11 Key Listener

15.12 Item Listener

15.13 Summary

15.14 References

Page 265: Self Learning Material Programming in Java

259

15.0 Objective

After studying this chapter student will able to:

Understand various classes and methods of AWT.

Create basic graphical user interface based forms.

Identify different layouts which can be applied in different frames.

Can apply action event based on mouse and key.

Implement an application which can be used as stand-alone GUI based application without

database.

15.1 Introduction to AWT

AWT is one of the most important component of java because it gives the basic idea about the

graphical user interface that how to create and manage windows. AWT is known as Abstract

Window Toolkit which is specially used for creating your own applets and GUI based stand-alone

applications.It is the foundation of Swings which is mostly used now days with many applications

which are using java. The AWT contains many classes and methods which are further explain in

this chapter which contains frame, labels, buttons, panel and many more which all together helps

in creating window application.

15.2 AWT package Containers

The AWT package is inside the java package, so to use the AWT classes we need to import the

entire package using

importjava.awt.*;

* is used for importing all the classes available in AWT package. If we want to import only one

specific class we can directly name the class rather than using * for eg:

importjava.awt.Frame;

AWT package contains numerous classes and contain several packages inside it and it is Java’s

one of the largest package. Table 15-1 list some of the many AWT classes.

Sr.No Class Description 1 Frame Creates a window that has title bar, close, restore default and

minimize options 2 Label Creates a label which can display text or image in it. 3 Menu Creates a menu drop down option which containsMenuItems in it. 4 MenuBar Creates a menu bar. 5 MenuItems Create a menu items which can be shown in drop down menu. 6 Panel The simplest form of container which can be used inside frame. 7 TextField Creates a single line editable text input.

Page 266: Self Learning Material Programming in Java

260

8 TextArea Creates a multiline editable text input. 9 Button Creates a push controllechd button 10 Font Give options of font style

Table 15-1

Just like this there are many classes which can be used under the AWT packages some of them

which are used regularly are explain above. Although AWT is not that much used these days still

these are the base classes which can help the student to understand the concept of Swings easily.

15.2.1 Containers and Components

There are two types of GUI elements which are containers and components. Containers are those

which hold the components in a specific layout such as frame and panel whereas the components

are the GUI entity like label, button textfield etc.

In the above figure there are two containers which are Frame and Panel and three components

Label, Textfield and Button. Container can contains another container whereas Frame can contain

Panel in itself and further components can be placed in the containers.

15.2.2 Container Classes

AWT contains mainly three types of container classes which are Frame, Panel and Applet. Further

we are going to explain Frame and Panel whereas Applet is not that much in use these days so it

is not explained in that much detail with example.

I. Frame class: A frame provides the main place where there entire components are placed

we can also say it is main window where everything is placed. We can contain frame class

in our program by importing Frame class from AWT package. To show how we can create

a frame in java following example is used :

Program 15.1 Program to show the use of Frame

importjava.awt.Frame;

class Demo

Page 267: Self Learning Material Programming in Java

261

{

public static void main(String [] args)

{

Frame f = new Frame("My First Frame"); // Creating Object of Frame

f.setSize(400,200); // Calling method setSize(width, height)

f.setVisible(true); // Calling method setVisible(boolean)

}

}

Output:

II. Panel class: Panel is a type of container which can be created inside the frame to divide

the frame into different parts with different layouts. Panel is basically a rectangle area

which is used to combine the GUI components which are related to each other.

For example:

Program 15.2 Program to show the use of Panel

importjava.awt.Frame;

importjava.awt.Panel;

importjava.awt.Color;

class Demo

{

public static void main(String [] args)

{

Frame f = new Frame("My First Panel");

Page 268: Self Learning Material Programming in Java

262

f.setSize(400,200);

f.setLayout(null); //Setting Layout this will be explained further

Panel p = new Panel(); // Creating Object of Panel

p.setBounds(0,70,400,130);

p.setBackground(new Color(150,40,30)); // Applying color to panel

f.add(p); // Adding panel into frame

f.setVisible(true);

}

}

15.3 Basic User Interface components

User interface components are those which allows user to interact with application in better and

easy ways. So far we have study the program which was command line based which were not

using any kind of GUI and not user friendly solution to that is AWT user interface components

which are explained as follow:

15.3.1 Labels

The simplest component to use is Label. Label is a class which contains String which can be

displayed any where on the frame. There are different kinds of constructors available for Labels:

Label() throws HeadlessException

Label(String str) throws HeadlessException

we can create Label by using any way from above two. If we create Label with default constructor

then we can set text to label afterword’s by using setText method which belongs to label class. In

second method the str pass to Labels constructor is set as a text to Label.

Page 269: Self Learning Material Programming in Java

263

For example:

Program 15.3 Program to show the use of Label as a components

importjava.awt.Frame;

importjava.awt.Label;

class Demo

{

public static void main(String [] args)

{

Frame f = new Frame("My First Label");

f.setSize(400,200);

f.setLayout(null);

Label l = new Label("My name is Chetan");

l.setBounds(140,80,120,30);

f.add(l);

f.setVisible(true);

}

}

Output:

Page 270: Self Learning Material Programming in Java

264

15.3.2 Button

One of the most used component is Button in any application. Button is a component that contains

some text and performs some action on clicking on it. Button is created using a class Button it also

have two constructors :

Button() throws HeadlessException

Button(String str) throws HeadlessException

here we are going to explain button using following example:

Program 15.4 Program to create button in a frame.

importjava.awt.Frame;

importjava.awt.Button;

class Demo

{

public static void main(String [] args)

{

Frame f = new Frame("My First Button");

f.setSize(400,200);

f.setLayout(null);

Button b = new Button("Click me");

b.setBounds(160,80,100,30);

f.add(b);

f.setVisible(true);

}

}

Page 271: Self Learning Material Programming in Java

265

Output:

15.3.3 CheckBox

A checkbox is a component which is used to turn an option on or off. It have small boxes which

can have a check mark or not with a label with itself. Every checkbox is associated with a label

which describe what kind of option it is. check box are created using CheckBox class.

Program 15.5 Program to show the use of CheckBox

importjava.awt.*;

public class CheckboxExample1

{

CheckboxExample1()

{

Frame f= new Frame("Checkbox Example");

Checkbox checkbox1 = new Checkbox("C++");

checkbox1.setBounds(100,100, 50,50);

Checkbox checkbox2 = new Checkbox("Java", true);

checkbox2.setBounds(100,150, 50,50);

f.add(checkbox1);

f.add(checkbox2);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

public static void main(String args[])

{

Page 272: Self Learning Material Programming in Java

266

new CheckboxExample1();

}

}

Output:

15.3.4 Choice

Choice class is used to create a pop up display list which is used to select different kind of options

among them. It is also known as combo box which are mainly used in forms to input city or state.

Choice contains further choice list which is displayed when the button place on choice is pressed.

The item which we click or select become the first item and displayed to the user.

Program 15.6 Program to create a choice.

importjava.awt.*;

public class ChoiceDemo

{

ChoiceDemo()

{

Frame f= new Frame();

Choice c=new Choice();

c.setBounds(100,100, 75,75);

Page 273: Self Learning Material Programming in Java

267

c.add("Item 1");

c.add("Item 2");

c.add("Item 3");

c.add("Item 4");

c.add("Item 5");

f.add(c);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

public static void main(String args[])

{

newChoiceDemo();

}

}

Output:

15.3.5 TextField

TextField class is a class which is used to create a single line input box. it allows the user to input

string in it and further it can be passed on or moved to any kind of variable for further processing.

Program 15.7 Example of TextField

Page 274: Self Learning Material Programming in Java

268

importjava.awt.*;

classTextFieldExample

{

public static void main(String args[])

{

Frame f= new Frame("TextField Example");

TextField t1,t2;

t1=new TextField(“Welcome “);

t1.setBounds(50,100, 200,30);

t2=new TextField();

t2.setBounds(50,150, 200,30);

f.add(t1); f.add(t2);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

}

Output:

Page 275: Self Learning Material Programming in Java

269

15.3.6 TextArea

Sometime single line input is not sufficient in an application in that case TextArea is used where

we can input multiple lines for example:

Program 15.7 Example of TextArea

importjava.awt.*;

public class TextAreaExample

{

TextAreaExample(){

Frame f= new Frame();

TextArea area=new TextArea("Welcome to TextArea");

area.setBounds(10,30, 300,300);

f.add(area);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

public static void main(String args[])

{

newTextAreaExample();

}

}

Output:

Page 276: Self Learning Material Programming in Java

270

15.3.7 Menu, MenuBar, MenuItem

Menu, MenuBar, MenuItem these all are different classes which can combine togather to form

menu to the main window. MenuBar contains Menu and Menu contains MenuItem.

15.8 Example of Menu in a Frame.

importjava.awt.*;

classMenuExample

{

MenuExample(){

Frame f= new Frame("Menu and MenuItem Example");

MenuBar mb=new MenuBar();

Menu menu=new Menu("Menu");

Menu submenu=new Menu("Sub Menu");

MenuItem i1=new MenuItem("Item 1");

MenuItem i2=new MenuItem("Item 2");

MenuItem i3=new MenuItem("Item 3");

MenuItem i4=new MenuItem("Item 4");

MenuItem i5=new MenuItem("Item 5");

menu.add(i1);

menu.add(i2);

menu.add(i3);

submenu.add(i4);

submenu.add(i5);

Page 277: Self Learning Material Programming in Java

271

menu.add(submenu);

mb.add(menu);

f.setMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

public static void main(String args[])

{

newMenuExample();

}

}

Output:

15.4 Layouts

All the components we have discussed till now have been positioned by the null layout. Layout is

basically the arrangement of the positions of the component in a window. Layout manager

automatically arrange our component using default layout. If developer wants to arrange the

components with its own strategy then AWT is providing facility to set the layout using the

following method:

voidsetLayout(LayoutManager object)

Page 278: Self Learning Material Programming in Java

272

heresetLayout is the method and object is the reference object of LayoutManager which tells which

kind of Layout we are using. if you want to set the corrdinates of the component then you can pass

null as a layoutManager object. if you do this you get a method setBounds() which takes four

parameters which together gives x, y ,width and height of the component.

Java has several predefined LayoutManager classes:

1. BorderLayout

2. GridLayout

3. FlowLayout

4. CardLayout

15.4.1 Border Layout

This Layout is used to arrange the components in five regions: south, west, east, north and center.

Each region (area) may contain one component only. The BorderLayout provides five constants

which are as follow:

1) public static final int NORTH

2) public static final int SOUTH

3) public static final int EAST

4) public static final int WEST

5) public static final int CENTER

Program 15.9Example of Border Layout

importjava.awt.*;

public class Border {

Frame f;

Border(){

f=new Frame();

Button b1=new Button("NORTH");;

Button b2=new Button("SOUTH");;

Button b3=new Button("EAST");;

Button b4=new Button("WEST");;

Button b5=new Button("CENTER");;

Page 279: Self Learning Material Programming in Java

273

f.add(b1,BorderLayout.NORTH);

f.add(b2,BorderLayout.SOUTH);

f.add(b3,BorderLayout.EAST);

f.add(b4,BorderLayout.WEST);

f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) {

new Border();

}

}

Output:

Page 280: Self Learning Material Programming in Java

274

15.4.2 Grid Layout This Layout is used to arrange the components in the rectangular grid form. This grid is a form of

matrix where one component fits in one grid. It uses two dimensional grid which can be define the

number of rows and columns.

Program 15.10 Program to show the use of Grid Layout

importjava.awt.*;

importjavax.swing.*;

public class MyGridLayout{

JFrame f;

MyGridLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

JButton b6=new JButton("6");

JButton b7=new JButton("7");

JButton b8=new JButton("8");

JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));

//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) {

newMyGridLayout();

}

}

Output:

Page 281: Self Learning Material Programming in Java

275

15.4.3 Flow Layout

Flow Layout uses simple layout just same live words flowing in a text editor. The direction of the

layout is in the form of left to right where the component added first will go to right and new

component will be added left to the previous component. We can change the flow of the flow

layout from left to right to right to left or any other.

Program 15.11 Example of flow layout.

importjava.awt.*;

importjavax.swing.*;

public class MyFlowLayout{

JFrame f;

MyFlowLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));

//setting flow layout of right alignment

Page 282: Self Learning Material Programming in Java

276

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) {

newMyFlowLayout();

}

}

Output:

Program 15.4.4 Card Layout

Card layout is different layouts among all the layouts because this layout can store the several

different layout in it. Every layout is separated with the different card index in the deck. This is

mainly for those interfaces which need to be optimum or dynamic in nature.

Page 283: Self Learning Material Programming in Java

277

Check your progress / Self-assessment questions

Q1) Differentiate between container and component?

Q2) Explain any 2 graphical user interface components with example?

Q3) Write a program to show the use of flow layout.

Solution

Ans 1) Containers are those which hold the components in a specific layout such as frame and

panel whereas the components are the GUI entity like label, button textfield etc.

Ans 2)

Frame: A frame provides the main place where there entire components are placed we can also

say it is main window where everything is placed.

Frame f = new Frame();

Label: The simplest component to use is Label. Label is a class which contains String which can

be displayed any where on the frame.

Label l = new Label();

Page 284: Self Learning Material Programming in Java

278

Ans 3)

importjava.awt.*;

importjavax.swing.*;

public class MyFlowLayout{

JFrame f;

MyFlowLayout(){

f=new JFrame();

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));

//setting flow layout of right alignment

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String[] args) {

newMyFlowLayout();

}

}

Page 285: Self Learning Material Programming in Java

279

15.5 Event delegation approach

The modern approach to handle event is based on delegation event model, which is quite simple,

a source generates an event and send it to one or more listeners. Here listener waits till they don’t

get any event; once event is received the listener performs the event and return. The advantages of

this design are that the application that performs event is separate from the user interface that

generates those events. The user interface elements are able to delegate the processing of an event.

15.5.1 Events

In delegation approach an event is an object that describes a state change in a source. Some of the

activities that can generate events are:

1) Pressing a Button

2) Entering a key

3) Selecting an item

4) Clicking the mouse

15.5.2 Event Source

Source is an object that generates an event. Source occurs when the state of an object is changed

and that object generates some kind of event but the most important thing source must be registered

to listener.

15.5.3 Event Listener

Listener is an object that is used when an event occurs. It has two conditions:

1) it must be registered to one or more source.

2) it must implements some methods which need to be performed when event occurs

15.6 Action Listener

ActionListener is an interface which is used to implement ActionEvent on any kind of event.

ActionEvent is generated when any push button is pressed, any list item is selected or any menu

item is selected. ActionListener interface contains one undefined method which is defined by a

class which implements ActionListener, This method is invoked when any event is executed. The

method is as follow:

public abstract void actionPerformed(ActionEventae)

{

// Code to be executed

}

ActionEvent class object contains the information about the source and further according to that

action is performed. ActionEvent class defines four integer constant that can be used to identify

Page 286: Self Learning Material Programming in Java

280

any modification to an action event: ALT_MASK, CTRL_MASK, META_MASK and

SHIFT_MASK.

Program 15.12 Program to perform action event in GUI frame using ActionListener.

importjava.awt.*;

importjava.awt.event.*;

public class ActionListenerExample {

public static void main(String[] args)

{

Frame f=new Frame("ActionListener Example");

final TextField tf=new TextField();

tf.setBounds(50,50, 150,20);

Button b=new Button("Click Here");

b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){ // implementing undefined function

tf.setText("Welcome to ActionLidtener.");

}

});

f.add(b);f.add(tf);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

}

15.7 Adjustment Listener

AdjustmentListener is an interface which is used to receiving adjustment event. Adjustment event

is generated by a scroll bar. There are five types of adjustment events: BLOCK_DECREMENT,

BLOCK_INCREMENT, TRACK, UNIT_DECREMENT, UNIT_INCREMENT. When any class

implements AdjustmentListenerinterface then it need to override a method:

public void adjustmentValueChanged(AdjustmentEventae)

{ }

Program 15.13 Program to implement AdjustmentListener.

Page 287: Self Learning Material Programming in Java

281

importjava.awt.*;

importjava.awt.event.*;

public class AwtListenerProgram {

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

publicAwtListenerProgram (){

prepareGUI();

}

public static void main(String[] args){

AwtListenerProgramawtListenerDemo = new AwtListenerProgram ();

awtListenerDemo.showAdjustmentListenerDemo();

}

private void prepareGUI(){

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEventwindowEvent){

System.exit(0);

}

});

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);

statusLabel.setSize(350,100);

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

Page 288: Self Learning Material Programming in Java

282

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

}

private void showAdjustmentListenerDemo(){

headerLabel.setText("Listener in action: AdjustmentListener");

ScrollPane panel = new ScrollPane();

panel.setBackground(Color.magenta);

panel.getHAdjustable().addAdjustmentListener(new CustomAdjustmentListener());

Label msglabel = new Label();

msglabel.setAlignment(Label.CENTER);

msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

panel.add(msglabel);

controlPanel.add(panel);

mainFrame.setVisible(true);

}

classCustomAdjustmentListener implements AdjustmentListener {

public void adjustmentValueChanged(AdjustmentEvent e) {

statusLabel.setText("Adjustment value: "+Integer.toString(e.getValue()));

}

}

}

15.8 Mouse Listener

The MouseListener is an interface which is used to provide events based on mouse. This interface

defines five methods. which are relates to mouse click, move , pressed , released and many others.

if the mouse is pressed and released at the same point, mouseClicked() is invoked. When the mouse

is entered into any component then mouseEntered() is invoked. When it leaves the component

mouseExited() is called. The mousePressed() and mouseReleased methods are called when the

mouse is pressed and released.

MouseListener methods are declared like this:

public void mouseClicked(MouseEvent me)

{

Page 289: Self Learning Material Programming in Java

283

// Code to be executed when mouse is clicked

}

public void mouseEntered(MouseEvent me)

{

// Code to be executed when mouse is entered

}

public void mouseExited(MouseEvent me)

{

// Code to be executed when mouse is exited

}

public void mousePressed(MouseEvent me)

{

// Code to be executed when mouse is pressed

}

public void mouseReleased(MouseEvent me)

{

// Code to be executed when mouse is released

}

15.9 Mouse Motion Listener

MouseMotionListener interface defines two methods. The mouseMoved and mouseDraggedcan

be performed multiple times and can return more than one value. The mouseDragged() method is

called when the mouse is dragged and returns all the corrdinates of the mouse position. The

mouseMoved() method is called multiple times as the mouse is moved. There forms are as follow:

public void mouseDragged(MouseEvent me)

public void mouseMoved(MouseEvent me)

Program 15.14 Program to implement MouseListener

importjava.awt.*;

importjava.awt.event.*;

public class MouseListenerExample extends Frame implements MouseListener{

Label l;

MouseListenerExample(){

Page 290: Self Learning Material Programming in Java

284

addMouseListener(this);

l=new Label();

l.setBounds(20,50,100,20);

add(l);

setSize(300,300);

setLayout(null);

setVisible(true);

}

public void mouseClicked(MouseEvent e) {

l.setText("Mouse Clicked");

}

public void mouseEntered(MouseEvent e) {

l.setText("Mouse Entered");

}

public void mouseExited(MouseEvent e) {

l.setText("Mouse Exited");

}

public void mousePressed(MouseEvent e) {

l.setText("Mouse Pressed");

}

public void mouseReleased(MouseEvent e) {

l.setText("Mouse Released");

}

public static void main(String[] args) {

newMouseListenerExample();

}

}

Program 15.15 Program to implement MouseMotionListener

importjava.awt.*;

importjava.awt.event.*;

public class MouseMotionListenerExample extends Frame implements MouseMotionListener{

MouseMotionListenerExample(){

addMouseMotionListener(this);

Page 291: Self Learning Material Programming in Java

285

setSize(300,300);

setLayout(null);

setVisible(true);

}

public void mouseDragged(MouseEvent e) {

Graphics g=getGraphics();

g.setColor(Color.BLUE);

g.fillOval(e.getX(),e.getY(),20,20);

}

public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {

newMouseMotionListenerExample();

}

}

15.10 Window Listener

This interface defines many methods like windowActivated() and windowDeactivated() which are

called when a window is activated or deactivated. If a window is iconified, the windowIconified()

method is called. Similarly to open a window or close a window windowOpened() and

windowClosed() method is used. The gernal forms of these methods are:

public void windowActivated(WindowEvent we)

public void windowDeactivated(WindowEvent we)

public void windowIconified(WindowEvent we)

public void windowOpened(WindowEvent we)

public void windowClosed(WindowEvent we)

15.11 Key Listener

To handle keyboard events AWT provides KeyListener interface which provides the action event

on keys to application. when key is pressed a KEY_PRESSED event is generated which calls the

method keyPressed(). Similarly there are keyReleased() and keyTyped() methods which can be

defined by the developer according to his requirements. The following example show how key

Listener is use and how key events are used.

Page 292: Self Learning Material Programming in Java

286

Program 15.16 Program to implement KeyListener

importjava.awt.*;

importjava.awt.event.*;

public class KeyListenerExample extends Frame implements KeyListener{

Label l;

TextArea area;

KeyListenerExample(){

l=new Label();

l.setBounds(20,50,100,20);

area=new TextArea();

area.setBounds(20,80,300, 300);

area.addKeyListener(this);

add(l);add(area);

setSize(400,400);

setLayout(null);

setVisible(true);

}

public void keyPressed(KeyEvent e) {

l.setText("Key Pressed");

}

public void keyReleased(KeyEvent e) {

l.setText("Key Released");

}

public void keyTyped(KeyEvent e) {

l.setText("Key Typed");

}

public static void main(String[] args) {

newKeyListenerExample();

}

}

Page 293: Self Learning Material Programming in Java

287

15.12 Item Listener

ItemListener is an interface which is used to perform action on event when item is selected. This

interface defines itemStateChanged() method that is invoked when the state of an item is changed.

for example:

importjava.awt.*;

importjava.awt.event.*;

public class ItemListenerExample implements ItemListener

{

Checkbox checkBox1,checkBox2;

Label label;

ItemListenerExample()

{

Frame f= new Frame("CheckBox Example");

label = new Label();

label.setAlignment(Label.CENTER);

label.setSize(400,100);

checkBox1 = new Checkbox("C++");

checkBox1.setBounds(100,100, 50,50);

checkBox2 = new Checkbox("Java");

checkBox2.setBounds(100,150, 50,50);

f.add(checkBox1); f.add(checkBox2); f.add(label);

checkBox1.addItemListener(this);

checkBox2.addItemListener(this);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}

public void itemStateChanged(ItemEvent e)

{

if(e.getSource()==checkBox1)

label.setText("C++ Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

if(e.getSource()==checkBox2)

label.setText("Java Checkbox: "

+ (e.getStateChange()==1?"checked":"unchecked"));

}

Page 294: Self Learning Material Programming in Java

288

public static void main(String args[])

{

newItemListenerExample();

}

}

Check your progress / Self-assessment questions

Q1) How many methods need to be override when we are using MouseListner Interface.

Q2) MouseMotionListener is an interface or a class? Explain

Solution:

Ans1) public void mouseClicked(MouseEvent me)

{

// Code to be executed when mouse is clicked

}

public void mouseEntered(MouseEvent me)

{

// Code to be executed when mouse is entered

}

public void mouseExited(MouseEvent me)

{

// Code to be executed when mouse is exited

}

public void mousePressed(MouseEvent me)

{

Page 295: Self Learning Material Programming in Java

289

// Code to be executed when mouse is pressed

}

public void mouseReleased(MouseEvent me)

{

// Code to be executed when mouse is released

}

Ans 2) MouseMotionListener is an interface which have some methods which we need to override

while implementing interface.

15.12 Summary

AWT is one of the largest package in java which contains so many classes and methods which

together helps in creating stand-alone applications, applets and many other things. Although AWT

is not widely used these days but still it is the base of graphical user interface. Today most java

programs uses swing, because swing provides rich implementation than AWT but swing is built

on the API of AWT and many AWT classes are exactly used in swing package. Therefore, even

though most interface today will be based on swing, but solid knowledge of AWT is required. This

chapter also discussed about Event handling which is the most important thing for an application

because without any action the application is nothing. There are several types of event which can

be performed by mouse, keyboard, window and many others which were discussed in detail.

15.13Refrence/Suggested Readings

1. Java The Complete Reference, 8th Edition, Herbert Schildt, Tata Mcgraw-Hill Edition.

2. Head First Java, 2nd Edition, Siyan, K/Bates, Oreilly.

3. Programming Java, 4th Edition, E Balagurusamy, Tata Mcgraw-Hill Edition.

Page 296: Self Learning Material Programming in Java

290

15.14 Model Questions

Q1) Define AWT

Q2) What is AWT. Explain it with an example

Q3) Explain about various AWT classes used in Java

Q4) How mouselistener is different from mousemotionlistener?

Page 297: Self Learning Material Programming in Java

291

Lesson -16 Java I/O Handling

Structure of lesson

16.0 Objective

16.1 Introduction to I/O

16.2 Input Stream

16.3 Output Stream

16.4 File Input Stream

16.5 File Output Stream

16.6 Data Input Stream

16.7 Data Output Stream

16.8 File Class

16.9 Reader Stream

16.10 Writer Stream

16.11 Random Access File

16.12 Summary

16.13 References

Page 298: Self Learning Material Programming in Java

292

16.0 Objective

After Studying this chapter student will be able to:

Understand various I/O Streams.

Understand the concept of files and how to write and read data

Identify the difference between different input output streams

16.1 Introduction to I/O Stream

We use the variable and arrays for storing data inside the programs. This approach causes the

following problems:

1. The data can be store at some limits.

2. The data which is stored in variable and array is temporarily stored, after terminating the

program the values got erased.

3. It is very difficult to store large amount of data in variables and arrays.

To eliminate this limitation, we can use the secondary storage devices such as Floppy Diskor Hard

Disk. The data is stored in these devices in the form of files. Data which is stored in the files is

known as persistent data.

File is collection of record that is stored on particular area of the disk. Record is collection of field

and field is the group of characters.

16.2 Input Stream

Input stream classes that are used to read to 8-bit bytes include a super class known as InputStream

and a number of subclasses for supporting various input related function.

Fig : 16.1 Hierarchy of input stream classes

The super class i.e.InputStream is an abstract class, and therefore we can’t create an instance of

this class. Instead, we must use the subclasses that inherits from this class. Following input

functions are defined by InputStream class:

Page 299: Self Learning Material Programming in Java

293

Marking position in streams

Finding the number of bytes in a stream

Skipping ahead in a stream

Reading Bytes

Closing Streams

Sr. No Method Description 1 int available( ) Returns the number of bytes of input currently

available for reading. 2 void close( ) Closes the input source. Further read attempts will

generate an IOException. 3 void mark(intnumBytes) Places a mark at the current point in the input stream

that will remain valid until numBytes bytes are read. 4 booleanmarkSupported( ) Returns true if mark( )/reset( ) are supported by

theinvoking stream 5 int read( ) Returns an integer representation of the next

available byte of input. –1 is returned when the end of the file is encountered.

6 int read(byte buffer[ ]) Attempts to read up to buffer.length bytes into buffer and returns the actual number of bytes that were successfully read. –1 is returned when the end of the file is encountered.

7 int read(byte buffer[ ], int offset, intnumBytes)

Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning the number of bytes successfully read. –1 is returned when the end of the file is encountered.

Table 16.1 Methods defined by Input Stream

16.2.1 Declaration of class as aInputStream

public abstract class InputStream

extends Object

implementsCloseable

Program 16.1 Write a Program to provide input using InputStream.

importjava.io.FileInputStream;

importjava.io.InputStream;

public class InputStreamDemo {

public static void main(String[] args) throws Exception {

Page 300: Self Learning Material Programming in Java

294

InputStream is = null;

int i;

char c;

try {

// new input stream created

is = new FileInputStream("C://test.txt");

System.out.println("Characters printed:");

// reads till the end of the stream

while((i = is.read())!=-1) {

// converts integer to character

c = (char)i;

// prints character

System.out.print(c);

}

} catch(Exception e) {

// if any I/O error occurs

e.printStackTrace();

} finally {

// releases system resources associated with this stream

if(is!=null)

is.close();

}

}

}

Output:

Let us assume there is test.txt file which is having chetan in it then the output will be

Characters printed:

Chetan

Page 301: Self Learning Material Programming in Java

295

16.3 Output Stream

Output stream classes are inherited from the sub class output stream. Like aInputStream, and

OutputStream is an abstract class and therefore we cannot represent as it.Output Stream having

various subclasses for performing the output operations. . Following output functions are defined

by OutputStream class:

Writing Bytes

Closing Streams

Flushing Streams

Fig: 16.2 Hierarchy of output stream classes

Sr. No Method Description 1 void close( ) Closes the output stream. Further write attempts will

generate an IOException. 2 void flush( ) Finalizes the output state so that any buffers are

cleared. That is, it flushes the output buffers. 3 void write(int b) Writes a single byte to an output stream. Note that

the parameter is an int, which allows you to call write( ) with expressions without having to cast them back to byte.

4 void write(byte buffer[ ]) Writes a complete array of bytes to an output stream.

Table 16.1 Methods defined by Output Stream

16.3.1 Declaration of class as Output Stream

Page 302: Self Learning Material Programming in Java

296

public abstract class OutputStream

extends Object

implementsCloseable, Flushable

16.4 File Input Stream

The FileInputStream class creates an InputStream that you can use to read bytes from a file. Two

commonly used constructors are shown here:

FileInputStream(String filePath)

FileInputStream(File fileObj)

We can use throw a FileNotFoundException. Here, filePathis the full path name of a file, and

fileObj is a File object that describes the file.the following example creates two FileInputStream

that use the same disk file and each of that have two constructor.

FileInputStreamfis= FileInputStream(“test.txt”);

File f = new File(“test.txt”);

FileInputStream fis2= FileInputStream(f);

The following example tell us how to read a single byte, an array of bytes, and a sub range

array of bytes.

Program 16.2 Program to read single character at a time using FileInputStream

importjava.io.FileInputStream;

public class DataStreamExample

{

public static void main(String args[])

{

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

Page 303: Self Learning Material Programming in Java

297

System.out.print((char)i);

fin.close();

}

catch(Exception e){System.out.println(e);

}

}

}

Program 16.3 Program to read entire data at a time using FileInputStream

importjava.io.FileInputStream;

public class DataStreamExample

{

public static void main(String args[])

{

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;

while((i=fin.read())!=-1){

System.out.print((char)i);

}

fin.close();

}

}

}

16.5 File Output Stream

Page 304: Self Learning Material Programming in Java

298

FileOutputStream is a kind of OutputStream which is used to write bytes to a file. It implements

the AutoCloseable and Closeable interface. Some of constructors of FileOutputStream are as

follow:

FileOutputStream(String filepath)

FileOutputStream(File fileObj)

FileOutputStream(String filepath, Boolean append)

FileOutputStream is not dependent on file, if file is not created it automatically creates a file and

perform its operation. How FileOutputStream works is explain in following program example:

Program 16.4 Write a program to write byte using FileOutputStream

importjava.io.FileOutputStream;

public class FileOutputStreamExample

{

public static void main(String args[])

{

try{

FileOutputStreamfout=new FileOutputStream("D:\\testout.txt");

fout.write(65);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

}

}

Program 16.5 Program to write data using FileOutputStream

importjava.io.FileOutputStream;

public class FileOutputStreamExample

{

public static void main(String args[])

{

Page 305: Self Learning Material Programming in Java

299

try{

FileOutputStreamfout=new FileOutputStream("D:\\testout.txt");

String s="Welcome to javaTpoint.";

byte b[]=s.getBytes();//converting string into byte array

fout.write(b);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);

}

}

}

Check your progress

Q1) What is FileInputStream and FileOutputStream?

Q2) What happen if we are trying to write in a file which does not exist?

Solution:

Ans1) The FileInputStream class creates an InputStream that you can use to read bytes

from a file. Two commonly used constructors are shown here:

FileInputStream(String filePath)

FileInputStream(File fileObj)

Page 306: Self Learning Material Programming in Java

300

We can use throw a FileNotFoundException. Here, filePathis the full path name of a file, and

fileObj is a File object that describes the file.the following example creates two FileInputStream

that use the same disk file and each of that have two constructor.

FileOutputStream is a kind of OutputStream which is used to write bytes to a file. It implements

the AutoCloseable and Closeable interface. Some of constructors of FileOutputStream are as

follow:

FileOutputStream(String filepath)

FileOutputStream(File fileObj)

FileOutputStream(String filepath, Boolean append)

Ans 2) File will be created automatically.

16.6 Data Input Stream

DataInputStream enables you read primitive data to or from stream. it implements DataInput

interface, this interface provides converter which convert primitive types into sequence of bytes.

Program 16.6 Program to input data using DataInputStream.

import java.io.*;

public class DataStreamExample {

public static void main(String[] args) throws IOException {

InputStream input = new FileInputStream("D:\\testout.txt");

DataInputStream inst = new DataInputStream(input);

int count = input.available();

byte[] ary = new byte[count];

inst.read(ary);

for (byte bt : ary) {

char k = (char) bt;

Page 307: Self Learning Material Programming in Java

301

System.out.print(k+"-");

}

}

}

16.7 Data Output Stream

DataOutputStream enables you write primitive data to or from stream. it implements DataOutput

interface, this interface provides converter which convert primitive types into sequence of bytes.

Program 16.7 Program to write data using DataOutputStream.

import java.io.*;

public class FilterExample

{

public static void main(String[] args) throws IOException

{

File data = new File("D:\\testout.txt");

FileOutputStream file = new FileOutputStream(data);

FilterOutputStream filter = new FilterOutputStream(file);

String s="Welcome to our programming";

byte b[]=s.getBytes();

filter.write(b);

filter.flush();

filter.close();

file.close();

System.out.println("Success...");

}

}

16.8 File Class

The File class is a kind of a file or directory path name. Because file and directory names have

different formats on different platforms, a normal string is not enough to name them. The File class

contains several methods for working with the path name, deleting and renaming files, creating

Page 308: Self Learning Material Programming in Java

302

new directories, listing the contents of a directory, and determining several common attributes of

files and directories

importjava.io.File;

classfileProperty

{

public static void main(String[] args) {

//accept file name or directory name through command line args

String fname =args[0];

File f = new File(fname);

System.out.println("File name :"+f.getName());

System.out.println("Path: "+f.getPath());

System.out.println("Absolute path:" +f.getAbsolutePath());

System.out.println("Parent:"+f.getParent());

System.out.println("Exists :"+f.exists());

if(f.exists())

{

System.out.println("Is writeable:"+f.canWrite());

System.out.println("Is readable"+f.canRead());

System.out.println("Is a directory:"+f.isDirectory());

System.out.println("File Size in bytes "+f.length());

}

}

}

16.9 Reader Stream

Reader is an abstract class that take character input rather than byte input, which is explained with

the help of example:

import java.io.*;

public class ReaderExample {

public static void main(String[] args) {

Page 309: Self Learning Material Programming in Java

303

try {

Reader reader = new FileReader("file.txt");

int data = reader.read();

while (data != -1) {

System.out.print((char) data);

data = reader.read();

}

reader.close();

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

16.10 Writer Stream

Writer is an abstract class that takes character as an output which is further, explain with an

example:

importjava.io.FileWriter;

public class FileWriterExample {

public static void main(String args[]){

try{

FileWriterfw=new FileWriter("D:\\testout.txt");

fw.write("Welcome to javaTpoint.");

fw.close();

}catch(Exception e){System.out.println(e);}

System.out.println("Success...");

}

Page 310: Self Learning Material Programming in Java

304

}

16.11 Random Access File

RandomAccessFile class file is like a large array of bytes stored in the file system. Using a random

access file, we can read from a file as well as write to the file. Reading and writing using the file

input and output streams are a sequential process. Using a random access file, we can read or write

at any position within the file. Instances of this class support both reading and writing to a random

access file. How it works:

RandomAccessFileraf = new RandomAccessFile("randomtest.txt", "rw");

The following program shows how random file works:

importjava.io.File;

importjava.io.IOException;

importjava.io.RandomAccessFile;

public class Main {

public static void main(String[] args) throws IOException {

String fileName = "randomaccessfile.txt";

File fileObject = new File(fileName);

if (!fileObject.exists()) {

initialWrite(fileName);

}

readFile(fileName);

readFile(fileName);

}

public static void readFile(String fileName) throws IOException {

RandomAccessFileraf = new RandomAccessFile(fileName, "rw");

int counter = raf.readInt();

String msg = raf.readUTF();

System.out.println(counter);

System.out.println(msg);

incrementReadCounter(raf);

raf.close();

}

Page 311: Self Learning Material Programming in Java

305

public static void incrementReadCounter(RandomAccessFileraf)

throwsIOException {

longcurrentPosition = raf.getFilePointer();

raf.seek(0);

int counter = raf.readInt();

counter++;

raf.seek(0);

raf.writeInt(counter);

raf.seek(currentPosition);

}

public static void initialWrite(String fileName) throws IOException {

RandomAccessFileraf = new RandomAccessFile(fileName, "rw");

raf.writeInt(0);

raf.writeUTF("Hello world!");

raf.close();

}

}

Check your progress

Q1) Write a program to enter byte stream into a file.

Q2) Using which class we can save primitive data types directly into the file?

Q3) How RandomAccessFile is different from other classes? Explain with suitable

example

Solution:

Page 312: Self Learning Material Programming in Java

306

Ans1)

importjava.io.FileInputStream;

public class DataStreamExample

{

public static void main(String args[])

{

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;

while((i=fin.read())!=-1){

System.out.print((char)i);

}

fin.close();

}

}

}

Ans2) Data Output Stream.

Ans3) RandomAccessFile class file is like a large array of bytes stored in the file system. Using a

random access file, we can read from a file as well as write to the file. Reading and writing using

the file input and output streams are a sequential process.

RandomAccessFileraf = new RandomAccessFile("randomtest.txt", "rw");

16.12 Summary

Page 313: Self Learning Material Programming in Java

307

Java programs performs Input and Output operations using Streams. Whereas Stream is an

abstraction which either produce or consume information. Java supports many I/O streams. All

streames behave in the same manner like: ByteStream, CharacterStream, File Input and Output

Stream, DataInputStream and DataOutputStreams which are all discussed and how they are little

bit different from each other.

16.13 References

1. Java The Complete Reference, 8th Edition, Herbert Schildt, Tata Mcgraw-Hill Edition.

2. Head First Java, 2nd Edition, Siyan, K/Bates, Oreilly.

3. Programming Java, 4th Edition, E Balagurusamy, Tata Mcgraw-Hill Edition.

16.14 Model questions

Q1) Explain about InputStream and OutputStream classes.

Q2) Explain about Reader and Writer classes.

Q3) How RandomAccessFile is different from other classes? Explain with suitable

example.