Programming in Java: Self Learning Material
Programming in Java: Self Learning Material
Programming in Java
(BSBC 502)
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
CONSTANTS, VARIABLES AND DATA TYPES:- Introduction; Constants; Variables; Data Types;
Variables, Constants, Standard Default Values.
SECTION-B
SECTION-C
SECTION–D
JAVA AWT: -Java AWT package Containers; Basic User Interface components; Layouts.
File Output Stream, Data I/P and O/P Streams, File Class, Reader and Writer Streams, Random Access
File).
SuggestedBook:
3. 33
Overview of Java Language Aarti, ACET Amritsar
Reviewed By
Pankaj Deep Kaur, GNDU Regional Campus,
Jalandhar
Programming in 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
1
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.
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).
2
Figure 1.1 a. James Gosling. 1. b Java Logo used by Sun Microsystems. 1.c Java logo
by Oracle
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.
3
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.
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.
4
Que. 4.Outline major differences between C++ and Java?
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 :
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
5
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.
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
6
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.
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.
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.
7
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.
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.
8
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.
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.
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.
9
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
10
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.
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.
11
Ans. 8.An array of String type.
Ans. 10.Inheritance.
12
BSBC-502
Programming in Java
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
13
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
14
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.
15
Release date –January 23,1996
JDK 1.0
Originally called Oak
16
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.
17
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.
C++
Java
application
application
JVM
OS OS
18
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.
19
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.
20
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.
Client 2
Windows XP
Android
Desktop
Client 3
Mobile
Internet
Server 3
Windows
Client 1
Windows 7 Client 4
Mac
Laptop
Tablet PC
21
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.
22
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.
23
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.
24
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.
25
unaware applied in a virtualized environment which underlying that the platform has been
virtualized.
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
26
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.
27
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
28
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
29
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.
30
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.
31
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.
32
BSBC-502
Programming in Java
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
33
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.
34
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.
35
Running a java program
Hello world
During compilation, full name with extension is used . While running a program, only class
name is used.
36
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.
37
}
}
class Square
{
public int side;
public int area()
{
return this.side*this.side;
}
}
class Classname
{
public static void main (String[] arguments)
{
Statements
}}
38
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.
39
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
40
void push(int item); // Insert item into 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");
}}
41
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.
42
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.
43
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.
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
44
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.*;
45
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
46
welcome
47
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.
48
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
49
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.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.
50
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.
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.3 Initialization
Declaration of variables as close as possible to where they are
used.
51
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
52
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.
BSBC-502
Programming in Java
53
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
54
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.
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.
55
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.
56
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?
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
57
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.
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.
58
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 :
59
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
60
is 15 digits after decimal. Examples of use of double data type are : radius of earth in
inches, area of a nano organism etc.
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.
4.5 Constants
61
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.
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.
62
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.
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.
63
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.
These statements will be explained in detail in Lesson 4 Control Structures – Branching and
lesson 5 Control structures -Looping.
64
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.
65
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.
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.
Ans 1.C++ uses preprocessor directives #include, and java uses import statement.
66
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 9.Different reference types in java are class, interface and array.
Ans 12. d
Ans 13. a
Ans 14. b
Ans 15. c
67
4.14 Model Questions
68
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
69
5.0 Objectives
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.
70
There are variety of operators in Java, which are explained below:
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.
71
Ques 1. What is difference between an operator and an operand?
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
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.
72
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
73
Comparison == double equal Checks if x is equal to y, Left to Right
to written as x = = y
Not equal to != Sign of Checks if x is not equal to Left to Right
exclamation, y, written as x != y
equal to
74
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.
75
Decrement -- minus minus subtracts one from Right to Left
value of a existing value of a
variable variable
Example :5 | 7 will work as 00000101 & 00000111 it gives 00000111 i.e.7. Note that 5 || 7 will
give result as 1.
76
Ques 9. Which are various bit-wise 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.
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’.
77
If then else ?: Question To evaluate one of two Right to Left
mark and operands on the basis of a
colon condition given by first
operand.
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.
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.
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.
78
Mathematical expression Java Expression
(x+y)/z
( + ) Math.sqrt(x+y)
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.
79
Fig. 5.1 : Operator precedence chart [source:
http://www.tutorialspoint.com/java/java_basic_operators.htm]
80
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
81
5.10 Answers to Check Your Progress / Self Assessment Questions
82
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 ;
83
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
84
6.0 Objectives
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.
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.
85
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”.
true
Condition
al
Group of statements
86
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>
}
False True
Condition
87
al
Figure 6.2 Flow chart of if-else statement
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
88
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
False if else statement is shown in fig. 6.3.
Condition1 Statement Group-1
True
False
Condition Statement Group-2
True
False
Condition Statement Group-3
True
Statement
Next Statement
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();
89
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
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.
if(condition-1)
statement group 1
else if(condition-2)
statement group 2
else if(condition-3)
statement group 3
90
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.
True
Condition1 Statement Group 1
False -
True
Condition2 Statement Group 2
False
True
Condition3 Statement
- Group 3
False
Statement Group 4
Next Statement
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 ;
91
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
92
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.
Expression
Nextstatement
93
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.
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) : ");
94
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:
95
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 !!
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
96
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.
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. 8.The default statement block is used to execute the statements when no label match with
the switch variable.
97
6.7 Model Questions
98
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
99
7.0 Objectives
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
100
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>
}
True
condition Body of Loop
False
Next 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.
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 ;
101
i++ ;
}
mean = sum / n ;
System.out.println("Value of Mean = " + mean);
}
}
Output
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
102
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) ;
Group of Statementsfalse
trueNe
condition
False
Next
103
{
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
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
104
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.
initialization
False
condition
True
Group of -
statements
update expression
Next Statement
105
{
System.out.println(n+" X "+i+" = "+(n*i)) ;
}
}
}
Output
Enter a Number : 7
7X1= 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
Output
Enter a Number : 75
106
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
107
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
{
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( ; ; ) { }
108
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
109
j=j + i ;
j- - ;
}
System.out.println(“J=” + j ) ;
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
:
start of loop
:
Loop body
Example
class BreakLoopDemo
{
public static void main(String args[ ])
{
for(int i=2; i<100; i = i+2)
{
110
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
:
start of loop body
Normal flow
:
Loop body
For example:
class ContinueLoopDemo
{
public static void main(String args[ ])
{
int sum = 0 ;
for(int i=1; i <= 50 ; i++)
111
{
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
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.
112
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.
113
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
114
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.
Que. 1. What is meant by iterative code? What is difference between entry controlled loop and exit
controlled loop?
Que. 5. Write a program to display first n elements of Fibonacci series using while loop.
115
Que. 8. Write a program to find factorial of a number using for loop and while loop.
116
BSBC-502
Programming in Java
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
117
8.0 Objectives
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.
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 ;
……………….
118
type varname_N ;
{ <method body>
<method body>
<method body>
As shown in the above class definition, the body of a class usually consists of instance variable
and methods.
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:
119
class Employee
int empNo ;
String EmpName ;
double basicSal ;
The class Employee declared above contains three instance variables, empNo, EmpName and
basicSal.
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 ;
For example, the class Employee as shown above is extended and contains a method findTax( )
as illustrated below:
120
class Employee
int empNo ;
String EmpName ;
double basicSal ;
void findTax( )
double tax ;
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
121
Check Your Progress / Self Assessment Questions
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..
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.
int rollno ;
double marks ;
122
ob.rollno = 1001;
ob.marks = 567;
double 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 ;
123
Student(int r, String n, double m)
rollno = r ;
name = n ;
marks = m ;
double findPercentage( )
double result ;
return result ;
class studentDemo
Student s1, s2 ;
124
Check Your Progress / Self Assessment Questions
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.
Superclass
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:
125
{
// members that are specific to subclass and are not persent in superclass
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.
class SuperClass
{ double a, b ;
SuperClass(double m, double n)
{ a=m;
b=n;
void print( )
{ double c ;
{ super(m,n) ;
126
c=o;
void mean( )
{ double result ;
result = (a + b+ c ) / 2 ;
class ConstructorDemo
sup.print( ) ;
sub.print( ) ;
sub.mean( ) ;
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.
127
GrandParent
Parent
Child
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:
Parent
128
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) ;
129
sub.mean( ) ;
}
}
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
// Method body
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.
void print( )
130
{
131
simple types. All the wrapper classes reside in java.lang package and its hierarchy is depicted in
Fig. 8.4.
Number
132
Check Your Progress / Self Assessment Questions
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( ) ;
}
}
133
abstract class AbstractClassName
{
abstract void print( ) ; // abstract method
void display( )
{ // code here
}
}
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 :
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.
134
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
1) Marker Annotation : This is type of annotation that does not have any method in its body. For
example:
@interface MyAnnotation{}
2) Single-Value Annotation : This is type of annotation that has one method definition in its
body. For example:
@interface MyAnnotation
{ int value( );
@interface MyAnnotation
3) Mulit-Value Annotation : An annotation that has more than one method defined in its body, is
called Multi-Value annotation. For example:
135
@interface MyAnnotation
{ int val1( );
@interface MyAnnotation
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) ;
}
136
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) ;
}
}
137
{
public static void main(String args[])
{
NestingMethod ob = new NestingMethod( ) ;
ob.max(16,19);
}
}
138
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.
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
139
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.
Ans1.A class is a structure or blueprint of the object, whereas an object is the physical
implementation of a class.
140
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 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
141
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 ?
142
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
143
9.0 Objectives
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.
144
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.
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.
145
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.
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]);
146
}
}
Output
Value of fourth element 30.9
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 } ;
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 ;
147
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
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
148
int[ ][ ] and is assigned to the variable arr2D. Each element of this array is again an array of
typeint[ ]. It dynamically allocates 3 arrays of integers each of which stores 5 elements of type
integers. The array of 3 elements created in the previous step holds the references of these 3 arrays.
The 5 elements in each of these 3 integer arrays are initialized to their default value of 0.The above
steps are shown diagrammatically in fig. 7.2. In a two dimensional array, the number of rows is
given by arr2D.length and the number of values in each ithrow is given by arr2D[i].length.
Arr2D
a[0] 0 00 0 0
0 00 0 0
a[1] 0 00 0 0
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
149
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.
150
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.
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( ));
Output
Initial size: 0
Initial capacity: 4
Capacity after addition of four elements: 4
Current capacity: 7
Current capacity: 7
151
\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.
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)
152
Creates a string str3 with string “BC”. Each byte value is converted to its equivalent
character.
Creates a string str5 with sub-string “cde”. Please note that index always starts from 0.
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)
class StringArrayDemo
{
153
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
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.
154
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.
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) ;
155
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.
156
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:
157
Check Your Progress / Self Assessment Questions
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.
byte shor
158
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:
Output
args[0]: Passing
args[1]: arguments
args[2]: at
args[3]: command
args[4]: line
159
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
Ans1. length
Ans2. Yes
160
Ans3. Yes
Ans 5.length( )
Ans 6. Yes
Ans7. String.concat( )
Ans 11. b
Ans 12. c
Ans 13. c
Ans 14. b
BSBC - 502
Programming in Java
Unit-3 Lesson - 10 Interfaces
161
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
162
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.
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
163
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.
164
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.
165
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) ;
166
}
}
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.
167
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.
168
int empid, deptid;
long basicSalary;
int experienceInYears, SpecialIncrement ;
long totalsalary, long totalbonus ;
169
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.
170
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 );
171
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
Ques 6. Can a class do both the things i.e. implement an interface and extend a class?
172
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.
173
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) ;
174
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.
175
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) ;
}
}
176
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.
177
//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.
a. method defination
c. method declaration
178
a. mandatory
b. optional
c. necessary
a. key
b. keyword
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
179
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.
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.
180
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 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
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?
181
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
182
11.0 Objectives
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.
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.
183
Figure 11.1. Inbuilt or System 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.
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.
184
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.
For example, to include or import every class of awt package, it can be written :
import java.awt.* ;
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.
Ques 2. Which statement does java provide to include a package in java program?
185
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.
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.
186
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
187
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.
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?
188
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.
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
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
189
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.
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 :
190
Example : To access a public class from a package
Once an object of the class is created, it can easily use methods of the class defined in the 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.
191
Protected access specifier will allow access from within the same class, package and any
of its subclasses.
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.
192
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.
Ans1. Java.lang package is the only package that is included in every program by default.
Ans. 4. There are many ways in which import statement can be used, some of these are :
Ans 5. False.
Ans 6. Option –d is used with javac command to place class files in a particular folder
193
11.13 References / Suggested Readings
194
BSBC - 502
Programming in Java
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
195
12.0 Objectives
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.
196
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.
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
197
impression about the developer. So, Java provides an elegant way of dealing with run time errors
called exceptions, it called exception handling.
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).
198
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”.
Example
public class exception1
199
{ 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)
200
{ System.out.println("Sorry, an exception occured, ");
}
System.out.println("Bye");
}
}
201
ArrayIndexOutOfBounds, Program terminating....
Bye
202
{
}
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.
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
203
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.
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
204
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
205
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.
206
{ 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( ));
}
}
}
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
207
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.
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
208
Ans 2. Compile time error.
Ans 3. False. (there must be one or more catch blocks after try)
Ans. 4. False.
Ans. 7. False. It is not compulsory, if not defined, it will be used from parent class.
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.
209
BSBC - 502
Programming in Java
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
210
13.0 Objectives
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.
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.
211
Check Your Progress / Self Assessment Questions
Exercise - I
import java.applet.* ;
import java.awt.* ;
// 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.* ;
212
{
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.
Exercise - II
Ques 3. Which packages are required to create an applet ?
Ques 4. Which class will be inherited to create an applet?
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
213
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.
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
214
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:
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.*;
215
msg += "Init method " ;
g.drawString(msg,40,20);
Output
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.
216
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
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.
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
217
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
218
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>
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 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.
219
width The width 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?
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>
</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.
220
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.
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.
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.
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
221
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.
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
String msg = "Hello Everybody..." ;
222
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>
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:
223
import java.applet.*;
import java.awt.*;
if (msg == null)
msg = arg ;
<HTML>
<HEAD>
</HEAD>
<BODY>
</APPLET>
</BODY>
</HTML>
224
Output
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?
225
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.
CODEBASE
226
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
227
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.
<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);
}
}
228
</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
229
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.*;
230
{
setBackground(Color.white) ;
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
231
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
232
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?
233
…………………
<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) ;
}
}
234
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
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.
Exercise - VII
Ques 3. Which attributes of an applet tag are used to send arguments to an applet?
235
Ques 4. Is there any limit to number of arguments send to an applet?
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">
236
var browserUsed = navigator.appName;
if (browserUsed == 'Mozilla')
'height="100", 'width="250"'>',
'</OBJECT>');
else
</script>
</html>
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?
237
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
238
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) ;
}
}
catch(Exception e) { }
result = ( phy + chem + math) / 300 * 100 ;
g.drawString("The percentage is "+result, 150,125) ;
}
239
}
Output
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:
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
240
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
Exercise I-V
Ans1. True
Ans2. True
241
Ans 6. void init( )
Ans 7. The <script> tag is used to declare scripting languages such as JavaScript.
Exercise VI-IX
Ans2. Pixels
Ans 4. No
Ans 5. HTML5.
Ans 6. <object>
242
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?
243
BSBC-502
Programming in Java
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:-
244
In this topic we are going to learn how we can draw lines, rectangles, ellipse, circles and arcs using
various methods.
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 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: -
245
Figure 11.1
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)
Example: -
//Program to create rectangles
importjava.awt.*;
246
importjava.applet.*;
/*
<applet code="rectangles" width =400 height=500>
</applet>
*/
public class rectangles extends Applet
{
}
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 ()
247
Methods are shown below
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 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: -
248
Figure 11.3
As shown in example we have mentioned the co-ordinate same as.
drawArc ()
fillArc ()
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.*;
249
importjava.applet.*;
/*
<applet code="Arc" width =300 height=300>
</applet>
*/
public class Arc extends Applet
{
}
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.
250
Check your progress/ Self-assessment questions
Exercise-I
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)
import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
251
{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}
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
public XYLineChartExample() {
super("XY Line Chart Example with JFreechart");
252
setSize(640, 480);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
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.*;
253
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> */
254
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.
import java.applet.*;
import java.awt.*;
/*
<applet code = "BarChart.class" width=400 height=400>
</applet>
*/
year[0] = getParameter("year0");
year[1] = getParameter("year1");
year[2] = getParameter("year2");
year[3] = getParameter("year3");
year[4] = getParameter("year4");
255
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"));
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.
256
Exercise-I
Answer 4. drawOval() method draw an oval on specified co-ordinates whereas fillOval() method
fills that oval with a color.
257
Chapter-15 Java AWT and Event Handling
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
258
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.
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.
259
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.
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.
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 :
class Demo
260
{
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:
class Demo
{
261
f.setSize(400,200);
f.setLayout(null); //Setting Layout this will be explained further
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.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:
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.
262
For example:
class Demo
{
f.setVisible(true);
}
Output:
263
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 :
class Demo
{
f.add(b);
f.setVisible(true);
}
264
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.
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
265
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.
importjava.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
266
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.
267
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:
268
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:
269
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.
270
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)
271
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.
importjava.awt.*;
272
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:
273
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.
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:
274
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.
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
275
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
newMyFlowLayout();
}
}
Output:
276
Check your progress / Self-assessment questions
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();
277
Ans 3)
importjava.awt.*;
importjavax.swing.*;
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();
}
}
278
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
279
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.*;
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);
}
}
280
importjava.awt.*;
importjava.awt.event.*;
publicAwtListenerProgram (){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
281
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
controlPanel.add(panel);
mainFrame.setVisible(true);
}
282
// Code to be executed when mouse is clicked
}
public void mouseEntered(MouseEvent me)
{
// Code to be executed when mouse is entered
}
importjava.awt.*;
importjava.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
283
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();
}
}
importjava.awt.*;
importjava.awt.event.*;
MouseMotionListenerExample(){
addMouseMotionListener(this);
284
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) {}
285
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");
}
286
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.*;
287
public static void main(String args[])
{
newItemListenerExample();
}
}
Q1) How many methods need to be override when we are using MouseListner Interface.
Solution:
288
// Code to be executed when mouse is pressed
}
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.
289
15.14 Model Questions
290
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
291
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
292
Marking position in streams
Finding the number of bytes in a stream
Skipping ahead in a stream
Reading Bytes
Closing Streams
293
InputStream is = null;
int i;
char c;
try {
System.out.println("Characters printed:");
// prints character
System.out.print(c);
}
} catch(Exception e) {
Output:
Let us assume there is test.txt file which is having chetan in it then the output will be
Characters printed:
Chetan
294
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
295
public abstract class OutputStream
extends Object
implementsCloseable, Flushable
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”);
The following example tell us how to read a single byte, an array of bytes, and a sub range
array of bytes.
importjava.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
296
System.out.print((char)i);
fin.close();
}
catch(Exception e){System.out.println(e);
}
}
}
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();
}
}
}
297
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:
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);}
}
}
importjava.io.FileOutputStream;
298
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);
}
}
}
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)
299
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(String filepath)
FileOutputStream(File fileObj)
FileOutputStream(String filepath, Boolean append)
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;
300
System.out.print(k+"-");
}
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...");
}
}
301
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) {
302
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());
}
}
}
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...");
}
303
}
importjava.io.File;
importjava.io.IOException;
importjava.io.RandomAccessFile;
if (!fileObject.exists()) {
initialWrite(fileName);
}
readFile(fileName);
readFile(fileName);
}
System.out.println(counter);
System.out.println(msg);
incrementReadCounter(raf);
raf.close();
}
304
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);
}
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:
305
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();
}
}
}
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.
16.12 Summary
306
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.
307