Java PTU
Java PTU
Programming in Java
(MCA-201)
Syllabus
I.K. Gujral Punjab Technical University
PDCA-201Programming in Java
SECTION-A
FUNDAMENTALS OF OBJECT-ORIENTEDPROGRAMMING:-Introduction, Object-Oriented
Paradigm,BasicConceptsofObject-OrientedProgrammingBenefitsofOOP,Applications of
OOP.
How
JavaDiffersfromCandC++(Javacharacterset,Keywords,Identifiers,Literals,
Operators, Separators), DECISIONMAKINGAND LOOPING:-Introduction, The while
Statement,
ThedoStatement,TheforStatement(Additionalfeaturesofforloop,Nestingofforloops),
Jumps inLoops(Jumpingoutofaloop,Skippingapartofaloop),LabeledLoops.CLASSES.(10)
SECTION-B
OBJECTS AND METHODS:-Introduction, Defining a Class, Adding Variables, Adding
Variables, Adding Methods, Creating Objects, Accessing Class Members,
Constructors, Inheritance: Extending a Class (Defining a subclass, Subclass constructor,
Multilevel inheritance, Hierarchical inheritance), Overriding Methods, Final Variables and
Methods, Final Classes, Finalizer Methods.
ARRAYS, STRINGS AND VECTORS: - Arrays, One-Dimensional Arrays, Creating an Array
(Declarationofarrays,Creationofarrays,Initializationofarrays,Arraylength),Two-Dimensional
Arrays(Variablesizearrays),Strings(Stringarrays,Stringmethods,StringBufferclass),Vectors,
Wrapper Classes. INTERFACES: Introduction, Defining Interfaces, Extending Interfaces,
Implementing Interfaces, Accessing Interface Variables.
SECTION-C
PACKAGES: Introduction, System Packages, Using System Packages, Naming Conventions,
CreatingPackages,AccessingaPackage,UsingaPackage,AddingaClasstoaPackage,Hiding
Classes.MANAGINGERRORSANDEXCEPTIONS:-Introduction,TypesofErrors(Compile-time error,
Run-time error), Exceptions, Syntax of Exception Handling Code, Multiple Catch
Statements, Using finally Statement, Throwing Our Own Exceptions, Using Exceptions for
Debugging.
SECTION-D
APPLETPROGRAMMING:-Introduction, How Applets Differ from Applications, Preparing to
Write Applets, Building Applet Code, Applet Life Cycle (Initialization state, Running State, Idle
or stopped state, Dead state, Display state), Creating an Executable Applet, Designing a Web
Page (Comment Section, Head Section, Body Section), Applet Tag, Adding Applet to HTML
File, Running the Applet, More About Applet Tag, Passing Parameters to Applets, Aligning the
Display, More about HTML Tags, Displaying Numerical Values, Getting Input from the User.
SuggestedReadings/Books:
1.EBalagurusamy,ProgrammingwithJava, 4th Edition2010.
2.HebertSchildt,Java the Complete Reference,8th Edition2011.
3.BruceEckel,ThinkinginJava,KalyaniPublishers,4th Edition2011.
TableofContents
ChapterNo.
1
2
3
4
5
6
Titl
e
Written By
Page No.
15
45
61
81
107
126
145
160
Fundamentals of Java
Java building blocks
Operators and Expressions
7
Array, Vectors and string handling
8
Interfaces
9
Packages
10
Exception handling
11
Introduction to applets
12
Advanced Applet Programming
30
177
197
Reviewed By
Pankaj Deep Kaur, GNDU Regional Campus,
Jalandhar
IK Gujral Punjab Technical University Jalandhar
All rights reserved with IK Gujral Punjab Technical University Jalandhar
PDCA-201
Programming in Java
Unit-I.
Lesson 1.
Fundamentals of Java
Chapter Index
Objectives
Introduction
1. Introduction to Java
Relation between C, C++ and Java
Features of Java
Important Java Terminology
i. Bytecode
ii. JDK
iii. JVM
iv. JRE
2. Object Oriented Paradigm
3. Basic Concepts of Object Oriented Programming
4. Benefits of OOP
5. Applications of OOP
6. Summary
7. Glossary
8. Answers to Check Your Progress / Self Assessment Questions
9. References / Suggested Readings
10. Model Questions
Objectives
Introduction
Java is one of the most popular general purpose programming languages today. It is based on
object oriented programming paradigm, which itself is one of the most common programming
paradigm. Java source code is compiled into byte code which java interpreter is able to execute.
Java offers many special features like platform independence, supports multithreading and offers
applets. Four basic principles of object oriented programming are data abstraction, encapsulation,
inheritance and polymorphism.
Introduction to Java
Java is one of the very few pure object oriented programming languages and was created by
James Gosling at Sun Microsystems Inc. in 1990. The basic idea behind Java was to develop a
language that is much simpler than C++ and offers much wider scope than C++. It was originally
termed as Green Project and the team who created it was called Green Team. Later in 1991,
it was renamed Oak. Again in 1992, it was renamed Java. In January 2010, Sun Microsystems
was taken over by Oracle Corporation, therefore now, java belonged to Oracle, and following
this James Gosling resigned from Sun.
Java is a simple, portable, platform independent; pure object oriented language well suited to
design various types of applications. The applications comprise of designing CUI, GUI and web
applications (client side as well as server side), mobile applications, multimedia applications
etc.Apart from that, a special type of application known as appletcan be created in java that can
run inside a web browser.. Unlike C or C++ which are compiler based, Java uses a combination
of both interpreter and compiler. First of all java program is compiled by java compiler (javac) to
create a bytecode and then bytecode is executed by java interpreter called JVM (Java Virtual
Machine).
Features of Java
1. Simple :Java is a compact and simple language than C++. Many confusing features of
C++ like pointers, multiple inheritance, virtual functions, structure, union, operator
overloading etc. have been not been included in Java.
2. Platform Independent :Java is a platform independent language, so its programs can be
designed to run in a similar manner on multiple operating systems. In other
programming languages like C/C++, a program written on a machine with Windows OS,
can not be run on a different machine with Unix or Mac OS. But this problem does not
happen with Java. Java achieve this independence using its virtual machine called JVM
3.
4.
5.
6.
7.
(Java Virtual Machine). There exists a separate JVM for each OS.Pure Object Oriented
Language: In Java, everything is considered as an Object. Java posseses all the features
of a pure object oriented language, like Abstraction, Inheritance, Polymorphism etc. . An
extensive inbuilt class library in the form of API is available in Java. Further, no program
can be written in Java without the concept of a Class.
Robust :Here robust means reliable. Early checking of bugs happen in java which may
otherwise lead to run time errors and may cause a program to crash. Java also provides
strong type checking and has a run time exception handling feature . Another feature of
automatic garbage collection makes it more reliable.
Distributed :Java is a distributed language which means an application developed in
Java can be run on a network also. This is made possible by networking related API
provided by Java. It makes network communication from within an application very easy.
Automatic memory management: Java provides its own garbage collector, and
therefore memory management (memory allocation and de-allocation) is the
responsibility of JVM and programmer does not have to worry about it. JVM runs a
separate thread of garbage collector when any java application runs.
Multithreading: Java provides the feature to create multithreading based applications
and allows to run multiple threads of execution to run concurrently within the same
application. This improves the performance of an application.
Java Bytecode :A java program is not translated to native machine language. Rather it is
translated to java bytecode by java compiler (javac) which is later interpreted and
executed by java virtual machine.
also for web applications and mobile applications. Relation between C, C++ and Java can be
depicted from following figure.
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 :
//class definition.
Public static void main(String args [ ] )
{
//body of main
System.out.printl (Hello World !) ;
}
Java program can be written in any text editor like notepad. Type above program in a text file
and save the file as HelloWorld.java. All java program body is written inside a class. Note that
name of the class (having main method in it) must be exactly same as name of text file. When
this java program is compiled, a HelloWorld.class file is created which can be run by java. A
java program can contain multiple class files but only one class is allowed to have main method
in it. Also note that main method takes an argument of String type array. This can be used while
working with command line arguments.
Why is main () public static and void method?
First note that main is a method and belongs to a class. This main () method cannot be written
outside a class. It is declared to be public method of the class so that it can be called from
anywhere. It is static so that it can be called even without creating an object or instance of the
class. It is void which means it does not return anything.
popular paradigms are Imperative, Logical, Functional and the topmost popular one i.e. Object
Oriented.
In OO programming paradigm, the focus is on the real world entities and data ,around which the
problem revolves rather than on coding the solution. A problem is viewed as a group of
interacting entities called objects which are organized into classes.(A class is a template and an
object is an instance of the class). To develop an effective solution, developer tries to understand
the properties/features of objects and operations that can be performed on those objects. In object
oriented terminology, properties/features of objects are known as data members and operations
are known as member functions. Once objects, their features and their operations are well
understood , more effective solution can be developed with fewer efforts as compared to efforts
needed in other programming paradigms. Even a large and complex problem can be easily
understood and well managed in object oriented paradigm.
An example of real world entity is CAR, its features can be like Make, Model, FuelType,
SeatingCapacity etc. and operations that can be performed on a CAR can be, Drive(), Refill(),
FindSpeed() etc. This is shown in figure 1.3.
Class Vs Object: A class is a template using which objects or instances of the class are created.
All objects belonging to the same class have same feature set but distinct values. Each object is
distinct, and has separate representation in memory.
User interface design : Interface of many popular applications and even popular operating
systems like windows is developed using object oriented programming languages.
CAD (Computer Aided Design) :Software engineers can prepare 2-D and 3-D designs of
their products like automobiles etc. using CAD. CAD software isitself based on object
oriented paradigm.
Compiler Designing : A compiler is a type of system software that translates high level
language program to machine language. Coding a compiler is very easier in Object
oriented programming language like C++.
CASE Tools
10
Summary
Java developed by James Gosling, originally belonged to Sun microsystem, now currently owned
by Oracle Corporation. It is a pure object oriented language with features like Compact, robust,
distributed, automatic garbage collection, multithreading. It does not possess confusing features
of C++ like multiple inheritance, pointers etc.. Various types of applications can be created in
java like desktop applications (CUI and GUI), web application, mobile applications etc. It is
based on Object Oriented Paradigm which makes management of complex and large code more
manageable. Object oriented paradigm is based on four basic pillers viz data abstraction,
inheritance, polymorphism and Encapsulation.
11
Glossary
JVM: Java Virtual Machine. Part of java which makes java platform independent.
Applet : Small programs written in java which can be run in any web browser or in a
small utility software which is part of Java Development Kit (JDK) called applet viewer.
JDK : Java Development Kit, a software bundle that comprises many small software to
install Java and develop java applications.
JRE : Java Run time Environment. Part of JDK, required to run java applications.
Bytecode :Java byte code is language understood by java virtual machine. Any java
source code is translated to java bytecode by java compiler and is run by java virtual
machine.
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.
12
13
Model Questions
14
PDCA-201
Programming in Java
Unit-1.Lesson-2.
Chapter Index
Objectives
Introduction
Data types
Constants
Operators
Expressions
Summary
Glossary
Model Questions
Objectives
To learn about keywords, identifiers, literals, operators and character set of Java.
15
Introduction
Though both C++ and Java are object oriented programming languages and java is a superset of
C++, still there are many major differences between java and C++. In this lesson, we will study
about these differences, character set, various data types, identifiers and operators of Java
language. Also, it will be explained which are many flow control statements in Java. Valid rules
and conventions to form legal identifiers, scoping rules of variables etc. will also be explained.
Java is a pure object oriented language whereas C++ is a weak object oriented language.
Java uses a combination of both, compiler and interpreter. Firstly java source code is
compiled by java compiler into bytecode, and then this bytecode is interpreted by java
interpreter, JVM. But C++ is purely a compiler based language. C++ source code is
compiled by compiler into machine language.
In C++, main method may exist even outside a class, and a program can be created
without any class, but in Java everything has to be inside a class. A program cannot be
written in Java without a class.
In C++, there can be class methods and c-style functions also. But in Java there are no
functions, only methods are available inside a class..
C++ has signed and unsigned data types. There are no such unsigned data types in Java.
There are no structures, unions, and pointers in Java; also, there is no typedef keyword as
found in C++.
C++ has preprocessor directives, like #define and # include, but Java does not use the
concept of preprocessor directives.
C++ has class and function templates, Java does not have templates.
16
C++ uses const keyword to create non-modifiable constants, java uses final keyword for
this purpose, and there is no const keyword in Java.
C++ supports multiple inheritance, Java does not support multiple inheritance.
C++ has goto statement to jump from one part of program to another part, Java does not
use goto keyword for jumping.
Java has labeled breaks and labeled continue, but these are not found in C++.
Java provides feature of automatic memory management. Java has its own garbage
collector which performs memory de-allocation of unused objects. But in C++, memory
de-allocation is pure responsibility of C++ programmer.
C++ uses the syntax of main method as main(int argc, char *argv[]) where as java uses
main method as main(string args[]) but uses command line arguments in different ways.
Further, C++ uses two syntax for main, main( ) and main(int argc, char *argv[]), but java
uses only one syntax of main method.
Strings are treated differently in C++ and java. A string in C++ is simply an array of char
data type and ends with a NULL. But, in Java, String is a class type defined in java.lang
package.
C++ supports both single and multidimensional arrays, Java does not support multidimensional arrays. To create multi-dimensional arrays in Java, an array of single
dimension array of single dim arrays is created.
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.
Ques 1. How does C++ and Java include library functions in a program?
17
Java Keywords: A keyword is a predefined word that has a specific meaning and purpose in
Java, it cannot be used for any other purpose. There are many keywords in Java, like class,
interface, package main, for, while, if, try, catch, return, import etc. Some keywords like
const and goto are reserved words, it means though they are not currently used but they are
reserved for future.
A list of keywords of Java :abstract, continue, for, New, switch, default, goto, Package,
synchronized, Boolean, do, if, Private, this, break, double, implements, Protected, throw,
byte, else, import, public, throws, case, enum, instanceof, return, transient, catch, extends,
int, short, try, char, final, interface, static, void, class, finally, long, strictfp, volatile, const,
float, native, super, while
Note that all keywords of java are in lower case.
Java Identifiers: It is any user-defined word used to form a variable name, class name,
method name, package name, interface name etc. Identifier means it is used to identify
something in Java. There are some rules to form a valid identifier in Java, like, a keyword
cannot be used as identifier, an identifier name must start with an alphabet, an identifier
name in java is case sensitive (num, Num, NUM and NuM are different) and have no
maximum length. etc.
18
Java Literals: Literal means a constant. Whereas the value of a variablemay change any
number of times in program, a literal once initialized, cannot change. Java Literals are of four
types.
o String Literals: String literal is written by enclosing it in double quotes marks,
for example, Hello World!
o Character Literals: Character type literals are enclosed in single quotes and can
contain only one character. Like for gender we can use M or F, for grade we
can use A , B etc.
o Boolean Literals: Boolean data type has 2 literals, true and false.
o Numeric Literals: A numeric literal is a numeric constant like 123, 123.56 etc.
Java Operators
To perform different types of calculations in programs, java provides different types of
operators. There are three categories of operators, unary, binary and ternary. There are
arithmetic operators for performing mathematical or arithmetic operations, relational
operators for checking relations among operands, logical operators for performing logical
operations, conditional operator to check a condition and return a value,
increment/decrement operators to increment or decrement the value of a variable by 1 etc.
Operators operate on operands which may be variables or literals. Operators when
combined with operands create expressions, which calculate values and results.
Java Separators
19
Separators are some characters from java character set which act as punctuation characters. A
very simple and common example of a java separator is a semicolon(;).It is used at the end of
each statement to signify termination of a statement. Using semicolon as a separator multiple
statements can be written in one line. Other separators used in java are :
a. Parenthesis : for example used to write method arguments.
b. Curly braces : { and }, used to initialize array elements.
c. Brackets : [ and ], used to declare arrays.
d. Comma : used to separate variables in variable declaration, used in for loop to separate
expressions etc.
e. Period (.) : used to call a method on an object.
20
types, Boolean and numeric. Numeric data type is further of two types, integral and floating
point. Integral data type is used for integers or whole numbers, floating point is used with
real numbers.
a) Boolean data type is used to check whether a condition or an expression evaluates to true
or false. There are two Boolean literals true and false. For example, 5<7 gives true, 5==7
gives false.
b) Numeric Data types:
i.
integral data type because each char is represented in memory by its integer Unicode
in the range 0 to 65535.
o byte data type : It is used to represent 8-bit integers in the range -128 to +127.
o short data type: It is used to represent 16-bit integers in the range -32768 to +32767.
o int data type: It is used to represent 32-bit integers in the range -2147483468 to
+2147483467. This range is given by -231 to +231.
o long data type: It is used to represent 64-bit integers in the range -263 to +263.
ii.
Real data types: These are also called floating point data types and are used to
represent real numbers (numbers with decimal point) in memory. It consists of
following types :
o float :float data type is of 4 bytes width. Its range is -3.4x1038 to +3.4x1038 and their
precision is 7 digits. Example of float data type values are : rate of interest, radius of
circle, area of a circle, standard deviation of a series etc.
o double: Sometimes it may be required to represent values larger or smaller than the
range of float. Java provides a bigger data type for this purpose named as double.
Width of double data type is 8 bytes, range is -1.7x10308 to +1.7x10308 and its
precision is 15 digits after decimal. Examples of use of double data type are : radius
of earth in inches, area of a nano organism etc.
21
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.
Constants
22
Constant is a name given to a literal whose value remains same throughout the program.
This is in contrast to a variable whose value may change any number of times in Java.
There are different types of constants in java, as given below:
o numeric constants like 123, 10.5 etc. To create a numeric constant of long type
simply place a L behind it, like 123L.
o Boolean constants like true / false
Java provides a keyword final that lets create a constant. For example, final int num=10 ;
makes num a constant.
Scope of a variable
Scope of a variable is also called visibility of a variable that identifies the locations where a
variable can be accessed within a program. It depends upon where a variable has been
declared. Scoping rules of a variables decide its accessibility in different parts of the
program.
23
o Block level scope : Easiest to understand is block level scope. It means, a variable can
only be accessed inside a block where it is declared and cannot be accessed outside the
block. It is called local variable.
o Function level scope :A variable declared at the top of a function or method can be used
or accessed anywhere inside a method body. Such a variable is said to have function or
method level scope. It is local variable of the function or method.
o Class level scope :Data members declared inside a class are said to have class level
scope.
Example :
class Student
{
int rollno ;
int findMarks( )
{
float total_marks ;
:
:
{
int temp ;
:
:
}
}
}
In this example, rollno has class level scope, total_marks has method level scope and
temp has block-level scope.
Expressions
An expression is a combination of operands and operators. Operands may be
variables,constants or literals. An expression in java is same as a formula in mathematics.
An arithmetic expression is createdusing only arithmetic operations and operands. For
example, num1+num * 5.
24
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.
25
Summary
There are many major and small differences in C++ and Java. Basically, Java is a big superset of
C++ and has much wider scope than C++.
In C++, there can be class methods and c-style functions alsowhereas in Java there are no
functions, only methods (inside class).
C++ has signed and unsigned data types, there are no such unsigned data types in Java.
Java character set is set of different types of characters that can be used to form basic
programming elements like variables, constants, expressions etc. while writing a java program
A keyword is a predefined word that has a specific meaning and purpose in Java, it cannot be
used for any other purpose. There are many keywords in Java.
Java identifier is a user-defined word used to form a variable name, class name, method name,
package name, interface name etc.
To perform different types of calculations in programs, java provides different types of
operators. There are three categories of operators, unary, binary and ternary.
Java provides different data types. Broadly, there are two categories of data types in Java, these
are primitive data types and reference data types. Primitive data types include char, boolean,
byte, short, int, long. Non-primitive data types include array, class and interface.
A java program may need to perform calculations on values, for this values are stored in memory
locations which are accessed in program by names, these are called variables.
Scope of a variable is also called visibility of a variable. It means where a variable can be
accessed within program.
An expression is a combination of operators and operands. Operands may be variables or
constants or literals.
26
. A special type of statements called flow control statements are used to control the flow of
execution of a program.
27
Glossary
Character Set : Permissible set of characters in language, also called building blocks.
Identifiers: used defined names given to class, method, interface, variables etc.
Literals : constants.
28
Model Questions
1. What are the various data types of Java?
2. What are the rules to form a valid identifier?
3. Explain different types of operators available in Java?
4. What is the difference between an operator and a separator?
5. What is an expression? How an expression is formed?
6. What is meant by scope of a variable? Which are different types of scopes?
29
PDCA-201
Programming in Java
Unit-1.Lesson-3.
Chapter Index
Objectives
Introduction
Java Operators
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Assignment Operator
o Bitwise Operators
o Shift Operators
o Increment / Decrement Operators
o Other operators
new operator
instanceof operator
dot operator
Writing mathematical expressions in Java
Summary
Glossary
Model Questions
30
Objectives
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.
31
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.
32
Java Operators :Various types of operators available in Java will be explained now, along with
their associativity.
Arithmetic Operators: Arithmetic operators are those operators which are used to perform
arithmetic operations. There are five arithmetic operators in Java, these are
Operation
Symbol
Used
Multiplication
Symbol
Purpose
Associativity
Multiplies x by y, written
Left to Right
Name
Asterisk
as x * y
Division
Slash
Left to Right
divided by y, written as
x/y.
Remainder
Percentage
Left to Right
is divided by y, written as
x%y
Addition
Plus
Left to Right
x+y
Subtraction
Minus
Subtracts y from x,
written as x-y
33
Left to Right
In an expression, first multiplication, division and remainder are solved, when these are finished,
then addition and subtraction are solved, working on the expression from left to right. This is just
like BODMAS that is taught to us in schools.
(/ is solved next)
= 2 + 12 - 1
(% gives remainder)
= 14 -1
=13
Note that, there is no operator for raise to power. There is a static method given by Math class
for this purpose, it can be used as Math.pow(x, y) to calculate x y
Relational Operator
Relational operators are used to check relation between operands. Relational operators give
answer in true or false only. Relational operators are generally used in decision making
(selection statements) and looping (iterative statements) that will be explained in lesson Flow
Control Statements . There are five relational operators as shown in table below:
Operation
Less than
Greater than
34
Symbol
Used
<
>
Symbol
Name
Less than
Greater than
Purpose
Associativity
Left to Right
Left to Right
Less than or
equal to
<=
Less than,
equal to
Greater than
or equal to
>=
Greater than,
equal to
Comparison
==
Not equal to
!=
double equal
to
Sign of
exclamation,
equal to
Left to Right
Left to Right
Left to Right
Left to Right
Logical Operators
Relational operators are used to check conditions. Sometimes more than one condition is to be
checked or tested. Then two or more relational expressions can be combined using logical
operators. There are three logical operators in Java.
Operation
Logical And
Symbol
Used
&&
Symbol
Name
Double
ampersand
Logical OR
||
Double pipe
sign
Logical NOT
Sign of
exclamation
Purpose
Associativity
Left to Right
35
Left to Right
Left to Right
This expression checks if total income is less than 10,000 AND total bonus is less than 25 % of
total income, here && operator used to join two relational expression, first one is totalIncode <
10000, and second one is totalBonus< totalIncome * .25/100.
Such expressions in which logical operators are used are called logical expressions.
In such an expression, first all arithmetic operators are solved, then relational and finally logical
operators are solved. Final result is always in terms of boolean true or false.
Assignment Operator
Assignment operator is used with most of other operators. Its job is to assign a value to a
variable. It has least precedence. A variable is used at the left side of assignment operator, and on
its right side there can be a variable or a constant or an expression. It has right to left
associativity. It is a binary operator.
Operation
Assigning
value to a
variable
Example :
Symbol
Used
=
Symbol
Name
Equal to
Purpose
Associativity
Assigns a value to a
variable used on left side.
Right to Left
There is one more way in which assignment operator can be used; it is called multi-assignment
i.e. assigning same value to multiple variables. Suppose it is required to assign same value 10 to
three variables x, y and z. It can be performed by writing : x=y=z=10 ;
Increment/Decrement Operators
36
These two are unary operators, increment operator is used to increment value of a variable by
one, that is to add one to value of a variable, and decrement operator is used to decrease the
value of a variable by 1.
Operation
Increment
value of a
variable
Decrement
value of a
variable
Symbol
Used
++
--
Symbol
Name
plus plus
Purpose
Associativity
Right to Left
minus minus
Right to Left
37
Symbol
Used
&
Symbol
Name
Ampersand
Purpose
Associativity
To perform ANDing of
bits of two numbers
Left to Right
bitwise or
Pipe
bitwise not
Tilde sign
bitwise
exclusive or
Caret
Left to Right
Left to Right
Left to right.
Example :5 | 7 will work as 00000101 & 00000111 it gives 00000111 i.e.7. Note that 5 || 7 will
give result as 1.
Ques 9. Which are various bit-wise operators?
Shift operators
There are two shift operators available in Java. These are left shift and right shift. Shift operators
also work on bits of a number and are considered as a type of bitwise operators. When bits of a
number are shifted to left, number gets multiplied by two, and when bits of a number are shifted
to right, it gets divided by two.
Operation
Left shift
Symbol
Used
<<
Right shift
>>
Symbol
Name
less than
symbol used
twice
Greater than
symbol used
twice
Purpose
Associativity
Left to Right
Left to Right.
Example :5 << 1 gives 10. Because when bits of 5 i.e. 0000 0101 are shifted to left once, they
become 0000 1010 and it represents number 10 (ten) in decimal. Similarly, if right shift is
performed on 139 giving binary as 10001011 it would give 01000101 i.e. 69.
Conditional Operator: As already explained, it is the only ternary operator that works on three
operands in Java. It uses symbol ? :. Its syntax is OperandOne ?OperandTwo : OperandThree
First of all, it evaluates first operand operandOne, and, if first operand gives true value, then
second operand operandTwo is evaluated (third operand OperandThree is not evaluated in this
case), but if first operand gives false, then third operand is evaluated (second operand is not
38
evaluated in this case). Actually, conditional operator provides an easy and short hand form of
equivalent selection statement if-else. Example : marksObtained >=60? gradeObtained=A :
gradeObtained=B . In this example, first operand is marksObtained >=60, second operand is
gradeObtained=A and third operand is gradeObtained=B. if marksObtained by student are
greater than or equal to 60 the gradeObtained will be assigned value A, and if marksObtained
by student>=60 returns false, gradeObtained will be assigned value B.
Operation
If then else
Symbol
Used
?:
Symbol
Name
Question
mark and
colon
Purpose
Associativity
Right to Left
Other Operators
Apart from above there are some other special operators available in Java. These are :
new operator : This operator is used to create a new object of a class. It assigns reference of
newly created object to reference value.
ExampleStudent s = new Student ( ) ; where Student is name of a class, s is a reference variable,
new Student( ) given on right side creates a new object
instanceof operator
instanceof operator is a binary operator.It is used to check whether an object is actually an
instance of a class or interface. Its syntax is objectName instanceof ClassName, where
objectName is name of object or instance, and ClassName is name of class. Here it is being
checked whether or not object objectName is an instance of class ClassName or not. Operator
instanceof returns true or false.
Example : s instanceof Student.
39
dot operator is used to call a method on an object or to access a data member with an object. For
example, if totalMarks is a data member and getMarks( ) is a method of Student class, and s is an
object of Student class and then dot operator can be used to access method and data member as
s.getMarks( ) and s.totalMarks.
method of writing expression in Java. Some of the examples are given below in this
regard.
Mathematical expression
Java Expression
(x+y)/z
( + )
x2+y2
x*x + y*y
disc = b2 4 a c
disc=b*b -4 * a *c
( + )
Math.pow(x+a, n)
x<y<z
40
Math.sqrt(x+y)
ci=p*Math.pow(1+r/100, t)
x<y && y<z
41
Summary
Operands are values on which an operation or calculation is performed. These operands may be
direct constants or may be values stored in variables. Operators are specials symbols or
characters which are part of character set of Java language and are used to perform
calculationson operands. Operators indicate type of operation to be performed on operands.
Expressions are formed with the help of operands and operators.
Operator precedence decides which operator will be solved first in an expression involving
different operators. It is also, known as hierarchy of operators. Associativity decides in which
direction operator works in an expression. Most of the operators have associativity from left to
right, but some operators have associativity right to left. Unary Operators work on a single
operand and they have highest precedence among three types of operators. Binary operators
work on two operands at a time. Most of the java operators are binary operators. Ternary
operators work on three operands at a time. The only ternary operator available in Java is
conditional operator.
42
Glossary
Ternary operator: an operator that works on three operands at a time, there is only one
ternary operator in java.
Precedence: order in which operators are applied. Each operator in Java has fix
precedence.
43
Ans. 8.A=b++ will assign current value of b to a and then b will be incremented independent of
a, where as in a=++b, first b will be incremented and then incremented value of b will be
assigned to a.
Ans 9.Bit wise and (&), bit wise or (|), bit wise complement(~) and bit wise xor (^)
References / Suggested Readings
1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I Fundamentals (9th Edition), Prentice Hall
Model Questions
Ques 1. Which are various binary operators in Java?
Ques 2.What is meant by precedence and associativity of an operator?
Ques 3.Explain the various shift operators in Java?
Ques 4.Explain the working of conditional operator in Java.
Ques. 5. Solve following :
i.
Find value of y and z.
x=10 ;
y=x++
z=++x;
ii.
Find value of y and z in :
x=10 ;
y=x<<2 ;
z=x>> 2;
iii.
Find value of y in :
x=10
y=x>=10? 20 : 30 ;
44
PDCA-201
Programming in Java
Unit-2.Lesson-4.
Chapter Index
Objectives
Introduction
Flow Control
Control Structures
Branching (Selection)
Simple if
if else
Nested if
if else ladder
switch
Summary
Glossary
Answers to Check Your Progress / Self Assessment Questions
References / Suggested Readings
Model Questions
Objectives
Introduction
Sometimes it is necessary to add decision making in our Java program. It means enabling our
Java program to decide whether or not to execute a group of statements. This decision may be
taken depending upon some condition. Decision making adds some intelligence to our program.
45
It changes the default behavior of the Java program whereby it executes each and every
statement of program from top to bottom.
Flow Control
In Java, the execution of the program begins with the main( ) method. The main( ) method
contains a group of statements that are executed sequentially one statement after the other. The
program terminates after executing the last statement of the main( ) method. The default
execution of statements can be controlled in a customized way using the controlstatements that
causes the flow of execution to branch or execute a block of statements repeatedly based upon
some condition.
Control Structures
The control statements in Java can broadly be put into three categories namely branching
(selection), iteration (looping), and jump statements. The branching statements chooses between
alternative paths or group of statements depending upon the outcome of a certain condition or
group of conditions. The iteration statements execute a block of statements repeatedly or
multiple times, based on condition. The jump statements are used to shift or transfer the control
to a specific part of the program.
Branching Statements (or Selection Statements)
The selection statements interrupt the normal flow of the program and makes selectionbetween
alternative paths depending upon the conditions outcome value while the program
executes.There are following four types of selection statements in Java, these are:
Simple if Statement
if-else Statement
else if ladder
switch statement
Simple if
The simple-if statement executes a certain piece of code only if a particular condition given with
if statement evaluates to true. If the condition evaluates to false, then no action will be taken
46
and the statements associated with if-block are skipped and the execution starts following the
next statement after the if-block.
if (<conditional expression>)
{
<groupor block of statements>; this is if block.
}
Where
if is a keyword in Java,
<conditional expression>is a boolean expression that evaluates to boolean values true or false.
<Group of statements> denotes compound statement called true part of if is executedonly when
condition is true.
Curly braces ({ and }) denote beginning and end of true block of if.
The flow chart of simple-if is shown in fig. 4.1.
Conditional
expression
expression
false
true
Group of statements
Next statement
Figure 4.1 Flow chart of simple if statement
The use of simple-if statement is demonstrated with the help of an example:
import ava.util.* ;
class SimpleIfDemo
{
public static void main(String[] args)
{
double pay, incomeTax, netPay ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter Basic Pay :");
pay = sc.nextDouble();
incomeTax =0;
netPay = pay ;
if(pay >= 30000)
{
incomeTax = pay * 30 / 100 ;
47
if-else
The simple if statement only executes a group of statements only if a condition or expression evaluates to true.
The if-else statement enables a program to make a selection between two different paths. The if block is
executed only if the condition is true and the else-block is executed only if the condition is false. The if-else
statement has the following syntax:
if (<conditional expression>)
{
<Statement Group 1>
}
else
{
<Statement Group 2>
}
The flow chart of if-else statement is shown in fig. 4.2.
False
Conditional
expression
expression
True
Next statement
Figure 4.2 Flow chart of if-else statement
48
Nested if
In a nested if statement, the if statement contains another if statement. The child if-else block can
be inserted either within the parent if-block or else-block. The nested if statement is useful in
complex situations, where a hierarchy of conditions is checked to choose an alternative path.The
general form of if else statement is:
if(condition1)
if(condition2)
if(condition3)
statement group 4
else
statement group 3
else
statement group 2
else
statement group 1
In the nested if-else statement, the condition of outermost if block is evaluated first. If it
evaluates to false, then the statement group 1 in the outermost else is executed and if-else is
terminated. On the other side, if the condition1 evaluates to true, then control jumps to execute
the next inner if statement. If the result of condition2 is false, then the statement group 2 is
executed. Otherwise, condition3 is evaluated. If outcome of condition3 is false, statement group
3 is executed, otherwise the statement group 4 is executed. The flow chart of nested if else
statement is shown in fig. 4.3.
49
Condition1
False
Statement Group-1
True
Condition 2
False
Statement Group-2
True
Condition 3
False
Statement Group-3
True
Statement
Group-4
Next Statement
50
{
System.out.println("Number "+b+" is greatest ") ;
}
else
{
System.out.println("Number "+c+" is greatest ") ;
}
}
}
}
Output
Enter three integer values :45 95 22
Number 95 is greatest
51
if else ladder
If-else ladder is useful in situations where we have to opt one path from many alternatives
available. For such situations, Java provides nested if-else-if ladder, using which, it is possible to
combine together several ifs and elses. But out of multiple alternatives written using many ifs
and many elses only one is executed and remaining all are skipped.
The general form of if..else..ifladder is shown here:
if(condition-1)
statement group 1
else if(condition-2)
statement group 2
else if(condition-3)
statement group 3
else
statement group 4
The conditions such as condition-1, condition-2 and condition-3 etc. are boolean expressions and
are evaluated from top to bottom one by one until an expression evaluates to true. As soon as a
true condition is found, the block of statements associated with it is executed and the rest of the
ladder is skipped. If none of the condition is true, the final else (optional)given at the end will be
executed. If the final else is missing, then no action takes place if all other conditions are false.
The flow chart representing if-else-if ladder is shown in fig. 4.4.
True
Condition1
Statement Group 1
False
Condition2
False
True
Statement Group 2
True
Condition3
Statement
Group 3
False
Statement Group 4
-
Next Statement
52
Program to get day number from user (1-7) and display print day name
import java.util.* ;
class IfElseLadderDemo
{
public static void main(String args[ ])
{
int week ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter a day (1-7) : ");
week = sc.nextInt() ;
String name ;
if(week == 1)
name = "Monday";
else if (week == 4)
name = "Thursday ";
else if(week == 3)
name = "Wednesday";
else if(week == 2)
name = " Tuesday";
else if(week == 5)
name = "Friday";
else if(week == 6)
name = "Saturday";
else if(week == 7)
name = "Sunday";
else
name = "Wrong week";
System.out.println("Name of the day is " + name) ;
}
}
Output
Enter a day (1-7) : 4
Name of the day is Thursday
Check Your Progress / Self Assessment Questions
6
53
Switch Statement
Although, the if-else-if ladder is good for selecting between multiple alternatives, but it is
confusing and complicated to understand. Java provides a solution to this problem in the form of
the switch statement. It is used to select one of several alternative paths in a program and the
choice is based upon aninteger value. A jumping statement break is used inside switch to transfer
the control outside switch block after performing required case or cases. The general form of
switch is as follows:
switch (<expression>)
{
case value_1:
statement block_1
break;
case value_2:
statement block_2
break;
:
case value_N:
statement block_n
break;
default:
default statement block
}
The flow chart demonstrating the switch statement is shown in fig. 4.5.
Expression
= Value_1
Statement block 1
= Value 2
= Value n
Statement block 2
...
Statement block n
Nextstatement
54
No match
The switch block is declared using a keyword switch followed by the expression enclosed in the
parentheses. The body of the switch statement contains multiple switch blocks containing a
group of statements enclosed within curly braces. The <expression> can be a variable or any
boolean expression that evaluates to an integer value. The variable used inside switch must be
either byte, short, char, or int. It must not be long, either of the floating-point types, boolean, or
any object references. Strictly, we can say that the value must be assignment compatible with
integer values such as value1, value2, valuen which are case labels and are defined using the
keyword case followed by colon and can of data type char, byte, short or int. The default case is
optional and can be defined using the keyword default followed by colon.
The switch statement works like this:
The value of the expression is successively tested against a list of case labels of data type
char, byte, short or int. When a match is found, a statement block associated with that
case label is executed.
If no case label is equal to the value of integral expression, the statement associated with
the default label is performed.
The break statement is optional and is used to exit from the switch block. If you omit the
breakstatement, execution will continue to the next case. Execution jumps to the default
statement if none of the case labels matches with the expression of theswitch( ) statement. In the
absence of default case, no action takes place if all matches fail. Although the default statement
is shown at the end of the switch( ) block in the above example, there is no rule that requires this
placement.Several case labels can have the same associated statement block. In that case, same
block of statements will execute for different case labels.
Program to get month number from user (1-12) and display the number of days in a month
import java.util.* ;
class SwitchDemo
{
public static void main(String args[ ])
55
{
int month ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter a month (1-12) : ");
month = sc.nextInt() ;
switch(month)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
System.out.println("Month has 31 days") ;
break ;
case 4: case 6: case 9: case 11:
System.out.println("Month has 30 days") ;
break ;
case 2:
System.out.println("Month has 28 days") ;
break ;
}
}
}
Output
Enter a month (1-12) : 4
Month has 30 days
A switch statement can be included in another switch statement known as nested switch
statement. Since eachswitch statement has its own independent block therefore, no conflicts arise
between the case labelof the inner switch and those of the outer switch. For example:
public class NestedSwitchDemo
{
public static void main(String[ ] args)
{
int a = 1, b = 2;
switch(a)
{
case 0:
System.out.println(" Value of a is 0 ") ;
switch(b)
{
case 0 :
System.out.println(" b is 0 ") ;
break ;
case 1 :
System.out.println(" b is 1 ") ;
break ;
56
default :
System.out.println("Default case of Nested Switch !!") ;
}
break ;
case 1:
System.out.println(" Value of a is 1 ") ;
switch(b)
{
case 0 :
System.out.println(" b is 0 ") ;
break ;
case 1:
System.out.println(" b is 1 ") ;
break ;
default :
System.out.println("Default case of Nested Switch !!") ;
}
break ;
default:
System.out.println("Default Case of Outer Switch !! ");
}
}
}
Output
Value of a is 1
Default case of Nested Switch !!
57
Glossary
selection statements :category of statements in Java that are used for selecting which
one out of two blocks will execute depending upon some condition.
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.
58
Model Questions
1. Which are various selection statements?
2. What is difference between simple if and if else statements?
3. Which are different types of if statement in Java?
4. What is use of nested if statement? Give an example.
5. What is use of else if ladder? How does it differ from nested if statement?
6. What is use of switch statement in Java? Give an example.
7. Which are various differences between else if ladder and switch statement?
8. Which are various limitations of switch statement in Java?
9. Write a program to find smallest of three numbers using nested if statement.
10. Write a program to calculate roots of a quadratic equation.
59
PDCA-201
Programming in Java
Unit-2.Lesson-5.
Chapter Index
Objectives
Introduction
Looping
Labeled Loops
Summary
Glossary
Model Questions
Objectives
60
61
Introduction
In the previous chapter, we have studied how to execute a group of statements and skip another
group on the basis of some conditions. Similarly, sometimes it may be required to execute a
block or group of statements more than once, this is called repetition. In this lesson, we will
study how repetition can be performed in Java program. Such type of code is called iterative
code. There are different ways to make iterative code, using looping statements provided by
Java. These statements are the topic of discussion of this lesson.
Looping
The loopingstatements allow a group of statements to be executed repeatedly and are also known
as iterative statements. The block of statements associated with a loop is executed multiple times
based on aboolean expression or condition. It is commonly used to determine when to terminate
the loop. The loop body contains a single statement or a block of statements. Java provides
following looping statements:
while Statement
do-while statement
for statement
62
True
condition
Body of Loop
False
Next Statement
63
64
Group of Statements
condition
true
False
Next
Statement
65
i=i+2;
} while( i < 100 ) ;
System.out.println("Sum of even numbers between 1 to 100 = "+sum) ;
}
}
Output
Sum of even numbers between 1 to 100 = 2450
that
controls the execution of the <loop body>. Initialization part is executed only once,when
the loop starts.
66
The <condition> is a boolean expression, usually involves the loop control variable. The
conditional expression is used to test the loop control variable against a target value such
that if the condition is true, the loop body is executed. When the condition becomes false,
the execution continues with the statement following the for loop.
After each iteration, the <update expression> is executed to update the value of the loop
control variable to ensure loop termination. The expression may increment or decrement
the value of the control variable. After execution of the update expression, the condition is
tested again to determine if the loop body should be executed again or not.
condition
True
Group of
statements
update expression
Next Statement
67
68
Output
Enter a Number : 75
Sum of odd numbers upto 75 numbers = 1444
Multiple statements can be included in both <initialization> and <update expression>. Each
statement is separated from each other using comma operator. For example, in the following
code, two variables i and j are initialized in the initialization part. Also two increment expression
are used in the update expression part.
int i, j
for(j=1 , k = 5 ; j + k < 10 ; j++, k++)
{
// Body of loop
}
Note that while using comma operator, you can not mix expressions with variable declarations,
nor can you have multiple declarations of different types. So the following statement would be
illegal:
int i = 1 ;
for(i++, int j = 0 ; i < 10 ; j++) { }
//illegal
Example:
class MultiStatDemo
{
public static void main(String args[ ])
{
int i, j;
for(i=1, j=10 ; i < j ; i++, j--)
System.out.println("i = " + i+", j = "+j);
}
}
Output
i = 1, j = 10
i = 2, j = 9
i = 3, j = 8
i = 4, j = 7
69
i = 5, j = 6
In the conditional expression of the for loop, normally the loop control variable is tested against
a target value so as to exit from the loop. The variation of this is that any boolean expression can
be used that does not include the loop control variable. For example:
70
import java.util.Scanner ;
class MoreForLoopDemo
{
public static void main(String args[])
{
int i, n ;
double avg, sum = 0 ;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : " ) ;
n = sc.nextInt( );
boolean limit = false;
i = 1;
for( ; !limit; )
{
sum += i ;
if(i == n) limit = true;
i++;
}
avg = sum / n ;
System.out.println("Average = " + avg);
}
}
Output
Enter a Number : 1000
Average = 500.5
An infinite for loop can be created by leaving the conditional expression or update expression or
all the parts blank. There are different ways to create infinite loop using for statement, these are :
for( ; ; ) { }
71
first pass or iteration of the outer loop triggers the inner loop, which executes to its completion
i.e. runs all iterations of the inner loop. Then the second pass of the outer loop triggers the inner
loop again and runs it to completion. This repeats until the outer loop terminates. Any number of
loops can be nested. For example:
class NestedLoopDemo
{
public static void main (String[ ] args)
{
int n=7, x=5, y= 1;
for(int i=0; i <= n ;i++)
{
for(int j=1; j <= i ; j++)
{
System.out.print(y + "\t");
y = y + x;
}
System.out.println("");
}
}
}
Outut
1
6
16
31
51
76
106
11
21
36
56
81
111
26
41 46
61 66 71
86 91 96 101
116 121 126 131
136
72
73
break
continue
return
break Statement
In loops, the break statement is used to exit from the loop. In such a case, the loop is terminated
immediately and the remaining code in the body of the loop is skipped. The program control
transfer to the next statement after the loop. Figure 5.4 demonstrates the use of break.
statement1
statement2
:
start of loop
statement is executed
Loop body
:
if (<condition>)
break ;
Flow when
: break
Normal flow
end of loop
74
}
Output
I=2
I=4
I=6
I=8
Statement after loop
continue Statement
The continue statement can be used in loops to prematurely stop the current iteration of the loop
body and to start with the next iteration. In whileand do-whileloops, a continuestatement causes
control to be transferred directly to the conditional expression that controls the loop. In a forloop,
control first transfers to the iteration portion of the forstatement and then to the conditional
expression. The figure 5.5 demonstrate the use of continue statement in the for loop.
statements
:
:
continue ;
:
Loop body
if (condition)
end of loop
body
Normal flow
Flow when continue
statement is executed
75
}
}
Output
Sum of odd numbers = 625
return <expression>
The first form return just the control not return any value to the calling method. In the second
form, the <expression> is evaluated and the result obtained is returned to calling method.
Labeled Loops
In labeled loops, Java provides labeled jumping statements such as labeled break and continue
statement. The syntax of labeled break and continue are:
break label;
continue label ;
where, the label is a name that identifies the block of code.
76
Labeled break
The labeled break statementcan be used in any looping statement that causes an immediate exit
from any number of nested blocks. The control is transferred to the first statement given after the
corresponding labeled block. For example:
class LabeledBreakDemo
{
public static void main(String a[])
{
int i ;
OUT :
{
for(i=0; i<5; i++)
{
while (true) //infinite loop
{
System.out.println("Inside Inner Loop");
break OUT ;
} // inner loop ends
// System.out.println("Outer loop."); // Unreachable.
} // outer loop ends
} //OUT block ends
System.out.println("Exited from all nested blocks") ;
}
}
Output
Inside Inner Loop
Exited from all nested blocks
Labeled continue
Java providesa labeled continue statement that skips the remaining code in the body of the loop
and any number of enclosing loop statements. It proceeds with the next iteration of the enclosing
labeled loop statement. In a labeled while and do-while statements, the condition will be first
tested after executing the continue statement. In a labeled for loop statement, the increment
expression will be tested and the condition is evaluated.
Example:
classLabeledContinueDemo
{
77
Glossary
Entry controlled: a type of loop where looping condition precedes loop body.
Exit controlled: a type of loop where loop body precedes looping condition
for loop: a type of entry controlled loop, a statement and keyword of Java, has 3 optional
parts.
while loop: another type of entry controlled loop, a statement in java, a keyword of Java.
78
break: a keyword of java, a statement to shift control from one statement to another
statement in another part of program.
continue : a keyword of Java, a statement used inside a loop body to start next iteration
of loop.
79
Model Questions
Que. 1. What is meant by iterative code? What is difference between entry controlled loop and
exit controlled loop?
Que. 2. Which are different types of looping statements available in Java?
Que. 3. What is the syntax of for loop. Give an example.
Que. 4.How does while loop differ from a for loop?
Que. 5. Write a program to display first n elements of Fibonacci series using while loop.
Que. 6. How does while loop differ from do while loop?
Que.7. Explain for each loop available in Java.
Que. 8. Write a program to find factorial of a number using for loop and while loop.
Que. 9. What is meaning of Labeled Loop. Give an example.
Que. 10. How control can be shifted outside a loop?
80
Defining a Class
Adding Variables
Adding Methods
Creating Objects
Constructors
Inheritance
Extending a Class
Defining a subclass
Subclass constructor
Multilevel inheritance
Hierarchical inheritance
Overriding Methods
Final Classes
Finalizer Methods
Wrapper Classes
Static Classes
Abstract Classes
Method Overloading
81
Nesting of methods
Garbage Collection
Summary
Glossary
Model Questions
Objectives
Introduction
Classes are the basic building blocks of a Java program. A class is like a structure or template that is used
to create objects. A class contains attributes and behaviour. The attributes are represented by variables
and the behaviour is represented by methods. A class is a user-defined data type that is created from
the java inbuilt primitive data types. Inheritance is one of the basic principles of object oriented
programming. Various types of inheritance will be studied here. Concept of method overloading and
method overriding will be explored.
82
6.1
Defining a Class
A class consists of variables and the methods that operate on those variables. The variables contain data
and the methods contain the code to process the data stored in variables. The variables and methods
are collectively known as class members. A class is declared using the keyword class followed by the
name of that class. The general form of a class definition is given below:
class ClassName
{
type varname_1 ;
type varname_2 ;
.
type varname_N ;
<method body>
}
return_type methodname_2(type var_1, type var_2,,type var_N)
{
<method body>
}
:
return_type methodname_N(type var_1, type var_2,,type var_N)
{
<method body>
83
}
}
As shown in the above class definition, the body of a class usually consists of instance variable and
methods.
6.1.1 Adding Variables
The variables declared within a class are also called as instance variables. The data types of instance
variablescan be of any primitive data types such as int, char, float, double etc. or can be a reference type
such as an object, array, string etc. You can define a class containing only member variables as shown
below:
class Employee
{
int empNo ;
String EmpName ;
double basicSal ;
}
The class Employee declared above contains three instance variables, empNo, EmpName and basicSal.
84
can be left blank, if a method does not require any value. Also, if a method have a return type other
than void, the method must contain a return statement of the form:
return result ;
Here, the result is the value to be returned.
For example, the class Employee as shown above is extended and contains a method findTax( ) as
illustrated below:
class Employee
{
int empNo ;
String EmpName ;
double basicSal ;
void findTax( )
{
double tax ;
percent = basicSal * 30/100.0;
System.out.println("The Income Tax is "+tax) ;
}
}
6.2 Creating Objects
Declare a variable of class type known as reference variable. The reference variable refers to the
object of the class. At this point, the reference variable contains the value null that means , it does
not point to any object yet.
85
Create an object using new operator and assign that object to a reference variable. The operator
new dynamically allocates memory for an object at runtime and returns a reference to it. In Java,
objects are manipulated through object references.
For Example
Employee e ;
6.3
Once an object of a class is created, its instance variables occupy memory and needs to be initialized.
The members of a class(variables and methods) can be accessed using the dot operator (.) with the
name of the object followed by the name of class member to be accessed. For example, the following
statements declare the Employee object and access the member empNo of the object e..
Employee e = new Employee ( )
e.empNo = 5209 ;
This statement assigns a value of 5209 to instance variable empNo within the object e.
Here is another example that demonstrates writing a class, creating objects of that class and accessing
its members to initialize them using a dot operator.
class Student New class student defined.
{
86
int rollno ;
double marks ;
public static void main(String a [ ])
{
Student ob = new Student( ) new object of Student class is created.
// assign values to data members of object
ob.rollno = 1001;
ob.marks = 567;
double result ;
result = ob.marks / 600 * 100 ;
System.out.println("The percentage is "+result) ;
}
}
6.4
Constructor
An object should be first initialized before using it in aprogram. In order to initialize an object,
each member variable of that object is initialized with some value. It is difficult to initialize all of
the variables in a class each time an object is created. For this purpose, constructor is used to
perform the initialization of variables upon creation of an object.A constructor is a special form
of a methodand is invoked automatically and immediately when an object is created using new
operator.However, there are some restrictions using a constructor:
A constructor must have the same name as the name of the class.
A constructor does not return anything by default, so no return type should be used, not even
void.
A class may have any number of constructors, this is called constructor overloading.
Every class has a default constructor. If we do not explicitly design a constructor for a class, the
java compiler builds a default constructor for that class.
87
For example:
class Student
{
int rollno ;
String name ;
double marks ;
88
6.5 Inheritance
Inheritance is an important principle of OOPs that enables code reusability. In this mechanism, one class
(subclass) can inherit all the instance variables and methods of another class (superclass). With the help
of an inheritance, a class immediately has all the functionality of a superclass and the new subclass has
to incorporate only those things that are not present in the superclass. While creating inheritance
hierarchy, at the root level, a general class is created that contains common attributes. This class can
then be inherited by other more specific classes, each of them, adding specific things that are unique to
it. Thus, using inheritance, one needs to start from scratch.
The inheritance relationship can be shown in Fig. 6.1 using the UML class diagram using a solid line with
an arrow head pointing towards super class name.
Superclass
Subclass
89
double a, b ;
SuperClass(double m, double n)
{
a=m;
90
b=n;
}
void print( )
{
}
}
class SubClass extends SuperClass
{
double c ;
SubClass(double m, double n, double o)
{ super(m,n) ;
c=o;
}
void mean( )
{
double result ;
result = (a + b+ c ) / 2 ;
System.out.println("Mean = "+ result) ;
}
}
class ConstructorDemo
{
91
sub.print( ) ;
sub.mean( ) ;
}
}
Multilevel Inheritance
In Java, hierarchies that consists of unlimited layers of inheritance can be created. So, you can create a
subclass of a class which is also a subclass of another class and so on. For example, if a class Childinherits
from class Parent, and class Parentinherits from class GrandParent, then theclass Child willacquire all
the members defined in class Parentas well as all the members declared in class GrandParent. The
multilevel inheritance is shown in Fig. 6.2 given below.
GrandParent
Parent
Child
Hierarchical inheritance
In hierarchical inheritance, many subclasses inherit from a single superclass. For example, if classes
Child1, Child2 and Child3 inherit from same class Parent,thenclasses Child1, Child2 and Child3 will
acquire all the members from the class Parent. The hierarchical inheritance is shown in Fig. 6.3 given
below:
92
Parent
Child1
Child2
Child3
Overriding Methods
Method overriding occurs when a subclass method has the same name and type signature as a method
in its superclass. The return types of both methods must be the same. When an overridden method is
invoked by the object of subclass, it will always refer to the version of a method defined by the subclass.
This can be demonstrated with the help of an example.
class SuperClass
{
double a ;
double b ;
SuperClass(double m, double n)
{
a=m;
b=n;
}
void mean( )
{
double result ;
result = (a + b ) / 2 ;
System.out.println("SuperClass Mean = "+ result) ;
}
93
}
class SubClass extends SuperClass
{
double c ;
SubClass(double m, double n, double o)
{
super(m,n) ;
c=o;
}
{
void mean( )
double result ;
result = (a + b+ c ) / 2 ;
System.out.println("Sub Class Mean = "+ result) ;
}
class ConstructorDemo
{
public static void main(String args[])
{
SuperClass sup = new SuperClass(25,37) ;
sup.mean( ) ;
SubClass sub = new SubClass(45,87,63) ;
sub.mean( ) ;
}
}
94
// Method body
}
Final Classes
Final classes prevent inheritance and thus, cannot be inherited. When a class is declared as final, all of its
methods are implicitly declared as final. To declare a final class, use the modifier at the beginning.
Finalizer Methods
Finalizer Methods are used in a garbage collection mechanism, in which the objects are
automatically destroyed when no reference of that object exist and the memory occupied by that
object is reclaimed. Sometimes, an object eligible for garbage collection occupies some
resources such as file or database connection for reading or writing purpose, then those resources
95
must be released before the object is destroyed. For this purpose, Java provides a mechanism
called finalization. You can add a finalizer in your class by simply defining the finalize( )
method. Java run time calls this method automatically, whenever the object of that class is about
to destroy. The syntax of the method is:
Wrapper Classes
Java uses simple data types such as byte, short, char, int, float, double and boolean that cannot be
treated as objects. Sometimes, an object representation of these types is required so as to perform
various operations. For this purpose, Java Provides wrapper classes corresponding to each of
these simple types. All the wrapper classes reside in java.lang package and its hierarchy is
depicted in Fig. 6.4.
96
Object
Number
Short
Byte
Character
Intege
r
Long
Float
Double
Boolean
d = d + 20.20 ;
97
Static Classes
A static class is created inside another class is called static inner class. The static inner class can access
only static variable and methods of its outer class including private. We cannot create an object of static
inner class without the reference of outer class. This can be illustrated with the help of an example:
class Outer
{ static int i = 95;
static class Inner
{ void print( )
{
System.out.println("Value of i ="+i) ;
}
}
}
class Test
{ public static void main(String args[])
{ Outer.Inner ob = new Outer.Inner( ) ;
ob.print( ) ;
}
}
Abstract Classes
Abstract classes are partially completed classes and contain one or more abstract methods. The abstract
methods are non-implementing methods having no body. An object of an abstract class cannot be
created but we can declare a reference variable of an abstract class. Any subclass of an abstract class
must either implement all of the abstract methods from the abstract class or declare itself as an abstract
too. An abstract class may also contain non-abstract methods. To declare a class abstract, the abstract
modifier is used with the name of the class. The syntax is:
abstract class AbstractClassName
{
// abstract method
98
Annotations
Feature of annotations were added to Java from Java version 5. In, Java language, annotations are used
to provide meta data. This meta data is special data that gives information about some other data.
Being meta data, annotations do not affect the execution of java program directly.
Annotations in java, are basically used for the purposes like, Compiler instructions, Runtime instructions
and Build-time instructions.
There are built-in java annotations which are predefined in java. these are : @Deprecated, @Override,
@SuppressWarnings
Broadly, there are three types of annotations as explained below :
1) Marker Annotation : This is type of annotation that does not have any method in its body. For
example:
99
@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations in Java.
2) Single-Value Annotation : This is type of annotation that has one method definition in its body. For
example:
@interface MyAnnotation
{
int value( );
}
It can be provide a default value also, like :
@interface MyAnnotation
{
}
Single annotaion can be used as : @MyAnnotation(value=33)
3) Mulit-Value Annotation : An annotation that has more than one method defined in its body, is called
Multi-Value annotation. For example:
@interface MyAnnotation
{
int val1( );
String val2( ); String val3( );
}
These can be provided default value also. For example :
@interface MyAnnotation
100
}
Method Overloading
In Java, different methods with the same name but different signature can be defined and is
known as method overloading. The signature of methods includes the number and/or type of
parameters. The difference in return types alone is not sufficient for the methods to be
overloaded. Method overloading implements polymorphism. Whenever, an overloaded method
is called, Java run time search for a matching method based on arguments supplied at the time of
the method call, to determine which version of the overloaded method is to be invoked. This can
be illustrated with the help of an example:
class Overloading
{
void max(int a, int b)
{
int big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two integer values = " + big) ;
}
void max(double a, double b)
{
double big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two double values = " + big) ;
}
}
class OverloadingDemo
{
public static void main(String args[])
101
{
Overloading ob = new Overloading( ) ;
ob.max(6,19);
ob.max(45.2, 34.5) ;
}
}
Nesting of Methods
When a method in a class invokes another method within the same class, it is known as nesting
of methods. In order to call a method in the same class, dot(.) operator is not required. It is
possible to call more than one method in the same class. This can be demonstrated with the help
of an example:
class NestingMethod
{
int a ;
int b ;
int big ;
void max(int a, int b)
{
if(a > b)
big = a ;
else
big = b ;
display( ) ;
}
void display( )
{
System.out.println("Maximun of two integer values = " + big) ;
}
}
class NestingMethodDemo
{
public static void main(String args[])
{
NestingMethod ob = new NestingMethod( ) ;
ob.max(16,19);
}
}
Methods with Varargs (Variablearguments)
Class methods can be defined with variable number of arguments also. An example of such a
method is println method that can print any number of values passed to it as arguments. Varargs
102
feature was added in Java version 5. To declare a method that may later take 0 or more
arguments, the syntax includes three dots (called ellipses).
Before the feature of variable arguments, either method overloading is used (it uses program
code larger) or method argument has to be an array of n elements but it makes little complicated
code.
While using a method with variable arguments, some rules have to be followed, otherwise
program code does not compile successfully.
There can be at maximum, only one variable argument in a method.
If used, the vararg must be the last argument in the method
Example.
public class Varargs
{ public static void main(String args[])
{ ShowMessage(5, "Hello", "Hi");
ShowMessage(3, "Hello", "Good Morning", "How are you?");
}
public static void ShowMessage(int x, String... args)
{ System.out.println("x =" + x) ;
for(String arg: args)
{
System.out.print(", " + arg);
}
}
}
Garbage Collection
Garbage collection is a mechanism of destroying objects automatically when no reference
variable exists containing the reference of that object and reclaiming the memory occupied by
the object. It provides optimum utilization of memory. The Java run time periodically initiate the
method void gc( ) of the class Runtime to initiate garbage collection to recycle unused objects.
Check Your Progress / Self Assessment Questions
Ques14.What is the difference between method overloading and method overriding?
Ques15.Which method is used to run a garbage collector?
103
Glossary
Method overloading :Methods having the same name but with different parameters
Constructor : a special method of a class, having same name as that of class, used to initialize an
object.
Base class : a class that acts like a parent or super class of another class.
Multilevel inheritance : a type of inheritance whereby a class is derived from another derived
class.
Hierarchical inheritance : a type of inheritance where by multiple classes are derived from same
base or parent class.
Overriding Methods : defining same named method in child or derived class as that of parent
class.
Method Overloading: having multiple functions of the same name in one class.
104
105
Model Questions
106
PDCA-201
Array, Vectors and String Handling
Unit-3. Lesson - 7
Chapter Index
Objectives
Introduction
Arrays
Creating an Array
Vectors
Strings
Type Conversion
Summary
Glossary
Model Questions
107
Objectives
Introduction
Many a times in a program, we may need to work with large number of variables. Declaring
huge number of individual variables is very inconvenient. A very simple solution to this multiple
declaration problem is to use an array or a vector which is group of homogenous data elements.
A string is collection of characters. Array, Vector and Strings are topic of discussion in this
chapter.
108
7.1 Arrays
An Array is a indexed collection of homogenous elements i.e. same data type. Unlike, an
ordinary variable which store a single value, an array can hold numerous items. The position of
an element in the array is tracked by using non-negative integer values called index numbers.
Array index number always starts with zero. If an array has n elements then these n elements are
referenced using integer indices from 0 to n - 1, inclusive. The size of an array is fixed after its
declaration and cannot be modified later.
In Java, arrays are treated as objects. Arrays can be of primitive data types, in which case all
the elements stored in the array are of that type. Arrays can also be of reference types, in which
case all the elements in the array are references of a class or interface type. Thus, an array can
hold objects of a specific class or interface type. An array has a final variable called length,
which represents the size of an array. The size of an array means the maximum number of items,
an array can hold.
7.3 One-Dimensional Arrays
One dimensional array is a list of elements. Elements in the list have only one dimension, .i.e.
theyexpand in one direction only. A single index number is used to access each element. This
index number is like the serial number of the element in the list. In memory, they are stored in
contiguous memory locations.The storage of an array in memory is shown in Fig. 7.1.
In the above figure, each box represents the amount of memory needed to hold one array
element. Size of the box depends on the data type of the array. For int data type this is 4 bytes.
The array variable, a holds a memory address of memory that holds the actual array elements.
7.4 Creating an Array
Since arrays in Java are treated as objects, accordingly, the new operator is used to create an
array object just like object of user-defined or built-in classes.
109
110
Here, an array marks of data type double is created to store marks of 50 students. The two steps
of creating an array can be combined into a single step using the syntax :
dataType arrayReferenceVariable= new dataType[size]
for example : double marks = new double[50] ;
The [ ] brackets tell the compiler that you are creating an array and not an ordinary variable. You
can also place the square brackets.
The use of an array is demonstrated with the help of an example:
class ArrayDemo
{
public static void main(String args[ ])
{
double marks[ ] ;
marks = new double[5] ;
marks[0] = 31.5;
marks[1] = 28.2;
marks[2] = 65.7;
marks[3] = 30.9;
marks[4] = 85.4;
System.out.println("Value of fourth element " + marks[3]);
}
}
Output
Value of fourth element 30.9
7.4.3 Initialization of arrays
Each variable of a primitive type array has a default value. For numeric types, the default values
equal zero (0 for integers, 0.0 for floating point). For boolean arrays the default value of each
element is false. For char array the default is '\u0000' and null for all object types.. Thus, when
an array is created, all its elements are set to an initial value. The array can be created and
initialized simultaneously in one step. For the initialization, a set of values are placed in the curly
braces and separated by comma. The size of the array will become equal to the number of
elements used for the initialization.
The syntax is:
type arrayReferenceVariable [ ] = { value_1, value_2, ,value_n } ;
For example:int week[ ] = { 1,2,3,4,5,6,7 } ;
111
}
}
Output
Mean value of marks 48.34
Check Your Progress / Self Assessment Questions
112
a[0]
a[1]
0 00
0 00
0 00
The two dimensional arrays can be demonstrated with the help of an example:
class TwoDimArray
{
Grou
public static void main(String args[
])
p of
{
State
ments
113
7.6 Vectors
A vector is a dynamic and resizable array. The size of an array can dynamically increase or
decrease as needed to accommodate addition or removal of elements after the vector has been
created. Vector is synchronized and thus is thread safe. Vector has many legacy methods that are
not part of the collection framework. Vector is very useful in situations where, the size of an
array is not known in advance.
Vector has the following constructors:
Vector( )
Vector(Int size)
Vector(Collection c)
The first default constructor creates a vector object having the initial size of 10. The second form
of constructors is used to specify the initial size of an array. The third constructor creates a vector
having initial size and increment value. The increment specifies the number of elements
allocated to vector when resized upward. The fourth constructor creates a vector that contains
the elements taken from the collection c. Whenever a vector is created, it starts with the initial
capacity. Once the initial capacity is full and the next time, an attempt is made to insert an object
114
in the vector, the vector automatically allocates space for that object plus extra space for
additional objects depending upon the value of increment.
The vector class of java.util package contains numerous methods that are used to manipulate
vector. Some of the methods are:
final boolean removeElement(Object ob) : remove an object from the vector and returns
true if removed successfully otherwise false.
final int size( ) : returns the size of the vector in terms of number of elements currently
occupied by the vector.
final Object elementAt(int index) : return the element from the vector at the specified
location.
final Object firstElement( ) : return the first element from the vector.
final Object lastElement( ) : return the last element from the vector.
115
7.7 Strings
A string is a sequence of characters enclosed within the double quotes. In Java, strings are
treatedas objects of the built-in class String. Handling of strings in Java is very easy. Strings are
immutable. It means once a string object is created and initialized, it cannot be modified.
However, you can still perform all types of string operations. The reason is every time the string
is modified, a new string object is created which contains the modified string. In Java, immutable
strings can be implemented more efficiently than changeable ones. Strings can be created either
initializing a variable with the string literal enclosed inside double quotes or by using any of the
constructors defined in the String class. For Example:
String name = My name is Rajan
116
Since the string literals are treated as string objects. So, you can call the methods of the String
class with the string literal.
The class String contains several constructors to create string object:
A string array contains a group of strings. Each string element stored in the array is an object.
String array is created using the new operator and declaring a reference variable of type String.
The syntax is:String ref[ ] = new String[5] ;
Once the string object is created. The next step is to initialize the array using the syntax:
117
ref[ i ] = Java
You can also create a string array using the declaration and initialization in one step:
String ref[ ] = { Java, is, an, Object, Oriented, Language) ;
Once the string array is created, it can be traversed using any loop. In Java 5, a new foreach loop
is introduced that is specifically used to iterate through an array or collection. It is simple and
concise that makes the program more readable. The syntax is:
for (type variable : array)
This can be demonstrated with the help of an example:
class StringArrayDemo
{
public static void main(String args[ ])
{
String[ ] student ={"Suresh","Ramesh","Rajan","Suraj","Chetan"};
for(String str : student)
System.out.print(str+ " ");
}
}
Output
Suresh Ramesh Rajan Suraj Chetan
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.
118
In certain situations, it is not sufficient to compare two strings for equality. For example, when
you want to sort different strings, you need to know which string is less than, equal to or greater
than the other. For this purpose, Java provides the compareTo( ) method.
The first compareTo( ) method compares two strings based on the unicode value of each
character in the strings. The character sequence represented by this String object is compared
lexicographically to the character sequence represented by the argument string. The result is:
a negative integer if this String object is lexicographically less than the argument string.
a positive integer if this String object is lexicographically greater than the argument string.
Concatenation of two strings means joining the two strings, which represents first strings
characters followed by the second strings characters. The concatenation of two strings can be
performed using + operator and the concat( ) method defined in the String class. Both produce a
new string object as the result. The syntax of concat( ) method is:
String concat(str) : It returns a new string object by joining the invoking string and the string str
passed as an argument.
119
Java RuntimePolymorphism
The String class provides methods used to convert values of primitive data types into strings. It
contains a static method valueOf( ) in overloading forms that operates on different data types to
create their equivalent strings. For example:
double d = 39.85 ;
String str = String.valueOf(d) ;
The String class offersseveral methods that are used to modify strings. Since string objects are
immutable, whenever you modify a string, a new string object is created containing a modified
string.
String replace(char old, char new) : Replace all occurrences of old character with new
character.
String replaceAll(String old, String new) : Replace all occurrences of the old string with
new string.
String replaceFirst(String old, String new): Replace only first occurrence of old string
with new string.
String substring(int start) : Returns a new substring object that begins with the character
at specified index and extends up to the end of the string.
String substring(int start, int end) : Returns a new substring object that begins with the
character at specfied index and extends to the character at index end-1.
String trim( ) : Returns a new string with the leading and trailing whitespace omitted.
120
";
}
}
Output
His name is Sunil and Sunil is a good boy.
Sunil is a good boy.
Unlike the String class, the StringBuffer class are mutable strings.Thus, both the capacity
and contents of a StringBuffer Class can be modified dynamically. String buffers are used
where modification of strings like appending, inserting, deleting and modifying is
involved.Every string buffer has a capacity. The capacity of a string buffer is the
maximum number of characters that a string buffer can accommodate, before its size is
automatically increased. As the length of the character sequence contained in the string
buffer exceed the capacity, the string buffer will automatically grow to make room for
further additions.The final class StringBuffer provides three constructors used to create
StringBuffer objects:
public StringBuffer(int capacity): Constructs anempty string buffer and the specified
initial capacity.
public StringBuffer(String str): Constructs a string buffer initialized with the contents of
the specified string. The initial capacity of the string buffer is 16 plus the length of the
string argument.
public int length( ): Returns the length of the sequence of characters of the string buffer.
121
If the two types are compatible, then Java will perform the conversion
automatically. For the primitive data types, a value of a narrower data type can be converted
automatically to a value of a broader data type without loss of information. This is called
widening conversion. Widening conversions to the next broader type for primitive data types are
summarized in Figure 3.6.
byte
shor
t
int
long
float
double
char
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, the numeric types are not compatible with char or
boolean. Also, char and boolean are not compatible with each other. Conversion from broader
122
data type to a narrower data type is called a narrowing primitive conversion, which results in loss
of information. This kind of conversion will not be performed automatically and need a casting.
A castis simply an explicit type conversion. It has this general form: (type) operand
7.9 Command Line Arguments
Command Line arguments are used to pass information to the program at runtime. The java
program contains a method main( ) that is used to receive the command line arguments from the
outside. A command-lineargument is the input values that follow the program's name on the
command lineat runtime. A string array is used as a parameter to the main( ) method to retrieve
the command-line arguments inside a Java program
The following example displays all of the command-line arguments:
class CommandLineDemo
{ public static void main(String args[ ])
{ for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
At command prompt, execute the program along with the command line arguments such as:
Java CommandLineDemo Passing arguments at command line
Output
args[0]: Passing
args[1]: arguments
args[2]: at
args[3]: command
args[4]: line
Check Your Progress / Self Assessment Questions
Summary
An Array is a indexed collection of homogenous elements of the same type. Unlike, an ordinary
variable which store a single value, an array can hold numerous items. A vector is a dynamic and
123
resizable array. The size of an array can dynamically increase or decrease as needed to
accommodate addition or removal of elements after the vector has been created. Vector is
synchronized and thus is thread safe. A string is a sequence of characters enclosed within the
double quotes. In Java, strings are treatedas objects of the built-in class String. Handling of
strings in Java is very easy. Strings are immutable in Java.
Glossary
Method overloading :Methods having the same name but with different parameters
124
Model Questions
1. What is an array ? What are its advantages ?
2. Write any five applications of arrays?
3. What is the difference between length variable and length( ) method?
4. What is a vector? How it differs from an array?
5. What is string in Java ? Why java strings are immutable?
6. Explain any five methods of string class.
125
PDCA-201
Programming in Java
Unit-3.
Lesson - 8.
Interfaces
Chapter Index
Objectives
Introduction
Defining Interfaces
Extending Interfaces
Implementing Interfaces
Summary
Glossary
Model Questions
Objectives
126
Introduction
In this chapter we will study about another very important part of java i.e. interfaces. Interfaces
are different from classes. A class can be extended only from a single base class since java
doesnt support multiple-inheritance. But it does not decrease the power of Java. Java provides
an alternative way of implementing multiple inheritance and that is using interfaces. There are
many inbuilt interfaces in java, and java also allows users to create user defined interfaces also.
Interface header
{
// constants declarations
// abstract method declarations
Interface body
}
Where
public keyword is optional, if an interface is not defined as public then by default its
access level becomes class level and it can be accessed only within same class.If it is
defined as public then it can be accessed by any other class.
127
InterFaceName is name of the interface, it is any valid java identifier and can be
given by user.
Within its body, many constants and methods can be declared in any order.
Interface header
constant declarations
method declarations
In this example, an interface student is being defined. A constant named SemesterFee is declared
and then two methods namely, findTotalMarks and findLectureShortage are also declared inside
body of this interface.
Like a class body, an interface body may contain any number of constant declarations
and methods.
Just like a class, an interface body is also given in a file with a .java extension, with the
name of the interface matching the name of the file, and when compiled, it also creates a
.class file i.e. byte code each interface appears in a separate .class file.
Like classes, Interfaces may also appear in packages, and their corresponding bytecode
file must be placed in a directory structure that matches the package name.
However, there are many differencesbetween an interface and a class. Some of these are :
Though an object of a class may be created, an object of interface cannot be created, but
it is allowed to create a reference variable of an interface.
An interface body cannot have any constructor or destructor, since its object cannot be
created.
128
By default, all of the methods given in an interface body are abstract and public, interface
methods cannot be declared private.
Only static constants are allowed inside an interface body, it cannot contain instance
fields.
A class can extend only one class whereas, an interface can extend multiple interfaces.
interface
ChidInterface
extends
ParentInterface1,
ParentInterface2,
ParentInterfaceN
{
//body of ChidInterface
}
Where
129
Extends is keyword of java and indicates that new interface is being inherited from
existing interface(s)
There is a major difference between class inheritance and interface inheritance in java. Since
java does not support multiple inheritance, a class can extend at maximum one class but an
interface can extend zero, one or multiple interfaces. This has been explained in section
8.5.1.
Example :
interface MyInterface1
{
final int num=10;
void fun( ) ;
}
interface MyInterface2 extends MyInterface1
{
final int length=10;
void gun( ) ;
}
class myClass implements MyInterface2
{
public void fun( )
{
System.out.println("This is fun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
}
public void gun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
}
130
}
In above example, first an interface MyInterface1 is created, then it is extended by another
interface MyInteface2. Fields and methods declared in MyInterface1 become available to
MyInterface2. In addition MyInterface2 can declare its own new methods and fields. Finally
a class myClass is created which implements interface MyInterface2. All the fields and
methods declared in MyInterface1 and MyInterface2 become available to class for
implementation via MyInterface2 only.
8.3 Implementing Interfaces
Since an interface merely declares methods, and does not provide method body or definition,
someone else has to provide method definition on the behalf of interface, otherwise methods
declared inside interface will not be useable. The task to define body of methods declared
inside interface is performed by the class which uses that interface i.e. the class which
implements that interface. It is said that a class implements an interface since class
provides the implementation details of the methods declared inside interface. It is the class
that decides how those methods will be implemented i.e. what exactly will be their working,
interface only imposes method signatures.
If one interface is implemented by multiple classes, each class may have its own
implementation of any methods of the interface. Further a concrete class that implements an
interface has to provide implementation part of all of the methods of the interface. If a class
does not provide the implementation part of all the methods then the class must itself be
declared as abstract.
Note that when a new class (child) is created from an existing class (parent), it is said that
(child) class extends (parent) class, but when a new class (child) extends an interface it is
termed that class implements interface.
131
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.
132
}
public void calculateBonus()
{
totalbonus =(experienceInYears*1000) ;
return ;
}
}
public class interfaceExample
{
public static void main(String a[ ])
{
regularEmp e=new regularEmp ();
e.basicSalary=5000 ;
e.experienceInYears =5;
e.calculateTotalSalary() ;
System.out.println("Total Salary is " + e.totalsalary );
e.calculateBonus() ;
System.out.println("Total Bonus is " + e.totalbonus );
}
}
Output :
Total Salary is 15000
Total Bonus is 5000
In the above example, an interface Employee is created that declares two methods,
calculateTotalSalary( ) and calculateBonus( ), then a class regularEmp
is defined which
implements the interface Employee. Class regularEmp provides implementation details of the
methods. When above program is compiled it will create three class files, Employee.class,
regularEmp.class, interfaceExample.class.
133
One interface can be implemented by more than one class also. Each class can define
implementation details of the methods in its own way, but each class will have exactly same
signatures of those methods. This is actually main reasons behind having interfaces in Java.
This is explained with following example.
134
totalsalary=basicSalary + 4000 ;
135
Output :
Total Salary of Regular Employee is 15000
Total Bonus of Regular Employee is 5000
Total Salary of Part Time Employee is 9000
Total Bonus of Part Time Employee is
In this example we have two different classes regularEmp and partTimeEmp implementing
same common interface Employee. Both have different data members. Both classes define the
implementation of the methods declared in interface Employee in their own way.
Class
regularEmp calculates total salary of a regular employee on the basis of his/her experience in
number of years, but class part time employee calculates total salary of a part time employee
using a fix formula. A class can implement more than one interface also, this has been explained
in section 8.5.2
136
interface
ChidInterface
extends
ParentInterface1,
ParentInterface2,
ParentInterfaceN
{
//body of ChidInterface
}
This syntax clearly shows that a new interface can be extended from multiple existing interfaces.
While doing so, all the members declared in existing interfaces ParentInterfaceName1,
ParentInterface2, , ParentInterfaceN are inherited by new interface (ChildInterface) being
created. When a class implements ChildInterface, all the methods will have to be implemented
by it.
Example : An interface extending multiple interfaces.
interface MyInterface1
Parent interface 1
{
final int num=10;
void fun( ) ;
}
interface MyInterface2
Parent interface 2
{
final int sum=0;
void gun( ) ;
}
i
interface MyInterface3 extends MyInterface1 child interface extending two interfaces
137
{
final int length=10;
void sun( ) ;
}
class myClass implements MyInterface2 class implements child interface.
{
public void fun( )
{
System.out.println("This is fun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
System.out.println("sum=" + sum) ;
}
public void gun( )
{
}
public void sun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
System.out.println("sum=" + sum) ;
}
}
In above example, first an interface MyInterface1 is created, then it is extended by another
interface MyInteface2. Fields and methods declared in MyInterface1 become available to
MyInterface2. In addition MyInterface2 can declare its own new methods and fields. Finally
a class myClass is created which implements interface MyInterface2. All the fields and
138
}
public void gun( )
{
System.out.println("This is gun method") ;
System.out.println("num=" + num) ;
System.out.println("length =" + length) ;
139
}
}
140
experienceInYears=expr ;
}
}
class partTimeEmp implements Employee
{
long empID, basicSalary, totalSalary ;
public void calculateTotalSalary()
{
totalSalary =(basicSalary + 3000 );
System.out.print("Total Salary of Part Time Employee With EmpId " + empID)
System.out.println (" is " + totalSalary );
}
partTimeEmp (long eid, long bsal) //parameterized constructor
{
empID=eid;
basicSalary=bsal;
}
}
public class interfaceexample3
{
public static void main(String a[ ])
{
Employee e; // reference variable of interface type is created.
141
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.
Summary
An interface is named block of code which may contain named constants and method
declarations (without their definition or implantation details). To define an interface in java,
interface keyword is used. Definition or body of an interface may contain constants and
abstract method declarations only. All constants declared inside an interface are public, static and
final by default, and all methods declared inside an interface are public and abstract by default.
Though an object of a class may be created, an object of interface cannot be created, but it is
allowed to create a reference variable of an interface
One interface can be implemented by more than one class also.
One class can implement more than one interface also.
142
Since java does not support multiple inheritance, a class can extend at maximum one class but an
interface can extend zero, one or multiple interfaces.
Polymorphism is the capability of a data member or field or variable of a particular class to be
used to reference objects of any of its descendent types in inheritance.
A class can extend another class, but a class can implement an interface.
Glossary
interface : an interface in java can be created which declares methods and variables.
extends : keyword of java, used when a derived class is created from base class or when
derived interface is created from base interfaces.
implements : keyword of java, used when a class is created base on an interface, class has
to provide implementation details of methods declared in the base interface.
static : keyword of java, used when a method of data member or field can be used without
an object of class.
abstract : keyword of java, used with a class, imposed on class when it cannot be
instantiated.
multiple inheritance : a type of inheritance, though not allowed in java, but an interface
can be extended from multiple interfaces.
143
144
PDCA-201
Programming in Java
Unit-3.
Lesson - 9.
Packages
Chapter Index
Objectives
Introduction
System Packages
Naming Conventions
Creating Packages
Accessing a Package
Using a Package
Hiding Classes
Summary
Glossary
Model Questions
Objectives
145
146
Introduction
Java provides a way to physically as well as logically create a group of related classes and
interfaces by using package. Packages enable a user to organize classes logically. A package is
just like a container and can have classes, interfaces and subpackages inside it. There are many
inbuilt system packages in Java and at the same time java enables its users to create user-defined
packages.
9.1 Introduction
Sometimes, it may be required to logically group some related classes. For example if multiple
team members are working on a common project and it may happen that every one may create
some classes and interfaces etc. Now, to avoid name conflicts, it may be required to place classes
and interfaces created by one team member at a common place but different from others. Java
solves this problem by providing packages. A Package is like a container and is a logical group
of related classes, interfaces and enumerations etc. providing both name-space management and
access protection.
There are broadly two types of package in java, these are system packages or built-in package
and user-defined packages. Java itself uses packages to group related classes. There are many
built-in java packages such as java, lang, util, awt, javax, swing, io, net and sql etc. To create a
package, package statement is used in Java.
Following figure (extracted from http://java67.blogspot.in/2012/08/What-is-package-in-javahow-to-use.html) shows some of predefined or inbuilt system packages available in java
147
java.lang package provides basic language functionality and fundamental types like
Thread, Math etc.
148
java.net : networking operations, working with sockets and DNS lookups etc.
java.security: many classes and methods for encryption and decryption related tasks.
java.awt:basic hierarchy of packages for many GUI components like Button etc.
Any of these packages can be used in a program. Only java.lang is such a special package which
is included in our program by default. To use any other system package in a program, java
provides import statement. It is generally used at the top of the program. It has to be used once
for each package to be included. There are two ways in which import statement can be used.
First method is used when it is required to import all the classes built in a package and second
method is used when it is required to import only a specific class from a package.
Syntax of import statement is : Import PackageName ;
For example, to include or import every class of awt package, it can be written :
import java.awt.* ;
to include only Math class of java.lang package :
import java.lang.Math ;
Further, an import statement imports only classes and interface at outermost level from a
package, to import classes and packages from sub-packages available in a package, another
import statement is used for example :
import java.awt.* ; includes classes etc. only from outermost awt package.
import java.awt.event.* ; imports classes etc. from event sub-package of awt package.
Check Your Progress / Self Assessment Questions
Ques 1. Which package is included in every java program by default?
Ques 2. Which statement does java provide to include a package in java program?
149
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.
150
Apart from having inbuilt system packages in Java, user defined packages can also be created.
For this, java provides package statement. It can be used in a program when it is to be
specified that classes and interfaces created in the program will belong to which package. If
used, it must be the first executable statement of the program.
Syntax of Package statement is :
package UserDefinedPackageName ;
Where
package is keyword and statement of java, indicates that all classes, interfaces etc. in the
current program must belong to this package.
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
{
}
class ArtsStudent
{
151
}
Save above program in a file MyFirstPackage.java. Now there are two ways to compile above
program. First, compile it ordinarily using the command : javac MyFirstPackage.java. Compiler
will create two class files, MedicalStudent.class and ArtsStudent.class. To make these classes
usable, they must be stored in a folder named student. So create a student package and move
these two .class files in that package.
Second method is using -d option with javac command. This option tells the compiler to place
the .class files in the corresponding folder having same name as that of the package.
Corresponding folder is also created by the compiler itself.
Following figure shows that .class files are stored in the student folder.
152
Package statement can also be used to access a package. For example to add a new class to a
package that uses the classes already defined in the package, it can be referred in package
statement. All members of a package can access each other, as each member has a default
package level access.
Example : To access a package
In order to access a package i.e. to access classes that belong to student package created above,
we can write following program.
package student ;
class CollegeStudent
{
}
It will add another class CollegeStudent to the package, which accesses already defined classes
in the package.
After this contents of student folder are :
Figure 9.3
9.6 Using a Package
To use or access a user defined package, import statement is used in the same way as it is used
for system packages. But if any class is to be used outside the same package to which it belongs
then class must be declared as public. Only public classes and interfaces etc. are accessible
153
outside package. Any class or interface which has a default package level access can only be
accessed inside the package only, and cannot be accessed outside package.
Example : Using a Package
To use a class from a package, it must be declared as public in the package. So let us first create
a public class in the student package using following program.
package student;
public class NonMedicalStudent
{
public NonMedicalStudent( )
{
}
public showMessage( )
{
System.out.println(showMessage ( ) method of NonMedicalStudent class );
}
}
After this contents of folder student are as shown below :
154
package.
public class CollegeStudent2
{
}
Once an object of the class is created, it can easily use methods of the class defined in the
package.
155
Access specifier private will allow access only from the containing class.
Access specifier 'default' (i.e. no modifier) allows access from within the containing class
and containing package.
Protected access specifier will allow access from within the same class, package and any
of its subclasses.
156
Summary
Java provides a way to physically as well as logically create a group of related classes and
interfaces by using package.
A Package is like a container and is a logical group of related classes, interfaces and
enumerations etc. providing both name-space management and access protection.
java.lang package provides basic language functionality and fundamental types like Thread,
Math etc.
Some other java in-built packages are :
java.net : networking operations, working with sockets and DNS lookups etc.
Java uses its own method of naming classes, interfaces, methods, packages, data members in a
class etc. These are collectively known as java naming conventions.
Apart from having inbuilt system packages in Java, user defined packages can also be created.
For this, java provides package statement.
To use or access a user defined package, import statement is used in the same way as it is used
for system packages.
Each program (source file) when compiled creates a .class file. Each class file belongs to a
package. If no package is specified, default package is used which has no name, and .class file is
saved into current folder.
157
Glossary
java.lang : only system package that gets imported by default in any package.
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.
158
Model Questions
1. What is use of packages in java?
2. How can system package used in java?
3. How can a user-defined package be created in java?
4. How can we hide some of the classes in a package?
5. What are various advantages of packages in java?
159
PDCA-201
Programming in Java
Unit-4.
Lesson-10.
Exception Handling
Chapter Index
Objectives
Introduction
Summary
Glossary
Model Questions
160
Objectives
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.
Throwable that provide various methods for exception handling. Java also enables a user to
define his own user-defined exceptions.
161
In Java, a run time error is called an exception. An exception indicates an exceptional event
or situation. It is basically, an abnormal event, that occurs in a program at run time i.e. when
a program is actually running or executing. There are two things that can be done when an
exception occurs. First, just ignore it and let the program abort. Second, do some efforts to
resolve the issue and let the program continue. First method is called uncaught exceptions
and second method that is more technical and requires some efforts at programmers level is
called exception handling.
Actually, unlike some other programming languages like C, Java does not let a program abort
abruptly in between due to run time error in it. A program that aborts in between creates a
162
bad impression about the developer. So, Java provides an elegant way of dealing with run
time errors called exceptions, it called exception handling.
}
}
Output :
It shows that program is compiled successfully. But when it is executed, it aborts at line
number 5 displaying a message that there is arithmetic type of exception at line 5.
Suppose, in above program, instead of 5/0, we were using 5/x, where x is given by user, then
for any non-zero value of x, program will run successfully, but if user gives x as zero, then
again, above program will generate run time error. This is why it is said that run time errors
depend on user input.
Exceptions in java are represented by an inbuilt class named Exception, and it has many
subclasses that represent a particular type of exception, like, ArithmeticException as shown
in the output of above program. Exception class is part of java.lang package (default package
automatically included inside every java program).
Exception handling
To handle exceptions in a program is called exception handling. For exception handling,
Java provides try catch finally statements and try catch blocks. These statements are used
in combination i.e. try cannot be used without catch and catch cannot be used without try.
But, a single try can have multiple catch blocks.
163
That part (or block) of Java program which may generate a run time error is written in pair of
curly braces under the heading try and it is called try block.
Another part which tells java compiler what to do if try block generates a run time error, is
written under heading catch, and it is called catch block.
Using this try block and catch block in Java program is known as exception handling. When
a run time error occurs in try block, it is termed as exception is raised or exception is
thrown.
Example
public class exception1
164
try
{
}
catch(Exception e)
{
}
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
{
try
{
}
catch(ArrayIndexOutOfBoundsException e)
165
}
System.out.println("Bye");
}
}
try
{
}
catch(ArithmeticException e)
{
System.out.println("Sorry,
an
exception
occurred,
Program
terminating....");
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("ArrayIndexOutOfBounds, Program terminating....") ;
}
System.out.println("Bye");
}
}
Output
166
}
catch (IOException e)
167
{
}
finally
{
try
{
reader.close();
}
catch(Exception e)
{
}
}
System.out.println("--- File End ---");
}
}
This program, tries to open a text file Output.txt for reading its contents. In both cases i.e.
when program ends successfully or if any exception occurs in between, file must be closed
before program ends. This is achieved using finally block which closes the file using
reader.close( ). Note that finally block itself has a try catch block. It is required in this example
because reader.close( ) itself may throw an exception.
Output of above program depends on the contents of output.txt file.
168
Throw objectname ;
Where throw is keyword of java, and object name is new object of any exception type defined in
Java.
The code or method that throws an exception has to be specified using throws clause , throws
clause indicates that this code may generate a run time error.
Example
public class ThrowingException extends Exception
{
try
{
}
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,
169
Now, if any error occurs somewhere inside any method then this stack information helps to
identify that method by displaying the stack contents from top to bottom, this is called stack
trace. In this way, printStackTrace() shows the location in the source code where the error or
exception occurred, thus allowing the developer who wrote the program to see what went wrong.
It actually, shows several lines on the output screen. First line consists of several strings. It
contains the name of the throwable sub-class and information about the package. From second
line onwards, it describes the error position/line number beginning with "at".
Example
class PrintStackTrace
{
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
170
There are two types of exceptions in Java. First type is JVM Exceptions which are exceptions
thrown exclusively by JVM. For example, all exceptions discussed in this lesson till now are
JVM
exceptions.
Examples
include:
NullPointerException,
Arithmetic
Exception,
thrown
explicitly
by
the
application
or
the
API.
These
include
IllegalArgumentException, IllegalStateException.
l=b=0 ;
}
NotRectangle(int x, int y) throws NotRectangle //parameterized constructor.
{
l=x ; b=y ;
}
}
public String toString( )
{
}
171
172
Summary
When a program is developed it may have some errors in it. Those errors or bugs affect a
program in many ways. Some dont allow a program to run, and some produce wrong output.
Still some other type of error may cause a program to crash in between.
Complie time errors are caught by the java compiler when a program is compiled. Runtime
errors occur when a program actually runs. A program with a run time error may abruptly abort
in between with only partial work done, and will have to be restarted after modifying
In Java, a run time error is called an exception. An exception indicates an exceptional situation
or event. To handle exceptions in a program is called exception handling. For exception
handling Java provides try catch statements and try catch blocks.
One try block can have either one or more catch blocks following it. This is logical and
sometimes necessary, because the risky code given inside try block may generate more than one
type of exception. When an exception occurs in try-block at a statement, say at statement-x,
control transfers to corresponding catch-block (skipping the code below statement-x in try
block), and then code given below catch-block is executed and finally program ends.
Sometimes it may be required in a program to generate an exception forcibly. This is performed
in Java using throw statement. printStackTrace method of Exception handling facility provided
by Java can be used for debugging purpose also. It can be used to ascertain where a bug has
exactly occurred.
173
Java language enables a programmer to define his own exceptions called user defined
exceptions. This becomes necessary when we wish to have exception types which have a
behavior different from those provided by system exceptions.
174
Glossary
Run time Error : occur at run time, are not detected by compiler.
try : java statement and keyword that encloses a code that may generate an exception.
catch : Java statement and keyword, used to write exception handling part.
Finally : java keyword, used to create finally block that always runs irrespective of
occurrence of exception.
175
Model Questions
Ques. 1. What is exception? How an exception is handled in Java?
Ques. 2. What is need of having multiple catch blocks with a single try block in Java? Give
example.
Ques. 3. Create a user defined exception, that does not allow a new student object with roll no of
three digits.
Ques. 4. What is use of printStackTrace ( ) method?
Ques. 5. Write a note on various system defined exceptions in Java?
176
PDCA-201
Applets
Unit-3. Lesson - 11
Applets
Chapter Index
Objectives
Introduction
Applet Tag
Types of Applets
Summary
Glossary
Model Questions
Objectives
177
178
11.1 Introduction
Java provides another way of creating a special kind of GUI based programs that are embedded in a web
document called applets. The applets can run inside a web browser or by using utility appletviewer for
testing purpose. The applets can also be transported over the internet along with the web document
using the HTTP protocol. Different arguments can be sent to applets at run time making it dynamic and
flexible in nature.
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.
179
180
Output
Once the applet program is designed and ready to run, the following steps are required to build the
compile code:
Savesource file as MyApplet.java. The name of Java source file must be same as the applet class.
Every applet has five stages in this life cycle, each of which has a matching method. You can
override these methods to gain access to the life cycle of the applet's life. The five stages of an
applet's life cycle are shown in Fig. 11.1. The default implementation of these methods is
provided which does nothing. Applets need not to override all of the methods. Because applets
run in a web browser, therefore these methods are not called directly by the applet. The browser
or applet viewer calls these methods at appropriate times during the life cycle of an applet.
181
Initialization State
In this phase, the applet is first initialized with values that are used by the applet later on.. The
method init( ) is overridden in the class for this purpose. This method is called by the web
browser when an applet is loaded first time or reloaded. It serves the same purpose as the
constructor in the console based program.
RunningState
The start phase occurs after the initialization phase when the web browser starts running the
applet or when the applet restarts again. The method start( ) is overridden in the class for this
purpose and is called automatically by the web browser every time the web page containing the
applet is revisited.
Stop State
The applet enters in this phase, when it is no longer visible on the screen such as when the user moves
to a different Web page. The stop( ) method used for this purpose, is automatically called by web
browser to tell the applet that it should stop its execution. It is called automatically by java when the
web page that contains current applet is replaced by another page.
DisplayState
182
The paint phase occurs whenever the applet's output is drawn on the screen for the first time as
well as whenever the applet's output must be restored or changed. For this purpose, the paint( )
method is used and is called once after start( ) method is called and again each time the web
browser is activated.
Whenever the applet needs to redraw its output, the paint( ) methodis called. The paint( ) method takes
one parameter of type Graphics. This parameter contains the graphics context, which provides the
graphical environment in which the applet is running. This context is used to draw output to the applet
window. The Graphicsclasscontains several methods which can be used to draw string, line, oval,
rectangle etc. Inside paint( ) method, the drawString( ) method is used that outputs a string starting at
the specified X,Y location. Its syntax is:
void drawString(String msg, int x, int y)
Here, msgis the string to be output beginning at position x,y. In a Java window, the upperleft
corner is at location (0,0).
DeadState
This phase occurs when an applet ends and the system is ready to deallocate memory, i.e. to remove
the applet from memory. Like the initialization phase, the destroy cycle occurs only once. If your applet
has captured resources that need to be cleaned up before the applet exits, this is the place to do it. The
destroy( ) method is called by the browser only once, when an applet shuts down.
The following example demonstrates the use of some of the applet life cycle methods:
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
String msg = "" ;
public void init( )
183
{
msg += "Init method " ;
}
public void start( )
{
msg += "Start method " ;
}
public void paint(Graphics g)
{
msg += "Paint method " ;
g.drawString(msg,40,20);
}
}
Output
184
Comment Section
The comment section is used to insert comments in the html code and makes the program more user
friendly. The comments are not executed by the browser and are not displayed in the browser. The <!-...--> tag is used to insert single or multiple line comments in the code. For example
185
Head Section
The head section contains the information about the HTML document like title, styles, links, scripts, and
other meta information.
The <style> tag is used to declare style information for an HTML document.
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.
<html>
<head>
<title>Web Site of PTU</title>
<style>
h1 {color:blue;}
p {color:red;}
</style>
<base href="http://http://www.ptu.ac.in//" target="Home Page">
<link rel="stylesheet" type="text/css" href="sheet.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript">
</head>
186
<body></body>
</html>
Body Section
The body section contains all the contents of the html document, such as texts, hyperlinks, images, lists,
tables, forms etc. HTML provides various tags to place these elements in the body of the document.
Tags with their attributes can also be used to control how the elements look on the page.
A very simple example of HTML code is given below. Type this code in notepad and save as Test.html.
After this, just double click on the icon where the file is saved. It will open in web browser.
<html>
<head><title>My first web page </title></head>
<body>
<b>Welcome !</b>
<br />
<b>This is body of web page containing main contents of the document.</b>
</body>
<html>
187
Applet Tag
HTML provides APPLET to embed applets in a web page. It is a paired tag (means, it opens with <applet>
and closes with </applet>). This tag is used to embed an applet in a web page and provides the
necessary information about the location of the appletss class file. Applet tag has many attributes that
can be used to provide some additional information about the applet being embedded.
The applet will be loaded and executed by a Javaenabled web browser when it encounters the applet
tag within the HTML file. The syntax of Applet tag is:
<APPLET code = appletName.class width=value height =value>
</APPLET>
It specifies the name of the .class file. If the .class file is in some other folder than
.html file, its path has to be mentioned.
width
height
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.
188
Double click the HTML file and it will be loaded in a default web browser to display the output.
2.
An alternative way to run the applet is with the utility appletviewer using the following command
at the command prompt: appletviewer< html filename>. It will invoke a window with the applet
running inside it.
Types of Applets
189
In Java, applets are of two types: Signed and Unsigned. The unsigned applets are considered to be untrusted and operate within a security sandbox that allows only a set of safe operations. The unsigned
applet can only communicate with the server from which it was downloaded and cannot access the
resources of the local machine on which it is running.
On most browsers, unsigned applets cannot perform the following tasks:
Applets cannot access client resources such as the local file system and executable files.
Applets cannot communicate with any server other than the server from which they were
downloaded.
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.
Include main( ) method in an applet that will execute when you run applet as an application.
2.
3.
4.
Start the applet by calling init( ) from the main( ) method and then start( ) if these methods are
overridden in applet.
5.
6.
190
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet
{
String msg = "Hello Everybody..." ;
public void paint(Graphics g)
{
g.drawString(msg,40,20);
}
public static void main(String args[ ])
{
Applet helloApplet = new HelloApplet( );
helloApplet.init( ) ;
Frame window = new Frame("Here it runs as an Application") ;
window.setSize(300, 200) ;
window.add(helloApplet) ;
window.setVisible(true) ;
// Make the window visible
}
}
Output
191
The parameter names used and their corresponding values are by default strings, whether or not they
are quoted. Therefore an applet checks that a valid string is returned as a parameter value. For each
parameter the NAME attribute must be specified, but the VALUE attribute is optional. The applet
should use a default value if no valid string is returned.The Applet class of the package java.awt.applet
contains a getParameter( ) method used to retrieve a value of the specified parameter as a String
object: public String getParameter(String name)
It returns the value of the named parameter in the HTML tag. The name argument is case
insensitive.The parameter passing mechanism can be illustrated with the help of an example:
import java.applet.*;
import java.awt.*;
public class parameterApplet extends Applet
{
String arg = "Welcom to Java Applet." ;
public void paint(Graphics g)
{
String msg = getParameter("Message");
if (msg == null)
msg = arg ;
g.drawString(msg, 50, 25);
}
192
Output
193
Ques 10. Which method is used to receive argument values from html document?
Summary
Java offers GUI based special programs called applets that are executed in a java enabled web browser
and can transport over the internet using Http protocol alongwith web document. The Applet class
contained in java .applet package is used to create an applet. The Applet class contains several methods
that are used to control the execution of an applet. An applet is a part of web documents and can be
inserted in an html page using <applet > tag. To run an applet, open the web page containingthe applet
in any Java enabled web browser or use the utility appletviewer. To create an applet, the following
inbuilt packages are used:
Applets are of two types: signed and unsigned. The unsigned applets are executed in a restricted
environment and cannot access the resources of the client machine, whereas, the signed applets can
access the resources. To make the applet dynamic in nature, an applet and html document can
communicate with others through the passing of parameters.
Glossary
start( ) : start method is overridden used in java class, it provides what an applet will do.
194
Java.awt: abtract window toolkit package of java that provides window environment to an
application.
HTML : Hyper Text Markup Language, a language used to design web pages. Its commands are
called tags.
java.applet : Another builit in package of java that provides Applet class to create an applet.
appletviewer: Java built in utility to run and test an applet, without using browser.
195
Model Questions
1. What is the difference between an application and an applet?
2. How can an applet be embedded in a web document.
3. Explain life cycle of an applet.
4. What is the use of <head> and <body>sections in HTML?
5. What is use of Applet tag in HTML ?
6. How can arguments be sent to an applet ?
7. What is the difference between signed and unsigned applets?
8. What are various advantages of applets in java?
9. How an applet can be used as an application ?
196
PDCA-201
Advanced Applet Programming
Unit-3. Lesson - 12
Chapter Index
Objectives
Introduction
Summary
Glossary
Model Questions
Objectives
197
12.1 Introduction
If required, Java applets can be designed to communicate with a web page, this feature makes applets
interactive and dynamic in nature. Any number of values (called arguments) can be passed from the
webpage page to the applet.At runtime, the applet retrieves the arguments from the web page using
the PARAM attribute of the applet tag. The layout of an applet can be controlled by setting the different
attributes of an applet tag. Applets can perform input/output operations. For security reason, an applet
created in Java is executed inside a sandbox by a web browser. It prevents an applet from accessing
local file system or clipboard of the local machine.
198
CODEBASE
This attribute is optional which inform the browser that the applet class file are found under the
directory URL specified in the CODEBASE tag. The CODE attribute is then interpreted relative
to this directory.
<APPLET codebase = projects/applets code = myApplet.class width = 200 height = 200>
</APPLET>
ARCHIVE
All classes and resources that are required by an applet can be bundled together in a JAR file.
(JAR is a compressed file, and can be created with jar utility of Java). The ARCHIVE attribute is
an optional, used to specify the JAR file. This file is fetched from the web server before the
applet is loaded. This technique is used to speedup the loading of an applet.
<APPLET archive = appletClasses.jar code = myApplet.class width = 200 height = 200>
199
</APPLET>
ALT
The ALT attribute is an optional attribute. It is used to specify a short text message that should
be displayed if the browser understands the APPLET tag but is currently unable to run Java
applets.
<APPLET code = myApplet.class alt = Java runtime is unable to run applet width = 200
height = 200>
</APPLET>
Alternate Text
In case, a browser does not support applets, then the optional alternative HTML text will be
displayed. This text is specified inside the <Applet> tag, in case browser is java enabled and can
run the applet then this text will be ignored by the browser.
<APPLET code = myApplet.class width = 200 height = 200>
Sorry, the browser cannot run the applet.
</APPLET>
NAME
This attribute can be used to assign a name to the applet within an HTML page. This name can
be used by applets to identify each other for inter-applet communication. Assigning a name to
the applet is useful in case, html page contains more than one applet.
ALIGN
This attribute specifies the alignment of the applet within the HTML page. This attribute can be
assigned to one of these possible values: LEFT, RIGHT, TOP, BOTTOM and MIDDLE.
200
<APPLET code = myApplet.class width = 200 height = 200 align = TOP hspace=20
vspace=25>
</APPLET>
The use of attributes in applet tag is demonstrated with the help of an example:
import java.awt.* ;
import java.applet.* ;
public class MyApplet extends Applet
{
public void paint(java.awt.Graphics g)
{
g.drawString("Applet Using different applet tags",50,25);
}
}
Here is corresponding html code to display applen in a web page.
<HTML>
<Head>
<Title>
A Simple Applet
</Title>
</Head>
<Body>
<Applet code="MyApplet.class" alt = "Browser is unable to run applet !"
width="350" height="150" align = BOTTOM vspace = 25 hspace = 25>
</Applet>
</Body>
</HTML
Output
201
The status bar is place at the bottom of the web browser or applet viewer which can be used to
display the message. The message can be displayed using the showStatus(String msg) method.
The status bar is used to display the information that is helpful to the users. There are two
additional methods of the AWT package that are commonly used to set the foreground and
background colors. The syntax is:
void setForeground(Color c)
void setBackground(Color c)
These methods takes a single argument, which is an instance of Java.awt.Color class. The calss
Color defines several constants such as Color.blue, Color.red, Color.gray, Color.darkGray etc. to
represent different colors that can be used to specify colors. The following program demonstrates
the use of showStatus( ) method:
import java.awt.*;
import java.applet.* ;
public class ShowStatusApplet extends Applet
{
String msg = "" ;
public void init( )
{
setBackground(Color.gray) ;
setForeground(Color.blue) ;
msg = "Applet setting the foreground and background colors" ;
}
public void paint(Graphics g)
{
202
g.drawString(msg,40,20);
showStatus("This message is displayed in the status window....") ;
}
}
Output
So far, we have only display text strings in the applet window. The class Graphics of the AWT package
defines several methods to draw different shapes like lines, rectangles, circles etc. Each shape can be
drawn filled or without filled having edges only. The following program shows the use of drawing
methods:
import java.awt.*;
import java.applet.*;
public class ShapeApplet extends Applet
{
public void init( )
{
setBackground(Color.white) ;
}
public void paint(Graphics g)
{
g.setColor(Color.black);
203
g.drawString("Draw Shapes",150,20);
g.drawRect(100,100,100,100);
g.setColor(Color.gray);
g.fillRect(110,110,80,80);
g.setColor(Color.black);
}
}
Output
Another example showing the use of different shapes with different color combinations.
importjava.awt.*;
importjava.applet.*;
public class FlagApplet extends Applet
{
public void init( )
{
setBackground(Color.gray) ;
}
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(100,40,10,150);
204
g.setColor(Color.orange);
g.fillRect(110,40,170,35);
g.setColor(Color.white);
g.fillRect(110,75,170,35);
g.setColor(Color.blue);
g.fillOval(175,77,30,30) ;
g.setColor(Color.green);
g.fillRect(110,110,170,35);
}
}
Output
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?
205
is also instructed to fetch or read these parameter values from web page. A Java applet has the
capability of retrieving the parameter values passed from the html page. The argument values
stored in html code are passed to the applet at runtime. This feature of applets make them
interactive and dynamic in nature.
The <PARAM> attribute of the <applet> tag is used to specify the (name , value) pair.
<APPLET code=AppletClassName width=w height=h>
<param name="p1" value="v1">
<param name="p2" value="v2">
returned.The package java.applet contains an Applet class that contains a getParameter() method
used to retrieve value of specified parameter as a String object. It syntax is :
public String getParameter(String pname) - Returns the value of the parameter pname defined
in the <applet> tag of HTML in a web page. The pname argument is case insensitive.
The parameter passing mechanism can be illustrated with the help of an example:
import java.applet.*;
import java.awt.*;
public class ParamApplet extends Applet
{
int rollno ;
String name ;
String class_name ;
String dept_name ;
public void init( )
{
String rno ;
rno = getParameter("prollno");
if(rno != null)
rollno = Integer.parseInt(rno) ;
name = getParameter("pname") ;
206
class_name = getParameter("pclass") ;
dept_name = getParameter("pdept") ;
}
public void paint(Graphics g)
{
g.drawString("Roll No = "+rollno, 0, 15);
g.drawString("Std Name = "+name, 0, 30) ;
g.drawString("Class = "+class_name, 0, 45) ;
g.drawString("Class = "+dept_name, 0, 60) ;
}
}
Here is the corresponding HTML Code
<HTML>
<HEAD>
<TITLE>Parameter Passing to Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="ParamApplet.class" width="550" height="200">
<PARAM name="prollno" value="201515089">
<PARAM name="pname" value="Rajan Malhotra">
<PARAM name="pclass" value="MCA Semester IV">
<PARAM name="pdept" value="Department of Computer Science & Engineering">
</APPLET>
</BODY>
</HTML>
Output
207
one of the constants LEFT, RIGHT, TOP, BOTTOM and MIDDLE and align the display
towards left, right, top, bottom and middle of the available space reserved for the applet in a html
page.
Check Your Progress / Self Assessment Questions
Ques 3. Which attributes of an applet tag are used to send arguments to an applet?
Ques 4. Is there any limit to number of arguments send to an applet?
208
209
210
this purpose, the numerical values are first converted into strings and then call the drawstring( )
method . Any numeric value can be converted into string by using a static method of the class
String. The syntax is:
String String.valueOf(numeric value) ;
Example:
import java.awt.* ;
import java.applet.* ;
public class DisplayApplet extends Applet
{
public void paint(Graphics g)
{
double phy = 95.50, chem = 72.50, math = 66.0, result = 0.0 ;
String percent ;
result = ( phy + chem + math) / 300 * 100 ;
percent = String.valueOf(result) ;
g.drawString("The percentage is "+percent, 100,75) ;
}
}
Output
211
import java.awt.* ;
import java.applet.* ;
public class InputApplet extends Applet
{
TextField txtRollno, txtPhy, txtChem, txtMath ;
public void init( )
{
txtRollno = new TextField(15) ;
txtPhy = new TextField(3) ;
txtChem = new TextField(3) ;
txtMath = new TextField(3) ;
add(txtRollno) ;
add(txtPhy) ;
add(txtChem) ;
add(txtMath) ;
}
public void paint(java.awt.Graphics g)
{
double phy = 0.0, chem = 0.0, math = 0.0, result = 0.0 ;
String strPhy, strChem, strMath, strResult ;
try
{
strPhy = txtPhy.getText() ;
phy = Double.parseDouble(strPhy) ;
strChem = txtChem.getText() ;
chem = Double.parseDouble(strChem) ;
strMath = txtMath.getText() ;
math = Double.parseDouble(strMath) ;
}
catch(Exception e) { }
result = ( phy + chem + math) / 300 * 100 ;
g.drawString("The percentage is "+result, 150,125) ;
}
}
Output
212
213
Summary
Java provides static and dynamic applets. The static applets always run in the same fashion and display
the same results every time they run. The dynamic applets are flexible and run in a different fashion and
produce different outputs. Different inputs can be passed from html page to an applet at runtime and
the applet behaves accordingly. The layout of an applet can be controlled using different attributes of
applet tag. The input/output operations can also be performed on an applet window using the
drawstring( ) method of the Graphics class.
Glossary
Codbase : this is an optional attribute of applet tag and used to specify the location of .class file,
in case it is not in the same folder as .html file.
<Name, Value> attributes <param> tag is used to specify a attribute name and its value. The
attribute name is used in applet to retrieve the its associated value from the html page.
AWT control components such as TextField and TextArea is used to capture input from the user
in an applet window.
214
Ans 5. HTML5.
Ans 6. <object>
Ans 7. drawstring(String text)
Ans 8. String.valueOf(numeric value)
Model Questions
1. How applet and html page can communicate with each other?
2. What is the use of (name, value) attributes of the <PARAM> tag.
3. What are different layouts to align an attribute?
4. How can numeric values be displayed in an applet?
5. Explain various attributes of applet tag available in HTML?
6. How can an applet receive input from the user?
7. What is use of <object> in HTML 5?
8. What is use of code and codebase attributes of applet tag?
215