0% found this document useful (0 votes)
11 views

JAVA NOTES

Java notes For 2nd year BSC HONORS COMPUTER SCIENCE STUDENTS

Uploaded by

SRDC CDE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

JAVA NOTES

Java notes For 2nd year BSC HONORS COMPUTER SCIENCE STUDENTS

Uploaded by

SRDC CDE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 116

2 | Java Fundamentals

UNIT – 1
JAVA FUNDAMENTALS
Introduction
Object Oriented Programming (OOP) is an approach to program organization and
development, which attempts to eliminate some of the pitfalls of conventional
programming methods by incorporating the best of structured programming features with
several new concepts. However not all languages are suitable to implement the OOP
concept easily. Languages that support OOP features include Smalltalk, C++, Ada and
object pascal.
Object Oriented Paradigm
The major Objective of Object Oriented approach is to eliminate some of the flaws
encountered in the procedural approach. OOP treats data as a critical element in the
program development and does not allow it to flow freely around the system. It ties data
more closely to the functions that operate on it and protects it from unintentional
modification. OOP allows us to decompose a problem into a number of entities called
objects and then build data and functions around these entities. The combination of data
and methods make up an object.
Method Method

Method Data Method

The data of an object can be accessed only by the methods of associated with that objects.
However methods of one object can access the methods of other objects. Some of the
features of object-oriented paradigm are:
1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data structures are designed such that they characterize objects.
4. Methods that operate on the data of an object are tied together in the data structure.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through methods.
7. New data and methods can be easily added whenever necessary.
8. Follow bottom-up approach in program design.
Basic Concepts Of Object Oriented Program
Object Oriented Program is an approach that provides a way of modularizing programs
by creating partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules on demand.
Objects and Classes
Objects are the basic runtime entities in an object oriented system. They may represent a
person, a place, a bank account, or any item that the program may handle. Program
objects should be chosen that they mach closely with the real world objects. Each object
contains data and code to manipulate that data
3 | Java Fundamentals

Object
PERSON

Name .
Data
Basic pay

salary()
methods
tax()

.The entire set of data and code of an object can be made user defined data type using the
concepts of a class. We can create any number of objects belonging to that class. A class
may be thought of as a ‘data type’ and an object as a variable of that data type.
Data Abstraction and Encapsulation
The wrapping up of data and methods into a single unit called class is known as
Encapsulation. The data is not accessible to the outside the wrapper and only those
methods which are wrapped in the class can access it. These methods provide the
interface between the object’s data and the program. This insulation of the data from the
direct access by the program is called data hiding.
Abstraction refers to the act of representing essential features without including the
background details and explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and methods that
operate on these attributes.
Inheritance
Inheritance is the process by which object of one class acquired the properties of objects
of another class. The concept of inheritance provides the idea of reusability. This means
that we can add additional features to an existing class without modifying it. This is
possible by deriving a new class from an existing one. A new class will have the
combined features of both the classes. The derived class is known as subclass.
Polymorphism
Polymorphism is a feature that allows one interface to be used for a general class of
actions. The specific action is determined by exact nature of the situation. Polymorphism
places an important role in allowing objects having different internal structures to share
the same external interface.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at runtime. It is associated with polymorphism and
inheritance. A procedure call associated with a polymorphism reference depends on the
dynamic type of that reference.
Benefits of OOP
The principal advantages are
1. Through inheritance we can eliminate redundant code and extend the use of existing
class
2. We can build the programs from the standard working module that communicate with
one another. This leads to saving of development time.
3. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
4. It is possible to have multiple objects to coexist without any interference.
4 | Java Fundamentals

5. It is easy to partition the work in a based on objects.


6. Object oriented system can be easily upgraded from small to large systems.
7. Software complexity can be easily managed.
Java History
Java is a general purpose object oriented programming language developed by Sun Micro
Systems, U.S.A in 1991 originally called Oak by James Gosling. Java was designed for
the development of software for consumer electronic devices like T.V.’s, V.C.R.’s such
other electronic machines. The java team which included Patrick Naughton discovered
that existing languages like C, C++ has limitations in terms of both reliability and
portability. However they modelled their new language Java on C, C++ but removed
number of features of C and C++ and made java simple, reliable, portable and powerful.
Java Features
Compiled and Interpreted
Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system. First Java compiler translates the
source code into bytecode instruction. In the second stage Java interpreter generates
machine code that can be directly executed by the machine.
Platform Independent & Portable
Java programs can be easily moved from one computer system to another. Changes and
upgrades in operating system, processor and system resources will not force any changes
in java programs.
Object Oriented Program
Java is a true object oriented language. Everything in Java is an object. All program code
and data reside within object and classes.
Robust & Secure
Java is a robust language. It provides many safeguards to ensure reliable code. Java also
incorporates the concept of exception handling which captures serious errors and
eliminates any risk of crashing the system.
Distributed
Java is designed as a distributed language for creating applications on Networks. It has
the ability to share both data and programs. This enables multiple programmers at
multiple remote locations to collaborate and work together on a single project.
Simple, Small & Familiar
Java is a small and simple language. Many features of C & C++ that are either redundant
or sources of unreliable code are not part of Java. To make the language look familiar to
the existing programmers, it was modelled by C & C++ language.
Multithreaded & Interactive
Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. The java runtime comes with tools that support multiprocess
synchronization and constructs smoothly running interactive system.
High Performance
Due to the use of interpreted bytecode and the incorporation of the multithreading
enhances overall execution speed of java programs.
Dynamic & Extensible
5 | Java Fundamentals

Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods, and objects. Java supports functions written in other languages such as C and
C++.
Easy of Development
Java supports features such as Generics, enhance for loop, Autoboxing or unboxing,
Typesafe Enums, varargs, Static import and Annotation. These features reduce the work
of the programmer.
Differences between Java and C
Java is an objecr oriented language. In an effort to build simple and safe language, the
java team did not include some of the c features in Java.
 Java does not include the C language statement keywords sizeof, and typedef.
 Java does not contain the data types struct and union.
 Java does not define the type modifiers keywords auto, extern, signed, and
unsigned.
 Java does not support an explicit pointer type.
 Java does not have a pre-processor and therefore we cannot use #define,
#include, and #ifdef.
 Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword done in C.
 Java adds new operators such as instanceof and >>>
 Java adds labelled break and continue statements.
 Java adds many features required for object oriented programming.
Differences between Java and C++
 Java does not support operator overloading
 Java does not have template classes as in C++
 Java does not support multiple inheritances of classes.
 Java does not support global variables.
 Java does not use pointers.
 Java has replaced the destructor functions with a finalize () method.
 There are no header files in Java.
Java & Internet
Java is strongly associated with the Internet because of the fact that the first application
program written in Java was HotJava, a Web browser to run applets on Internet. Internet
users can use Java to create applet programs and run them locally using a “Java-enabled
browser” such as HotJava. They can also use a Java-enabled browser to download and
applet located on a computer anywhere in the Internet and run it on his local computer. In
fact, Java applets have made the Internet a true extension of the storage system of the
local computer. The ability of Java applets to hitch a ride on the Information
Superhighway has made java a unique programming language for the Internet. In fact,
due to this, Java is popularly known as Internet Language.
Java & World Wide Web
World Wide Web is an open ended information retrieval system designed to be used in
the Internet’s distributed environment. Java could be easily incorporated into the web
system. Before Java the World Wide Web was limited to display of still images and texts.
However the incorporation of Java into web pages has made it capable of supporting
animation, graphics, games and wide range of special effects. With the support of Java
the web has become more interactive and dynamic.
6 | Java Fundamentals

Java’s Interaction with Web


Java communicates with a web page through a special tag called <APPLET>. The
following figure illustrates the process. Remote computer
User’s computer
Applet Source Code
ByteCode

HTML ByteCode
Java web browser document
Applet Tag
request HTML document

Output Web server

1. The user sends a request for an HTML document to the remote computer’s Web
server. The web server is a program that accepts request, process the request, and
sends the required document.
2. The HTML document is returned to the user’s browser. The document contains the
APPLET tag, which identifies the applet.
3. The corresponding applet bytecode is transferred to the user’s computer. This
bytecode had been previously created by the Java compiler using the Java source
code file for that applet.
4. The Java-enabled browser on the user’s computer interprets the bytecodes and
provides output.
5. The user may have further interaction with the applet but with no further
downloading from the provider’s web server. This is because the bytecode contain all
the information necessary to interpret the applet.
Web Browsers
A large portion of the Internet is organized as the World Wide Web which uses hypertext.
Web browsers are used to navigate through the information found on the net. They allow
us to retrieve the information spread across the Internet and display it using the hypertext
markup language(HTML). Examples of Web browsers include :
 HotJava
 Netscape Navigator
 Internet Explorer
HotJava
Htojava is the web browser from Sun Microsystems that enables the display of interactive
content on the web, using the java language. HotJava is written entirely in Java bad
demonstrates the capabilities if the java programming language.
Netscape Navigator
Netscape Navigator, from Netscape Communication Corporation, is a general-purpose
browser that can run java applets. It also supports JavaScript, a scripting language used in
HTML documents.
Internet Explorer
Internet Explorer is another popular web browser developed by Microsoft. Explorer uses
a just-in-time (JIT) compiler which greatly increases the speed of execution.
Java Environment
7 | Java Fundamentals

Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development
Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also
known as the Application Programming Interface (API).

Java Development Kit


The Java development comes with a collection of tools that are used for developing and
running java programs. They include :
 appletviewer - Enables us to run Java applets(without using a browser)
 java - Java interpreter which runs applets and applications by reading
and interpreting bytecode files.
 javac - The Java compiler, which translates java source code to bytecode
files.
 javadoc - Creates HTML - format documentation from Java source code
file.
 javah - produces header files for use with native methods.
 javap - Java disassembler, which enables us to convert bytecode files into
a program description.
 jdb - Java debugger, which helps us to find errors in our programs.

Application Program Interface (API)


The Java standard library (or API) includes hundreds of classes and methods grouped
into several functional packages. Most commonly used packages are:
 Language support package - A collection of classes and methods required for
implementing basic features of Java.
 Utilities package - A collection of classes to provide utility functions
such as date and time functions.
 Input/Output package - A collection of classes required for Input/Output
manipulation.
 Networking package - A collection of classes for communicating with
other computers via Internet.
 AWT package - The Abstract Window Tool kit package contains
classes that implements platform-independent
graphical user interface.
 Applet package - This includes a set of classes that allows us to
create Java applets.

Structure of a Java program


A Java program may contain many classes of which only one class defines a main
method. Classes contains data members and methods that operate on the data members of
the class. Methods may contain data type declarations and executable statements. To
write a Java program first define classes and then put them together. A Java program may
contain one or more sections as shown below

Documentation Section
8 | Java Fundamentals

Package Statement

Import Statements

Interface Statements

Class Definitions

Main Method Class

Main Method Definition

Documentation Section
The documentation section comprises a set of comment lines giving the name of the
program, the author, and other details. Java permits both single line comments and
multiline comments. The single line comments begin with // and end at the end of the
line. Multiline comments starts with /* and ended with */
Package Statement
The first statement allowed in a Java file is a package statement. This statement declares
a package name and informs the compiler that the classes defined here belongs to this
package. A package statement is optional.
Ex : package student;

Import Statements
Using import statements we can have access to the classes that are part of other named
packages.
Ex: import student.test;
This statement instructs the interpreter to load the test class contained in the package
student.
Interface Statements
An interface is like a class but includes a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance
features in the program
Class Definitions
A Java program may contain multiple class definitions. Classes are primary and essential
elements of the program. The number of classes used depends on the complexity of the
program.
Main Method Class
Since every Java standalone program requires a main method as its starting point, this
class is a essential part of the program. The main method creates objects of various
classes and establishes communications between them. On reaching the end of the main
method the program terminates and the control passes back to the operating system.
Java Character Set
The smallest units of Java language are the characters used to write Java tokens. These
characters are defined by the Unicode character set, an emerging standard that tries to
create characters for a large number of scripts worldwide. The Unicode is a 16-bit
9 | Java Fundamentals

character coding system and currently supports more than 34,000 defined characters
derived form 24 languages.
Java Tokens
Smallest individual units in a program are known as tokens. The compiler recognizes
them for building up expressions and statements. Java language include five types of
tokens.
 Reserved words
 Identifiers
 Literals
 Operators
 Separators
Reserved Words
Java language has reserved 50 words as key words. These key words, combined with
operators and separators according to the syntax, form definitions of the Java language.
Since keywords have specific meaning in Java we cannot use them as names for
variables, classes, methods and so on. All key words are written in the lower case letters.
Identifiers
Identifiers are programmer designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifiers follow
the following rules
1. They can have alphabets (A - Z, a – z), digits ( 0 - 9), underscore( _ ) and dollar sign
characters( $ ).
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
Literals
Literals in a Java are sequence of characters that represent constant values to be stored in
variables. Java language specifies five major types of literals.
 Integer Literals
 Character Literals
 Real Literals (or) Floating Literals
 String Literals
 Boolean Literals
Operators
An operator is a symbol that takes one or more arguments and operates on them to
produce results.
Separators
Separators are symbols used to indicate where groups of code are divided and arranged.
Parentheses ( ) Used to enclose parameters in method definitions and invocation. Also
define precedence in expression and surrounding cast types

Braces { } Used to contain the values of automatically initialized arrays and to define
a block of code for classes, methods and local scopes

Brackets [ ] Used to declare array types and dereferencing array values

Semicolon ; Used to separate statements.

Comma , Used to separate consecutive identifiers in a variable declaration, also used


10 | Java Fundamentals

to chain statements together inside a “for” statement

Period . Used to separate package names from sub-packages and classes; also used
to separate variable or method from a reference variable.

Java Statements
A statement is an executable combination of tokens ending with a semicolon (;) mark.
Statements are usually executed in sequence in the order in which they appear. However
it is possible to control the flow of execution, if necessary using special statements. Java
implements the following statements.
These do nothing and are used during program development as a
Empty Statement
place holder

Any statement may begin with a label. Such labels must not be
Labelled statement keywords, already declared local variables or previously used labels.
Labels in Java are used as the arguments of jump statements.

Java has seven types of expression statements :


Expression statement Assignment, pre-increment, pre-decrement, post-increment, post-
decrement, method call and Allocation expression

These select one of several control flows. Three types of selection


Selection statement statements in Java:

if, if-else, and switch

These specify how and when looping will take place. There are three
Iteration statement types of iteration statements:

while, do, and for

Jump statements pass control to the beginning or end of the current


block, or to a labelled statement. Such labels must be in the same
Jump statement block, and continue labels must be on an iteration statement. The
four types of jump statements are:

break, continue, return and throw

Synchronization These are used for handling issues with multithreading.


statement

Guarding statements are used for safe handling of code that may
Guarding statement cause exceptions. These statements use the keywords try, catch, and
finally

Command Line Arguments


Command line arguments are parameters that are supplied to the application program at
the time of invoking it for execution. We can write Java program that can receive and use
the arguments provided in the command line. This is accomplished by passing command
line arguments to main( ). Any arguments provided in the command line are passed to the
array as its elements. We can simply access the array elements and use them in the
program as we wish.
11 | Java Fundamentals

E.g. 1
/* This program uses command line argument as input */
class CmdArgs
{
public static void main( String args[])
{
String s;
int count,i;
count = args.length;
System.out.println(“Number of argument =”+count);
for (i=0;i<count;i++)
{
s = args[i];
System.out.println(“Java is “+s);
}
}
}
E.g. 2
// Java program with two classes
class Room
{
float length, breadth;
void getData(float a, float b)
{
length=a;
breadth = b;
}
}
class RoomArea
{
public static void main(String args[])
{
float area;
Room r1 = new Room();
r1.getData(12.6, 13.5);
area = r1.length * r1.breadth;
System.out.println(“Area=”+area);
}
}
12 | Java Fundamentals

Constants
Constants in Java refer to fixed values that do not change during the execution of a
program. Java supports the following types of constants.
Java Contants

Numeric Constants Boolean Constants Character Constants

Single
Integer Real String
Character
Constants Constants Constants
Constant

Integer Constants
An Integer constant refers to a sequence of digits. There are 3 types of integers.
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Decimal integer consists of a set of digits, 0 through 9, preceded by an optional minus
sign.
e.g. 123 -321 0 654321
Embedded spaces, commas and non-characters are not permitted between digits.
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading 0.
e.g., 037 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They
may also include alphabets A through F. A letter A through F represents the numbers 10
through 15.
e.g., 0x2 0x9f 0Xbcd

Real Constants
Floating point numbers represent decimal values with a fractional component. They can
be expressed in either standard or scientific notation. In standard or decimal notation the
numbers are having a whole number followed by a decimal point and followed by a
fractional part, which is an integer. It is possible that the number may not have digits
before the decimal point or digits after the decimal point.
e.g., 0.0683 .95 26.
The general form of the scientific notation is
Mantissa E exponent
The mantissa is either real number or integer number. The exponent is an integer with an
optional + or – sign. The letter E separating the mantissa and exponent may be written in
either lowercase or uppercase.
e.g., 0.65e4 10E-2
13 | Java Fundamentals

Character Constants
A single character constant contains a single character enclosed within a pair of single
quotation marks.
e.g., ‘5’ ‘;’ ‘X’

String Constant
A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
e.g., “Hello Java” “1997” “5+3” “x/y”

Boolean Constants
There are only two logical values that a Boolean value can have. They are true and false.
The values of true and false do not convert into any numeric representation. They can
only be assigned to variables declared as Boolean.
Backslash Character Constants
Java supports some special backslash character constants that are used in output methods.
Each one of they represent one character although they consists two characters. These
character combinations are known as escape sequences.

Constant Meaning
\b Backspace
\f Form Feed
\n Next line (or) New Line
\t Horizontal Tab
\r Carriage Return
\’ Quote
\’’ Double Quote
\\ Backslash

Variables
A variable is a identifier that denotes a storage location used to store a data value. A
variable may take different values at different times during the execution of the program.
e.g., average, height
A variable names may consist of alphabets, digits, the underscore ( _ ) and dollar ( $ )
characters, subject to the following conditions.
1. They must not begin with digit.
2. Uppercase and lowercases are distinct.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable name can be of any length.
14 | Java Fundamentals

Data types in java

Data Types
Primitive Non-primitive
Every variable is Java has a data type. Data type specify the size
(intrinsic) and type of values that
(derived)
can be stored. The various categories of data types are

Numeric Non-numerc Classes Arrays Interface

floating-
Integer Character Boolean
point

Primitive Data Types (Intrinsic or Built-in)


Integer Types
Integer types can hold whole numbers such as 123, 124. The size of the values that can be
stored depends on the integer data type we choose. Java supports four types of integers.
They are byte, short, int and long. Java does not support the concept of unsigned types
and therefore all java values are signed. The memory size and range of all the four integer
data types are
Type Size Minimum Value Maximum Value
byte One byte -128 127
short Two bytes -32,768 32,767
int Four bytes -2,147,483,648 2,147,483,647
long Eight bytes -9,223,372,036,854,775,808 -9,223,372,036,854,775,807
Floating Types
Floating point types can hold numbers containing fractional parts such as 27.9, -143.6.
There are two kinds of floating point storage in java. They are float and double. The float
type values are single precision and double type values are double precision. The size and
range of these data types are
Type Size Minimum Value Maximum Value
float 4 bytes 3.4e-38 3.4e+38
double 8 bytes 1.7e-308 1.7e+308
Floating point data types support a special value known as Not-A-Number (NAN). It is
resulted when an actual number is not produced from an operation.
Character Types
In order to store character constants in memory Java provide a character data type called
char. The character type assumes a size of two bytes, but basically it can hold only a
single character.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution of
the program. There are only two values that a Boolean type can take : true or false.
Boolean type is denoted by keyword boolean and uses only one bit of storage.
15 | Java Fundamentals

Declaration of Variable
A variable must be declared before it is used in the program. Declaration does three
things.
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
3. The place of declaration decides the scope of the variable
The general form of declaration of variable is
Datatype variable1, variable2,
variable3,........................variablen;

Variables are separated by commas and declaration statement must end with a semicolon.
Some valid declarations are
int a,b;
float x,y;
double p,q,r;

Giving values to Variables


A variable must be given a value after it has been declared but before it is used in an
expression. This can be achieved in two ways
1. By using an assignment statement
2. By using a read statement
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as
follows
Variable name = value;

E.g.,
initialvalue = 0;
finalvalue = 100;
yes = ‘x’;

We can also string assignment expression as shown below


x = y = z = 0;

it is also possible to assign a value to a variable at the time of its declaration. This takes
the form
datatype variablename = value;

e.g.,
int final value = 100;
char yes = ‘x’;

The process of giving initial values to a variable is known as the initialization. The one
that are not initialized are automatically set to zero.
The following are valid java statements
float x, y, z;
int m = 5, n = 10;
16 | Java Fundamentals

int m, n = 10;

read statement
We may also give values to variables interactively through the keyboard using the
readLine() method.
Import java.io.DataInputStream;
Class Reading
{
Public static void main(String args[])
{ Output
DataInputStream in = new DataInputStream(System.in);
Enter an Integer:
int intnumber = 0;
float floatnumber = 0.0f; 123
try
{ Enter a float number:
System.out.println(“Enter an Integer:”);123.45
intnumber = Integer.parseInt(in.readLine());
Integer Number = 123
System.out.println(“Enter a float number:”);
floatnumber = Float.parseFloat(in.readLine());
Float number = 123.45
}
catch(Exception e)
{
}
System.out.println(“Integer Number = ”+intnumber);
System.out.println(“float Number = ”+intnumber);
}
}

Scope of Variable
Java variable actually classified into three kinds :
1. Instance variable
2. Class variables and
3. Local variables
Instance variables and class variables are declared inside a class. Instance variables are
created when the objects are instantiated and therefore they are associated with the
objects. They take different values for each object. on the other hand, class variables are
global to a class and belong to the entire set of objects that class creates. Only one
memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They are called so
because they are not available for use outside the method definition. Local variables can
also be declared inside program blocks that are defined between an opening brace { and a
closing brace }. These variables are visible to the program only from the beginning of its
program block to the end of the program block. When the program control leaves a block,
all the variables in the block will cease to exist. The area of the program where the
variable is accessible is called its scope.
Symbolic constants
We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in a program. One example of such a constant is 3.142.,
representing a value of the mathematical constant . We face two problems with this
type of constants. They are
17 | Java Fundamentals

1. Problem in modification of the program


2. Problem in understanding the program
Assignment of symbolic name such constants frees us from these problems. Such a
constant can be declared as follows.
final type symbolic name = value;

e.g.,
final float PI = 3.1416f;
final MAX_MARKS = 50;

Symbolic names take the same form as variable but they are written in capitals. This is
only a convention, not a rule. After declaration of symbolic constants they should not be
assigned any other value within the program by using as assignment statement. They
cannot be declared inside a method. They should be used only as class data members in
the beginning of the class.
Automatic Conversions and Type Casting
Automatic Conversion
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met :
 The two types are compatible
 The destination type is larger than the source type
When these two conditions are met, a widening conversion takes place. For widening
conversion, 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.
Type Casting
To create a conversion between two incompatible types you must use a cast. This kind of
conversion is sometimes called a narrowing conversion. A cast is simply an explicit type
conversion. The syntax is :
type variable1 = (type ) variable2;

e.g.,

class TypeWrap
{
Public static void main(String args[]) Output
{ Variables Created
char c = ‘x’; byte b = 50; short s = 196; c=x
int i = 123456789; b=50
long l = 1234567654321L; float f1 = 3.142f; s=1996
float f2 = 1.2e-5F; double d = 0.000000987; i=123456789
System.out.println(“Variables Created”); l=1234567654321
System.out.println(“c=”+ c + “\nb=” + b + “\ns=”
f1=3.142 + s +
“\ni=” + i + “\nl=” + l + “\nf1=” +
f2=1.2e-005
f1 + “\nf2=” + f2 + “\nd=” + d2=9.87e-007
d);
System.out.println(“ ”); Types Converted
System.out.println(“Types Converted”); s1=50
short s1 = (short)b; s2=-13035
short s2 = (short)i; n1=1.23457e+012
float n1 = (float)l; m1=3
int m1 = (int)f1;
System.out.println(“s1=” + s1 + “\ns2=” + s2 +
“\nn1=” + n1 + “\nm1=” + m1);
18 | Java Fundamentals

}
}

Standard Default Values


In Java, every variable has a default value. If we don’t initialize a variable when it is first
created, Java provides default value to that variable type automatically as shown below
Type Of Variable Default Value
byte Zero
short Zero
int Zero
long Zero
float 0.0f
double 0.0d
char Null character
boolean false
reference null

Exercise

1. Write a program to determine the sum of the following


harmonic series for a given value of “n”
1 + ½ + 1/3 + 1/4 + ............................................+1/n
The value of n should be given interactively through the
keyboard

2. Write a program to read the price of an item in decimal


form (like 75.95) and print the output in paise (like 7595)

3. Write a program to convert the given temperature in


Fahrenheit to Celsius using the following conversion
formula and display the value in tabular form.
C = (F-32) / 1.8
19 | Java Fundamentals

UNIT – 2
OOPS Concepts in Java
Operators & Expressions
An operator is a symbol that ells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. They
usually form a part of mathematical or logical expressions. Java operators can be
classifieds into the following categories
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
Arithmetic operator are used to construct mathematical expression as in algebra. The Java
provides the following basic arithmetic operators.
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary Minus
* Multiplication
/ Division
% Modulo Division
(remainder)

These can operate on any built-in numeric data types of Java. We cannot use these
operators on boolean type.
e.g.,
a–b a+b a*b a/b a%b -a*b
Here a and b may be variables or constants and are known as operands.
Integer Arithmetic
When the both operands in a single arithmetic expression such as a + b are integers, the
expression is called an integer expression, and the operation called integer arithmetic
20 | Java Fundamentals

expression. Integer arithmetic always yields an integer value. In a / b when a and b are
integer types, gives the result of division of a/ b after truncating the division. This
operation called integer division. For modulo division the sign of the result is always the
sign of the first operand.
e.g.,
-10 % 3 = -1
10 % -3 = 1

Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation. Since floating
point values are rounded to the number of significant digits permissible, the final value is
an approximation of the correct result. Unlike ‘C’ modulus operator can be applied to the
floating point data as well. The floating point modulus operator returns the floating point
equivalent of an integer division. This means is that the division is carried out with both
floating point operands. But the resulting divisor is treated as an integer, resulting in a
floating point remainder.
e.g.,
6.2 % 10.4 = 4.2
20.5 % 6.4 = 1.3

Mixed-mode Arithmetic
When one of the is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then the other operand is
converted to real and the real arithmetic is performed. The result value will be real.
e.g.,
15 / 10.0 = 1.5

Relational operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. Comparisons can be done with the
help of relational operators. Java supports six relational operators. They are
Operator Meaning
== Is equals to
> Is greater than
< Is less than
>= Is greater than or equal to
<= Is less than or equal to
!= Is not equals to

A simple relational expression contains only one relational operator and is of the
following form :
ae-1 relational operator ae-2

ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them. When arithmetic expressions are used on either side of a relational
operator, the arithmetic expressions will be evaluated first and then the results compared.
21 | Java Fundamentals

That is, arithmetic operators have a higher priority over relational operators. A value of a
relational expression is either true or false.
e.g.,
4.5 <= 10 4.5 < -10 a+b == c+d 10 != a

Logical operators
Java allows the following three logical operators.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators are used to from compound conditions by combining two or more
relations.
e.g.,
a > b && x ==10
An expression of this kind which combines two or more relational expressions is termed
as a logical expression or a compound relational expression. A logical expression yields a
value of true or false, according to the truth table given below
Value of the expression
op-1 op-2 op-1 && op-2 op-1 || op-2
true true true true
true false false true
false true false true
false false false false

Assignment Operators
Assignment operators are used to assign the value of an expression to a variable.
e.g.,
a=a+4
In addition, Java has a set of shorthand assignment operators which are used in the form
v op= exp;

Where v is a variable, exp is an expression and op is a java binary operator. The operator
op= is known as the shorthand assignment operator.
The assign statement
V op= exp is equivalent to v = v op (exp)
Some of the commonly used assignment operators are
Statement with simple Statement with shorthand
assignment operator operator
a=a+1 a += 1
a = a -1 a -=1
a = a * (n+1) a *= n+1
a = a / (n+1) a /= n+1
22 | Java Fundamentals

a=a%b a %= b

Increment and Decrement Operators


The ++ and – are Java’s increment and decrement operators. The operator ++ adds 1 to
the operand while – subtracts 1. Both are unary operators and are used in the following
form
++ m or m ++ which is equivalent to m = m + 1 or m += 1
-- m or m -- which is equivalent to m = m - 1 or m -= 1
While ++m and m++ mean the same thing when they form statements independently,
they behave differently when they are used in expressions on the right-hand side of an
assignment statements. Consider the following
m = 5;
y = ++m;
in this case, the value of y and m would be 6. Suppose, if we rewrite the above statement
as
m =5;
y = m++;
then the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left. On the other hand, a
postfix operator first assigns the value to the variable on left and then increments the
operand.
Conditional Operator
The character pair ? : is a ternary operator available in Java. This operator used to
construct conditional expression of the form
exp1 ? exp2 : exp3;

exp1 can be any expression that evaluates to a boolean value. If exp1 is true, then exp2 is
evaluated; otherwise exp3 is evaluated. Both exp2 and exp3 are required to be return the
same type, which can’t be void.
e.g.,
a = 10;
b = 15;
x = (a>b) ? a : b;
in this example x will be assigned the value of b.
Bitwise Operators
Java defines several bitwise operators for manipulation of data at values of bit level.
These operators used for testing the bits, or shifting to the right or left. Bitwise operators
may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One’s complement
>> Shift Right
<< Shift Left
23 | Java Fundamentals

>>> Shift Right with zero fill


&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise XOR assignment
>>= Shift right assignment
<<= Shift left assignment
>>>= Shift right zero fill assignment

Special Operators
Java supports some special operators such as instanceof operator and member selection
operator ( . ).
Instanceof operator
It is an object reference operator and returns true if the object on the left-hand side is an
instance of the class given on the right-hand side. This operator allows to determine
whether the object belongs to a particular class or not.
e.g.,
person instanceof Student
is true if the person belongs to the Student class; otherwise it is falde.
Dot Operaotr
The dot operator is used to access the instance variables and methods of class objects.
e.g.,
person1.age
person1.salary()
it is also used to access classes and sub-packages from a package.
Operator Precedence and Associativity
Each operator in Java has a precedence associated with it. There are distinct levels of
precedence and an operator may belong to one of these levels. The operators of highest
level of precedence are evaluated first. The operators of the same precedence are
evaluated from left to right or from right to left, depending on the level. This is known as
the associativity property of an operator.
Operator Description Associativity Rank
. Member Selection
() Function call Left to Right 1
[] Array element reference
- Unary minus
++ Increment
-- Decrement
Right to Left 2
! Logical negation
~ Ones complement
( type ) Casting
* Multiplication
/ Division Left to Right 3
% Modulus
+ Addition
Left to Right 4
- Subtraction
<< Left Shift Left to Right 5
>> Right Shift
24 | Java Fundamentals

Operator Description Associativity Rank


>>> Right Shift With Zero Fill
< Less Than
<= Less than or Equal to
> Greater Than Left to Right 6
>= Greater than or equal to
Instanceof Type comparison
== Equality
Left to Right 7
!= Inequality

Operator Description Associativity Rank


& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional Operator Right to Left 13
= Assignment Operator Right to Left 14
Op= Shorthand Assignment Right to Left 15
Mathematical Functions
Java supports these basic math functions through Math class defined in the java.lang
package. These functions should be used as follows
Math.function_name();

e.g.,
Double y = Math.sqrt(x);
Functions Action
double sin(double x) Returns the Sine of the angle x in radians
double cos(double x) Returns the Cosine of the angle x in radians
double tan(double x) Returns the Tangent of the angle x in radians
double asin(double y) Returns the angle whose Sine is y
double acos(double y) Returns the angle whose Cosine is y
double atan(double y) Returns the angle whose Tangent is y
double atan2(double x, double y) Returns the Tangent whose angle is x/y
double pow(double x, double y) Returns x raised to y (xy)
double exp(double x) Returns e raised to x (ex)
double log(double x) Returns natural logarithm of x
double sqrt(double x) Returns the square root of x
double ceil(double x) Returns the smallest whole number greater than or
equal to x
double floor(double x) Returns the largest whole number less than or equal to
x
double rint(double x) Returns the truncated value of x
double round(double x) Returns the integer closest to the x
abs(x) Returns the absolute value of x
max(x,y) Returns the maximum of x and y
min(a,b) Returns the minimum of x and y
25 | Java Fundamentals

double random( ) Returns a value with a positive sign, greater than or


equal to 0.0 and less than 1.0.

Exercise
Write a program to find depreciation when salvage, number of
years and cost price given
Write a program that will read a real number and print the
following output in one line
Smallest integer The given number
Largest integer
Not less than the number Not greater
than the number
Decision Making and Branching
A Java program is a set of statements, which are normally executed sequentially in the
order in which they appear. However, in practice, we may have to change the order of
execution of statements based on certain conditions. This involves a kind of decision
making to see whether a particular condition has occurred or not and then direct the
computer to execute certain statements accordingly.
When a program breaks the sequential flow and jumps to another part of the code it is
called branching. When the branching is based on the particular condition it is known as
conditional branching. If branching takes place without any decision it is known as
unconditional branching. Java language possesses such decision making capabilities and
supports the following statements known as control or decision making statements.
if Statement
The if statement is Java’s conditional branching statement. It is basically a two way
decision statement. The if statement may be implemented in different forms.
1. Simple if
2. if....else
3. nested if....else
4. else if ladder
Simple if
The general form of a simple if statement is
if(Test Expression)
{
Statement-block; Test Expression
} True
?
Statement-x;

The statement block may be a single statement


or a group of statements. The test expression is False
any expression that returns Boolean values. If Statement-block
the test expression is true the statement block
will be executed otherwise the statement block
will be skipped and the execution will jump to Statement-x
the statement-x.
E.g.,
--------------
--------------
If(category==sports)
{
26 | Java Fundamentals

Marks = marks+bonus_marks;
}
System.out.println(“Marks=”+marks);
--------------
--------------

If value in category is equals to sports then the marks is added to bonus_marks before it
is printed otherwise bonus_marks are not added.

if-else statement Test


Expression
The general form of if-else statement is ?
if(test expression)
{
False
True block; True
}
else
{
false block; True-Block False-Block
statements statements
}
Statement-x;

If the test expression is true, Statement - x


then the true block statements
immediately following the if
statement, are executed; otherwise, the false-block statements are executed. In either case,
either true-block or false-block will be executed, not both. In both the cases the control is
transferred subsequently to the statement-x.
E.g.,
................
If(code==1)
boy=boy+1;
else
girl=girl+1;
xxx;
.................
.................

Here if the code is equal to 1 the statement boy=boy+1 is executed and control is
transferred to the xxx after skipping the else part. If the code is not equals to 1 then the
statement girl = girl+1 is executed before the control reaches the statement xxx.
Nested if-else statement
A nested if is an if statement that is the target of another if or else.
if(test condition1)
{
if(test condition2)
{
Statement-1;
}
else
{
Statement-2;
}
27 | Java Fundamentals

}
else
{
Statement-3;
}
Statement-x;

If condition1 is false the statement-3 will be executed otherwise it continues to perform


the second test. If the condition2 true the statement-1 is executed and then control is
transferred to statement-x; otherwise the statement-2 will be executed and control is
transferred to the statement-x. In a nested if, else statement always refers to the nearest if
statement and that is not already associated with else.

if(i==10)
{
if(j<20) a=b;
if(k>100) c=d;
else a=c;
}
else a=d;
Here the final else is not associated with if(j<20) because it is not in the same block (even
though it is the nearest if without an else) rather the final else is associated with if(i==10),
because it is the closest if within the same block.
The Else If Ladder
The else-if ladder is used when multipath decision is involved. A multipath decision is a
chain of ifs in which the statement associated with each else is an if. It takes the
following general form.
if(condition 1)
Statement-1;
Condition1
trueif(condition 2)
else false
Statement-2;
else if(condition 3)
Statement 1 Condition2
Statement-3;true false
............................
else if(condition n) Condition3
Statement 2
true false
Statement-n;
else default-statement;

statement-x;
Statement 3 Condition4
true false

Statement n Default Statement

Statement x
28 | Java Fundamentals

This construct is known as else-if ladder. The conditions are evaluated from the top to
downwards. As soon as the true condition is found, the statement associated with it
executed and the control is transferred to the statement-x. When all the n conditions
becomes false then the final else containing the default-statement will be executed.
e.g.,
if(code==1)
color=”pink”;
else if(code==2)
color=”black”;
else if(code==3)
color=”green”;
else color=”blue”;
System.out.println(“color = ” + color);

Exercise
1. Write a program to read marks of 5 subjects of a student
and find his average and grade. The grade is done
according to the following rules.
Average Marks Grade
80-100 Honours
60-79 First Division
50-59 Second Division
40-49 Third Division
0-39 Fail
2. Write a program to find the number of and sum of all
integers greater than 100 and less than 200 that are
divisible by 7.

The switch statement


The switch statement test the value of a given variable or expression against a list of case
values and when match is found, a block of statements associated with that case is
executed. The general form of the switch statement is as shown below
switch(expression)
{
case value-1 :
switch expression
Block-1;
break;
case value-2 :
Block-1;
break;
..............................
Expression =
Value 1
Block-1
Expression =
Value 2
Block-2
29 | Java Fundamentals

..............................
default :
default Block;
break;
}
Statement – x;

The expression is an integer


expression or character. Value-1,
value-2 , ............. are constants or
constant expressions (evaluable to an integer constant) and are
known as case labels. Each of these values should be unique with in
a switch statement. Block-1, Block-2 ...... are statements lists and
may contain zero or more statements. There is no need to put braces
around these. The case labels ends with a colon (:).
When the switch is executed, the value of the expression is successively compared
against the values value-1, value-2,..... Of a case is found whose value matches with the
value of the expression, then the block of statement that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement, transferring the control to the statement-x
following the switch. The default is an optional case, when present it will be executed if
the value of the expression does not match with any of the case values. If not present, no
action takes place when all matches fail and the control goes to the statement-x.
e.g.,
class CityGuide Output
{
public static void main(String args[]) Select Your Choice
{ M  Madras
Char choice= ‘ ’;
B  Bombay
System.out.println(“Select Your Choice”);
System.out.println(“ M  Madras ”);
C  Calcutta
System.out.println(“ B  Bombay ”);
System.out.println(“ C  Calcutta ”); Enter Your Choice  B
System.out.println(“Enter Your Choice ”);
try Bombay : Booklet 9
{
Switch(choice = (char)System.in.read())
case ‘M’ :
case ‘m’ : System.out.println(“Madras : Booklet 5” );
break;
case ‘B’ :
case ‘b’ : System.out.println(“Bombay : Booklet 9” );
break;
case ‘C’ :
case ‘c’ : System.out.println(“Calcutta : Booklet 15” );
break;
default : System.out.println(“Invalid Choice” );
}
catch(Exception e){ }
}
}
Exercise
1. A set of two linear equations with two unknowns X 1 and X2
is given below
AX1 + BX2 = m
CX1 + DX2 = n
30 | Java Fundamentals

The set has two unique solutions


mD−Bn nA−Cm
X1 = AD−CB X2 = AD−CB
Provide the denominator AD - CB ≠ 0.
Write a program that will read values of A, B, C, D, m and n
and compute values X1 & X2
2. A cloth showroom has announced the following seasonal
discounts on purchase of items
Discount
Purchase Amount
Mill Cloth Handloom Items
0-100 - 5.0%
101-200 5.0% 7.5%
201-300 7.5% 10.0%
Above 300 10.0% 15.0%

Write a program using switch and if statements to compute


the net amount to be paid by the customer
Decision Making And Looping
Looping
The process of repeatedly executing a block of statements is known as looping. The
statements in the block may be executed any number of times from zero to infinity
number. If loops continuous forever it is called infinity loop. In looping a sequence of
statements are executed until some conditions for the termination of the loop are satisfied.
A program loop consists of two segments, body of the loop and control statement. The
control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop. Depending upon the position of the control
statement in the loop a control structure may be classified either as entry-controlled loop
or exit-controlled loop.

Test
Expression
False
Body of the loop

True Test
Expression
True
Body of the loop

False

Entry control loop Exit control loop

In the entry-controlled loop, the control conditions are tested before the start of the loop
execution. Of the conditions are not satisfied, then the body of the loop will not be
executed. In the case of exit-controlled loop, the test is performed at the end of the body
of the loop and therefore the body is executed unconditionally for the first time. A
looping process in general would include the following four steps.
1. Setting and initialization of a counter
2. Execution of statements
3. Test for a specified condition
31 | Java Fundamentals

4. Increment/decrement counter
The java language provides 3 constructs for performing loop operations.
1. while construct
2. do construct
3. for construct
while statement
The basic form of the while statement is
Initialization
while (test condition)
{
Body of the loop
}

The while is an entry controlled loop. The test condition is evaluated and if the condition
is true then the body of the loop is execute. After execution of the body, the test condition
is once again evaluated and if it is true, the body is executed once again. This process
continues until the test condition becomes false and the control is transferred out of the
loop. On exit, the program continues with the statement immediately after the body of the
loop. The body of the loop may have one or more statements. The braces are needed only
if the body contains two or more statements.
e.g.,
sum=0;
n=1;
while(n<=10)
{
sum=sum+n*n;
n++;
}
System.out.println(“sum = ”+sum);

Here the body of the loop is executed 10 times. i.e., for n=1,2,...,10 each time adding the
square of the value of n, which is incremented inside the loop.
Exercise
1. Given a number write a program using while to reverse
the digit of the number
2. Shown below is Floyd’s triangle
a. 1
2 3
4 5 6
7 8 9 10
.................
..................
Write a program to produce the Floyd’s triangle for
given number of rows
b. Modify the program to produce the following form of
Floyd’s triangle
1
0 1
1 0 1
0 1 0 1
..............
...............
The do statement
32 | Java Fundamentals

The basic form of the do statement is


Initialization
do
{
Block of statements
}
while(test condition);
On reaching the do statement the program proceeds to evaluate the body of the loop first.
At the end of the loop the test condition in the while statement is evaluated. Of the
condition is true the program continues to evaluate the body of the loop once again. This
process continues as long as the condition is true. When the condition becomes false the
loop will be terminated and control goes to the statement that appears immediately after
the while statement. Since the test condition is evaluated at the bottom of the loop the
do....while construct provides an exit controlled loop and therefore the body of the loop is
always executed at least once.

e.g.,
class DoWhileTest
{
public static void main(String x[ ] ) Output
{ Multiplication Table
int row=1, column=0, y=0;
1 2 3
System.out.println(“Multiplication Table”);
do 2 4 6
{
column=1; 3 6 9
do
{
y=row*column;
System.out.println(“ ”+y);
column++;
}
while(column<=3);
System.out.print(“\n”);
row++;
}
while(row<=3);
}
}

Exercise

1. Write a program to compute the sum of the digits of a


given integer number

2. The numbers in the sequence

1 1 2 3 5 8 13 21

are called Fibonacci numbers. Write a program using


do..while loop to calculate and print the first ‘n’ Fibonacci
numbers.

The for statement


The for loop is another form of entry controlled loop. The general form of a for loop is
for(initialization; test condition; increment/decrement)
33 | Java Fundamentals

{
Body of the loop
}

The execution of the for statement is as follows.


1. Initialization of control variable is done first using assignment statements such as
1=1 and count=0. The variable i and count are called loop control variables.
2. The value of the control variable is tested using the test condition. The test
condition is a relational expression such as i<10, which determines when the loop
will exit. If the condition is true the body of the loop is executed otherwise the loop
is terminated and execution continues with the statement immediately following the
loop.
3. When the body of the loop is executed the control is transferred back to the for
statement after evaluating the last statement in the body. Now the control variable
is incremented/decremented using as assign statement such as i++ or i—and new
value of the control variable is again tested to whether it satisfies the loop
condition. If it is satisfied the body of the loop again executed. This process
continues till the value of control variable fails to satisfy the condition.

e.g.,
for( x=0; x<=9; x++)
{
System.out.println(x);
}
The for loops executed 10 times and prints the digits 0 to 9. The Three sections enclosed
with in parenthesis must be separated by semicolons. The brasses are optional when the
loop contains only one statement. Since the condition tested at beginning the body may
not be executed at all.
Additional Features of For Loop:
In initialization part more than one variable can be initialized at a time. If the
initialization has more than one then they are separated by commas.
e.g.,
for( i=0,n=0; n<17; ++n)
{
body of the loop
}
Like initialization section, the increment or decrement section may also have more than
one part.
e.g.,
for(n=1,m=50; n<=m; n++,m++)
{
…………………………
…………………………
}
The test condition may have any compound relation and the testing need not be limited
only to the loop control variable.
e.g.,
for(i=1; i < 20 && sum < 100; ++i)
{…………….
…………….
}
Another unique aspect of for loop is that one or more sections can be omitted, if
necessary.
34 | Java Fundamentals

e.g.,
m=100;
for(;m!=100;)
{ System.out.println(m);
m++;
}
both the initialization and increment/decrement sections are omitted. However the
semicolons separating the sections must remain. If the test conditions is also omitted then
the for statement sets an infinity loop.
Nesting of for loops :
Nesting of loops, that is, one for statement with in another for statement is allowed in
java. The for loop can be nested as follows.
Ex:
for(i=1;i<=10;i++)
{
………………….
………………….
for(j=1;j<=10;j++)
{
……………….
……………….
}
}

The Enhanced for loop:


The enhanced for loop, also called for each loop. This features helps to retrieve the array
elements efficiently rather than using array indexes. We can also use this to eliminate
iterators in a for loop and to retrieve the elements from a collections. The enhanced for
loop takes the following form.
for(Type Identifier : Expression)
{
//statements
}

e.g.,
int num[3]={56,48,79};
for(int k:num)
{
if(k>50&&k<100)
System.out.println(k);
}

Jumps in loops:
Some times when executing a loop it becomes desirable to skip a part of the loop or to
leave the loop as soon as a certain condition occurs. Java permits a jump from one
statement to the end or beginning of a loop as well as a jump out of a loop.
Jumping out of a loop:
An early exit from a loop can be accomplished by using the break statement. This
statement can be used within while, do, or for loops. When a break statement is
encountered inside a loop the loop is immediately exited and the program continuous
with the statement immediately following the loop. When the loops are nested the break
would only exit from the loop containing it. That is, the break will exit only a single loop.
e.g., e.g.,
35 | Java Fundamentals

while(……..) for(…..)
{ {
……………… for(…..)
……………… {
if(condition) break; …………
……………… if(condition) break;
……………… } Exit
} from inner loop
………….
………….
}

Skipping a part of a loop:


During the loop operations it may be necessary to skip a part of the body of the loop
under certain conditions. Like break statement java supports another statement called the
continue statement. The continue as the name implies causes the loop to be continued
with the next iteration after skipping any statements in between. The format of the
continue statement is simply
continue;

In while and do loops continue causes the control to go directly to the test condition and
then to continue the iteration process. In the case of for loop the increment section of the
loop is executed before the test condition is evaluated.

e.g., e.g.,
while(condition) for(…..)
{ {
……………… for(….)
……………… {
if(condition) break; …………
……………… if(condition) break;
……………… }
} ………….
…………
}

Labelled loops:
In java we can give a label to a block of statements. A label is any valid java identifier.
To give a label to a loop, place it before the loop with a colon at the end.
e.g.,
loop1:for(….)
{
………..
………..
}
A block of statements can be labelled as shown in below.
block1: {
…….
.……
block2: {
…….
.……
}
36 | Java Fundamentals

…….
.……
}
If we want to jump out side a nested loops or to continue a loop that is outside the current
one, then we may have to use the labelled break and labelled continue statements.
e.g.,
outer: for(int m=1;m<11;m++)
{
for(int n=1;n<11;n++)
{
System.out.println(“ ”+ m*n );
if(n==m)continue outer;
}
}
Here, the continue statement terminates the inner loop when n=m and continuous the next
iteration of outer loop.
e.g.,
loop1:for(int i=1; i<10; i++)
{
loop2:while(x<100)
{
y = i * x;
if (y>500) break loop1;
}
…………
…………
}
…………
…………
Here break causes the execution to break out of the both the loops.
Ex:
class ContinueBreak Output
{ *
public static void main ( String args[*] *)
{
* * *
loop1 : for(int i=1;i<100;i++)
{ * * * *
System.out.println(“ ”); * * * * *
if (i>=10) break; * * * * * *
for(int j=1; j<100; j++) * * * * * * *
{ * * * * * * * *
System.out.println(“ * ”); * * * * * * * * *
if(j==i) continue loop1;
Termination by break
}
}
System.out.println(“Termination by break “);
}
}
EXCERCISE
Write a program to print the following outputs using for loop.
1 $ $ $ $ $ 1
2 2 $ $ $ $ 2 2
3 3 3 $ $ $ 3 3 3
4 4 4 4 $ $ 4 4 4 4
5 5 5 5 5 $ 5 5 5 5 5

Classes, Objects & Methods:


37 | Java Fundamentals

Classes provide a convenient method for packing together a group of logically related
data items and functions that work on them. In java, the data items are called fields and
the functions are called methods. Classes create objects and objects use methods to
communicate between them. A class is essentially a description of how to make an object
that contains fields and methods.
Defining a class
A class is user defined data type with a template that serves to define its properties. Once
the class type has been defined we can create “variables” of that type. These variables are
termed as instance of classes, which are the actual objects. The basic form of class
definition is
class classname [extends superclassname]

[ fields declaration; ]

[ method declaration; ]

Everything inside the square brackets is optional. Classname and superclassname are any
valid java identifiers. Fields & methods are declared inside the body.
Fields declaration:
Data is encapsulated in a class by placing data fields inside the body of the class
definition. These variables are called instance variables because they are created
whenever an object of the class is instantiated. We can declare the instance variable
exactly the same way as we declare local variables.
Type identifier1, identifier2;

e.g.,
class Rectangle
{
int length, breath;
}

The class Rectangle contains two integer type instance variables. Instance variables are
also known as member variables.
Method declaration
Methods are declared inside the body of the class but immediately after the declaration of
instance variable. The general form of method declaration is
type methodname (parameter List)

Method body;

The type specifies the type of the value that method could return. This could be a simple
data type such as int, as well as any class type. It could even be void type. The
methodname is any valid identifier. The parameter list is always enclosed in parenthesis..
The list contains variable names and types. The variables in the list are separated by
commas. In the case where no parameters are required, the declaration must retain the
empty parenthesis. The body actually describes the operations should be performed on
the data. The body contains one or more valid Java statements.
38 | Java Fundamentals

e.g.,
class Rectangle
{
int length, breadth;
void getdata (int x, int y)
{
length=x;
breadth=y;
}
}

Here the method getdata has a return type as void because it does not return any value.
We pass two integer values to the method, which are then assigned to instance variables
length and breadth. The class can have many methods and variables. Instance variables
and methods in a class are accessible by all the methods in that class. But a method
cannot access the variables that are declared in other methods.
Creating objects:
An object is a block of memory that contains space to store all instance variables.
Creating an object is also referred to as instantiating object. Objects in java are created
using the new operator. The new operator creates an object of a specified class and
returns a reference to that object.
Rectangle r1;
r1=new Rectangle();

The first statement declares a variable to hold the objects reference and the second one
actually creates the object. Both statements can be combined into one as shown below.
Rectangle r1=new Rectangle();

The method Rectangle() is a default constructor of the class. We can create any number
of objects of Rectangle and each objects has its own copy of its instance variables of its
class. Any changes to the variables of one object have no effect on the variables of
another. It is also possible to create two are more references to the same object.
Rectangle r1=new Rectangle();
Rectangle r2=r1;

Accessing class members

The class members that is instance variables and methods of a class can be accessed
outside the class by using the concerned object and dot operator as shown below.
objectname.variablename=value;

objectname.method(argumentlist);

The objectname is the name of the object, variablename is the name of the instance
variable inside the object that we wish to access, methodname is the method that we wish
to call and argumetlist a comma separated list of actual values that must match in type
and number with the argument list of the methodname declared in the class.
rect1.length=15;
rect.getData(10,20);

e.g.,
class Rectangle
{
int length, breadth;
39 | Java Fundamentals

void getDta( int x, int y )


{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
class RectArea
{
public static void main(String args[])
{
int a1,a2;
Rectangle r1=new Rectangle(),r2=new Rectangle();
r1.length=10;
r1.breadth=20;
r2.getData(30,40);
a1=r1.area();
a2=r2.area();
System.out.println(“Area1=+”+a1+”Area2=”+a2);
}
}

Constructors
Constructor is a special type of method that enables an object to initialize itself when it is
first created. Constructors have the same name as the class itself. Once defined the
constructor is automatically called immediately after the object is created. They do not
specify a return type not even void. This is because the implicit return type of a class
constructor is a class type itself.

e.g.,
class Rectangle
{
int length,breadth;
Rectangle(int x,int y)
{
length =x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
class RectArea
{
public static void main(String args[])
{
40 | Java Fundamentals

Rectangle r1=new Rectangle(10,20),r2=new


Rectangle(30,40);
System.out.println(“Area=+r1.area()+”\
nArea2=”+r2.area());
}
}

this keyword:
Sometimes a method will need to refer the object that involved it. To allow this java
defines ‘this’ keyword. ‘this’ can be used inside any method to refer the current object.
That is ‘this’ always refers to the object on which the method was invoked.
Rectangle(int x,int y)
{
this.length=x;
this.breadth=y;
}

Instance variable hiding:


It is illegal in java to declare two local variables with the same name inside the same or
enclosing scopes but we can have local variables, including formal parameters to
methods, which overlap with the names of the class instance variables. However, when a
local variable has the same name as instance variable, the local variable hides the
instance variable. In such cases as ‘this’ lets you refer directly to the object, we can use it
to resolve any namespace collisions that might occur between instance variables and local
variables.
class Rectangle
{
int length,breadth;
Rectangle(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
}
Method Overloading
In java it is possible to define two or more methods within the same class that share the
same name as long as their parameter declarations are different. This is called method
overloading. Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method, in an object java
matches up the method name first and then number and type of the parameters to decide
which one of the definitions to execute. This process is also known as polymorphism. To
create an overloaded method, it is to provide several different methods definitions in the
class, all with the same names, but with different parameters list. The difference may
either be in the number or type of arguments. That is each parameter list should be
unique.

e.g, Room(float x)
class Room {
{ length=breadth=x;
float length,breadth; }
Room(float x, float y) int area ()
{ {
length=x; return(length*breadth);
breadth=y; }
} }
41 | Java Fundamentals

System.out.println(“Area1=”+r1.
class RoomArea
area());
{
public static void
main(String x[])
System.out.println(“Area2=”+r2.
{
area());
Room r1=new
}
Room(15.6f, 13.5f);
}
Room r2=new
Room(12.5f);

Using objects as parameters:


We can also pass objects as arguments to the methods. Consider the below example.
class Test
{
int a; float b;
Test(int I,float y)
{
a=i;
b=j;
}
boolean equles(Test o)
{
if(o.a==a && o.b==b) return true;
else return false;
}
}
class PassOn
{
public static void main(String x[])
{
Test t1=new test(20,13.6f), t2=new test(13,21.5f), t3=new
test(20,13.6f);
System.out.println(“t1=t2” + t1.equals(t2));
System.out.println(“t1=t3” + t2.equals(t3));
}
}

Returning objects:
A method can return any type of data including class type that we create.
e.g,
class Test
{
int a;
Test(int i)
{
a=i;
}
Test incr()
{
Test temp=new Test(a+10);
return temp;
}
42 | Java Fundamentals

}
class Return
{
public static void main(String x[])
{
Test t1=new Test(2).t2;
t2=t1.incr();
System.out.println(“t1.a=”+t1.a”t2.a=”+t2.a);
t2=t2.incr();
System.out.println(“After second increment t2.a=”+t2.a);
}
}

Recursion:
Recursion is the process that allows a method to call itself. A method that calls itself is
said to be recursive.
e.g.,
class Factorial
{
int fact(int n)
{
If(n==1) return n;
else return( n * fact(n-1) );
}
}
class Recursion
{
public static void main(String x[])
{
Factorial f=new Factorial();
System.out.println(“factorial of 3=”+f.fact(3));
System.out.println(“factorial of 4=”+f.fact(4));
}
}
A recursive function call does not make a new copy of the method, only arguments are
new. As each recursive call return, old local variables and parameters are removed.
Static members:
The members that are associated with the class itself rather than individual objects are
known as static members. To create such a member, precede its declaration with keyword
static.
e.g.,
static int count;
static int max(int a,int b)
The static variables and static methods are often referred to as class variables and class
methods. The class variables is a member that is common to all objects and accessed
without using a particular object and it can be accessed before any objects of its class are
created. Instance variable declared as static are global variables. When objects of its class
are created, no copy of static variables is made instead all instance of the class share the
same static variable. Method declared as static have several restrictions.
1. They can only call other static methods.
2. They can access only static data
3. They cannot refer to ‘this’ or ‘super’ in any way.
e.g.,
class MathOperation
{
static float mul(float x,float y)
43 | Java Fundamentals

{
return x*y;
}
static float div(float x,float y)
{
return x/y;
}
}
class MathApplication
{
public static void main(String x[])
{
float a=MathOperation.mul(2.3f,3.6f);
float b=MathOperation.div(2.3f,3.6f);
System.out.println(“a=”+a+”b=”+b);
}
}
Nesting of methods:
The method of a class can be called only by the object of the class. However there is an
exception to this. A method can be called of using only its name by another method of the
same class. This is known as nesting of methods.
e.g.,
class Nesting
{
int m,n;
Nesting(int x,int y)
{ m=x; n=y;}
int longest()
{
if(m>n) return m;
else return n;
}
void display()
{
int longest=longest();
System.out.println(“longest value=”+longest);
}
}
class NestingTest
{
public static void main(String x[])
{
Nesting nest.new Nesting(20,30);
nest.display();
}
}
Inheritance or extending a class:
Another aspect of OOP paradigm is reusability. Java supports this concept. Java classes
can be reused in several ways. This is basically done by creating new classes, reusing the
properties of exiting once. The mechanism of deriving of new class from an old one is
called inheritance. The old class is known as the base class or super class or parent class
and the new one is called the derived classes or sub class or child class. The inheritance
allows sub classes to inherit all the variables and methods of their parent classes.
1. Single inheritance (only one super class)
2. Multiple inheritance (several super classes)
3. Hierarchical inheritance (one super class, many sub classes)
44 | Java Fundamentals

4. Multi-level inheritance (derived from a derived class)


These forms of inheritances are shown below.
Single inheritance Multiple inheritances

A A B

B
C

Hierarchical inheritance Multi-level inheritance

A
A
B

B C D
C

Defining a sub class:


A sub class definition is as follows
class sub_class_name extends super_class_name
{
Variable declaration;
Method declaration;
}
The keyword extends specifies that the properties of the super class in name are extended
to the sub class name. The sub class will now contain its own variables and methods as
well those of the super class. By using sub classes we can add some more properties to an
existing class without actually modifying it.
Visibility control or Access control:
It may be necessary in some situations to restrict the access to certain variables and
methods from outside the class. We can achieve this by applying visibility modifiers to
the instance variables and methods. These visibility modifiers are also known as access
modifiers. Java provides three types of visibility modifiers they are public, private and
protected.

Public Access:
Any variable or method is visible to the entire class in which it is defined. We can make
it visible to the all classes by declaring a variable or method as public.
e.g.,
public int number
public void sum()
{
-----------
-----------
}

Friendly Access
45 | Java Fundamentals

When no access modifier is specified the member is default to friendly level of access.
The difference between the public access and friendly access is that the public modifier
makes fields visible in all classes regardless of their packages while the friendly access
makes fields visible only in the same packages but not in other packages.
protected access
The visibility of a protected field lies in between the public access and friendly access.
The protected modifier makes the fields visible not only to classes and sub classes in the
same package but also to sub classes in other packages. Non-sub classes in other
packages cannot access the protected members.
private Access
private fields are accessible only with their own class. They cannot be inherited by sub
classes and therefore not accessible in sub class. A method declared as private behaves
like a method declared as final. It prevents the method being sub classed.
private protected Access
A field can be declared with two keywords private and protected together like.
private protected int number;

This gives a visibility level in between the protected access and private access. This
modifier makes the fields visible in all sub classes regardless of what packages they are
in. These fields are not accessible by other classes in the same packages.

Access
modifier private
public protected friendly private
Access protected
Location

Same class Yes Yes Yes Yes Yes

Sub class in
Yes Yes Yes Yes No
same packages
Other class in
Yes Yes Yes No No
same package
Sub classes in Yes
Yes Yes No No
other package
Non sub class in
Yes No No No No
other package

Single inheritance:
When only one base class is used for derivation of a class and derived class is not used
as base class. Such type of inheritance between one base and derived class is know as
single inheritance.

e.g. 1, return( length * breadth );


class Room }
{ }
int length, breadth;
int area() class BedRoom extends Room
{ {
46 | Java Fundamentals

int height; class InherTest


BedRoom(int x, int y, {
int z) public static void main(String x[])
{ {
length=x; BedRoom b1=new
breadth=y; BedRoom(12,13,14);
height=z; int ar=b1.area();
} int vol=b1.volume();
int volume() System.out.println(“Area=”+
{ ar +
“\nVolume=” +
return(length*breadth*he vol);
ight); }
} }
}

e.g. 2, class BoxWeight extends Box


class Box {
{ double weight;
double width, height, Box(double w,double h,double
depth; d,double wi)
Box(){ } {
Box(double w,double width=w;
h,double d) height=h;
{ depth=d;
width=w; weight=wi;
height=h; }
depth=d; }
} class DemoBoxWeight
Box(double len) {
{ public static void main(String
x[])
width=height=depth=le {
n; BoxWeight b1=new
} BoxWeight(10,20,15,34.6);
double volume() BoxWeight b2=new
{ BoxWeight(2,3,4,0.076);
System.out.println(“volume of
return(width*height*dep box1=” +
th); b1.volome()
} +“volume of
} box2 =”
+b2.volume() );
}
}

Sub class constructor(super keyword):


A sub class constructor is used to construct the instance variables of both the sub class
and super class. The sub class constructor uses the keyword super to invoke the
47 | Java Fundamentals

constructor method of the super class. The keyword super is used subject to the following
conditions
1. Super may only used within a sub class constructor method.
2. To call the super class the constructor must appear as the first statement with in the
sub class constructor.
3. the parameters in the super class must match the order and type of the instance
variable declare in the super class.
E.g. 1
class Room class BedRoom extends
{ Room
int length,breadth; {
Room(int x,int y) int height;
{ BedRoom(int x,int y,int z)
length=x; {
breadth=y; super(x,y);
} height=z;
int area() }
{ int volume()
return(length*breadth); {
}
}
return(length*breadth*heigh
t);
}
}
class InherTest
{
public static void main(String x[])
{
BedRoom b1=new BedRoom(14,12,10);
System.out.println(“area=”+b1.area+”\
nvolume=”+b1.volume);
}
}

e.g. 2, }
class Box double volume()
{ {
private double width, height,
depth; return(width*depth*height);
Box(Box ob) }
{ }
width=ob.wigth;
height=ob.height; class BoxWeight extends Box
depth=ob.depth; {
} double weight;
Box(double w, double h, BoxWeight(double w, double
double d) h,
{ double d, double m)
width=w; height=h; {
depth=d; super(w,h,d);
} weight=m;
Box() }
{ BoxWeight()
width=height=depth=-1; {
} super();
Box(double len) weight=-1;
{ }
width=height=depth=len;
48 | Java Fundamentals

BoxWeight(double {
len,double m) super(ob);
{ weight=ob.weight;
super(len); }
weight=m; }
}
BoxWeight(BoxWeight ob)

class DemoSuper
{
public static void main(String x[])
{
BoxWeight b1=new BoxWeight(10,15,30,0.1);
BoxWeight b2=new BoxWeight(2,3,4,0.076);
BoxWeight b3=new BoxWeight();
BoxWeight b4=new BoxWeight(3,2);
BoxWeight clone=new BoxWeight(b1);
double vol;
vol=b1.volume();
System.out.println(“box1 volume is=” + vol);
vol=b2.volume();
System.out.println(“box2 volume is=” + vol);
vol=b3.volume();
System.out.println(“box3 volume is=” + vol);
vol=b4.volume();
System.out.println(“box4 volume is=” + vol);
vol=clone.volume();
System.out.println(“box5 volume is=” + vol);
}
}

The second form of super has the following general


form:-
The Second form of super is useful is in situations where member names of a sub class
hide members by the same name in super class.
e.g.,
class A
{
int i ;
}
Class B extends A
{
int i ;
B( int a, int b)
{
super.i = a ;
i=b;
}
void show ()
{
System.out.print ( “i in sub class = ” + I ) ;
System.out.print ( “i in super class = ” + super.i );
}
}
Class UseSuper
{
49 | Java Fundamentals

public static void main( String args[] )


{
B subob =new B(1,2);
subob.show();
}
}

Super class variable - sub class object:-


A reference variable of super class can be assigned a reference to any sub class derived
from that super class. When a reference to a sub class object is assigned to a super class
reference variable it will have access only those parts of the object define by the super
class.
e.g.,
class A
{
int i ;
void showA()
{
System.out.println (“ I = ” + i );
}
}
Class B extends A
{
int k;
B( int x, int y)
{
i=x;
k=y;
}
void show()
{
System.out.println (“I = ” + i + ” k = ” + k);
}
}
Class Ret Demo
{
public static void main (String args[])
{
A ob =new B(10,20);
Ob.showA();
}
}

Multilevel Inheritance:-
The procedure of deriving a class from another derived class is named as multilevel
inheritance.
50 | Java Fundamentals

A Super Class

B Intermediate Super Class

C Sub Class

The class A serves as a base class for the derived class B which in turn serves as a base
class for the derived class C. The chain ABC is known as inheritance path. The derived
class with multi-level base classes is declared as follows.

Class A
{
----------------
----------------
}
Class B extends A
{
----------------
----------------
}
Class C extends B
{
----------------
----------------
}

e.g.,
Import java.io.*;
Class Accel
{
double u, v,t;
BufferedReader x;
Accel()
{
x = new BuffredReader(new
InputStreamReader(System.in));
try
{
System.out.print (“\n enter initial velocity “);
u = Double.valueOf(x.readLine());
System.out.print (“\n Enter Final velocity ”);
v = Double.valueOf( x.readLine() );
System.out.print (“\n Enter time”);
t = Double.valueOf(x.readLine());
}
catch(Exception e){ }
}
double calculate ()
{
return ((v-u)/t);
}
51 | Java Fundamentals

}
Class Force extends accel
{
double m;
Force ()
{
super();
x = new BuffredReader(new InputStreamReader(System.
in));
try
{
System.out.print(“\n Enter Mass:”);
m = Double.valueOf(x.readLine());
}
catch(Exception e){ }
}
double calculate()
{
return( m * super. calculate() );
}
}

Class WorkDone extends Force


{
double s;
WorkDone()
{
super();
x = new BuffredReader(new InputStreamReader(System.
in));
try
{
Systerm.out.print (“\n Enter Displacement” );
s = Double.valueOf(x.readLine());
}
catch(Exception e){ }
}
double calculate()
{
return( s * super. calculate() );
}
}
Class AFW
{
public static void main(String args[])
{
WorkDone w1=new WorkDone();
double tmp=w1.calculate();
System.out.println (“work done =” + tmp );
}
}

Hierarchical Inheritance
Hierarchical Inheritance shows top-down style through splitting a compound class into
several simple sub classes. Below example shows a hierarchal classification of accounts
in a commercial bank.

Account

Savings Fixed Deposit Current

Short Medium Long


52 | Java Fundamentals

Hierarchical inheritance is declared as follows


Class A
{
------------------
------------------
}
Class B extends A
{
------------------
------------------
}
Class C extends A
{
------------------
------------------
}

e.g.,
import java.io.*;
class Shape
{
double area, circum;
BufferedReader x;
}
class Circle extends Shape
{
double radius;
Circle();
{
x =new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.print(“ Enter radius :”);
radius=Double.valueOf(x.readLine());
}
catch(Exception e){ }
}
void calculate()
{
area = 3.141549 * radius * radius;
circum = 2 * 3.14159 * radius;
}
}
Class Rectangle extends Shape
{
double length, breadth;
Rectangle ()
{
x = new BufferedReader(new
InputStreamReader(System.in));
try
{
53 | Java Fundamentals

System.out.print (“Enter Length ”);


length = Double.valueOf(x.readLine());
System.out.print(“Enter Breadth ”);
breadth = Double.valueOf(x.readLine());
}
catch(Exception e){ }
}
void calculate ()
{
area = length * breadth;
circum = 2 * ( length * breadth );
}
}
Class HInheritence
{
public static void main (String args[]);
{
Circle c1=new Circle();
Rectangle r1=new Rectangle ();
C1.calculate ();
r1.calculate ();
System.out.print(“area of circle = ” + c1.area +
“Circumference= ” + c1.circum);
System.out.print(“area of rectangle=” + r1.area +
“circumference=” + r1circum);
}

Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its super class, then the method in the subclass is said to override the
method in the superclass. When an overridden method is called, the method defined in
the subclass is invoked and executed instead of the one in the super class. The version of
the method defined in the super class will be hidden.
class A
{
int i,j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println(“ i and j : ” + i + “ ” + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a,b);
k = c;
54 | Java Fundamentals

}
void show()
{
System.out.println(“k : ” + k);
}
}
class Override
{
public static void main( String args[ ] )
{
B subob= new B(1,2,3);
subob.show();
}
}

When show( ) is invoked on a object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden function, you can do so by using
super keyword.
Dynamic Method Dispatch (Runtime Polymorphism)
Dynamic method dispatch is the mechanism by which a call to an overridden function is
resolved at run time, rather than compile time. Overridden methods allow java to support
run-time polymorphism. When an overridden method is called through a superclass
reference, java determines which version of that method to execute based upon the type
of the object being referred to at the time the call occurs. Thus, this determination is made
at run time.
class Figure
{
double dim1, dim2;
Figure( double a, double b)
{
dim1= a; dim2 = b;
}
double area()
{
System.out.println(“Area of figure is undefined”);
return 0;
}
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println(“Area of Rectangle”);
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a,b);
}
55 | Java Fundamentals

double area()
{
System.out.println(“Area of Triangle”);
return dim1*dim2;
}
}
class FindAreas
{
public static void main( String args[ ] )
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref =r;
System.out.println(“ Area is ” + figref.area());
figref =t;
System.out.println(“ Area is ” + figref.area());
figref =f;
System.out.println(“ Area is ” + figref.area());
}
}

Final Variables and Methods


All methods and variables can be overridden by default in subclasses. To prevent the
subclasses from overriding the members of the superclass, declare them as final using the
keyword final as a modifier.
final int size = 100;
final void showStatus( ){ . . . . . . . . . . . . . . . . . . .}
Making a method final ensures that the functionality defined in this method will never be
altered in anyway. Similarly, the value of final variables can never be changed. Final
variables, behave like class variables and they do not take any space on individual objects
of the class.

Final Classes
A class that cannot be sub classed is called a final class. To do this, precede the class
declaration with final.
final class Aclass
{
---------
---------
---------
}
Any attempt to inherit this class will cause an error and the compiler will not allow it.
Declaring a class as final implicitly declares all of its method as final, too.
Abstract methods and classes
Abstract method is a method which must always be redefined in a subclass, thus making
overriding compulsory. This is done using the modifier keyword abstract in the method
definition.
Abstract type name(parameter-list);
56 | Java Fundamentals

Abstract method doesn’t consists body and even parenthesis. When a class contains one
or more abstract methods, it should also be declared as abstract.
abstract class Shape
{
----------
----------
----------
Abstract void draw();
----------
----------
}
Abstract classes cannot be used to instantiate objects but they can be used to create object
references. Any subclass of an abstract class must either implement all of the abstract
methods in the super class or be itself declared as abstract. Also we cannot declare
abstract constructors or abstract static methods.
abstract class A
{
abstract void callMe();
void callMeToo()
{
System.out.println(“This is a concrete method”);
}
}
class B extends A
{
void callMe()
{
System.ut.println(“B’s implementation of callme”);
}
}
class AbsractDemo
{
public static void main(String args[ ])
{
B b= new B();
b.callMe();
b.callMeToo();
}
}
57 | Packages and Interfaces In Java

UNIT – 3

ARRAYS,STRINGS AND VECTORS


Array
An Array is a group of contiguous or related data items that share a common name.
Arrays of any type can be created and may have one or more dimensions. A specific
element in an array is accessed by its index.
One Dimensional Array
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one dimensional array. Creation of an
array involves three steps
1. Declaring the array.
2. Creating memory location.
3. Putting values into the location.
Declaration of Array
Arrays in java may be declaring in two forms.
type arrayname[ ];

type[ ] arrayname;

Here type declares the base type of the array. The base type of the array determines what
type of the data the array will hold.
e.g.,
int number[];
float[] marks;
Creation of Arrays
After declaring an array we need to create it in the memory. Java allows us to create array
using new operator.
arrayname= new type[size];

Here type specifies the type of the data being allocated. size specifies the number of
elements in the array.
e.g.,
number=new int[5];
Marks=new float[10];
Now the variable number refers to an array of 5 integers and marks refers to an array of
10 floating point values. The elements in the array allocated by new will automatically be
initialized to ‘0’.
Initialization of arrays
This is done using the array subscript as shown below.
Arrayname[subscript]=value;
58 | Packages and Interfaces In Java

e.g,
number[0]=35;
number[1]=40;
All array indexes start at zero. Array can be initialized when they are declared.
Initialization of arrays takes the following form.
type arrayname[ ]={list of values};

An array initializer is a list of comma separated expressions surrounded by the curly


braces. The array will automatically be created large enough to hold the number of
elements you specify in the array initializer.
int a[ ]={1,2,3};
It is possible to assign an array object to another.
e.g.,
int a[]={1,2,3};
int b[];
b=a;
Array length
In java all arrays stores the allocated size in a variable name length. We can obtain the
length of the array ‘a’ using a.length;
Ex:
class NumberSorting
{
public static void main(String x[])
{
int number[]={55,40,80,60,71};
int n=number.length;
System.out.println(“given list:”);
for (int i=0;i<n;i++)
System.out.println(number[i]);
System.out.println
for(int i=0;i<n-1;i++)
{
for (int j=i+1;j<n;j++)
{
if(number[j]<number[i])
{
int temp=number[i];
number[i]=number[j];
numbr[j]=temp;
}
}
}
System.out.println(“sorted list”);
for(int i=0;i<n;i++)
System.out.println(number[i]);
}
}

Two dimensional array


Tow dimensional arrays are having two indexes or subscript values instead of one. The
first index or dimension represents row and the second index selects column within that
row. We may create a two dimensional array like this.
int myarray[ ][ ];
59 | Packages and Interfaces In Java

myarray=new int[3][4];

This creates a two dimensional array with 3 rows and 4 columns and which can store 12
integer values.
A two dimensional array may be initialized by following their declaration with a list of
initial values enclosed in brasses.
Ex: int table[2][3]={0,0,0,1,1,1};
Initializes the first row to 0’s and second row to 1’s. The above statement can be
ebulliently written as
int table[ ][ ]={{0,0,0},{1,1,1}};
by surrounding the elements of each row by brasses.
We can refer to a value stored in a two dimensional array by using subscripts for the both
column and row of the corresponding element.
Ex: int value=table[1][2];
This retrieves the value stored in second row and third column of table array.
Ex:
class MulTable
{
final static int ROWS=20;
final static int COLUMNS=20;
public static void main( String x[ ] )
{
int product[][]=new int[ROWS][COLUMNS];
System.out.println(“multiplication table”);
int i,j;
for(i=0;i<ROWS;i++)
{
for(j=10;j<COLUMNS;j++)
{
product[i][j]=i*j;
System.out.println(“ ”+product[i][j]);
}
System.out.println();
}
}
}

Variable size arrays


Java treats multidimensional array as arrays of arrays. It is possible to declare a two
dimensional array as follows.
int temp[ ][ ]=new int[3][ ];
temp[0]=new int[2];
temp[1]=new int[4];
temp[2]=new int[3];

These statement creates a two dimensional array as having different lengths for each row
as shown below. Tmp[0][1]
tmp[0]
tmp[1]
60 | Packages and Interfaces In Java

tmp[2]

Tmp[1][3]
Tmp[2][2]

Strings
In java strings are class objects. A java string is an instantiated object of the string class.
String can be implemented using two classes namely ‘String’ and ‘StringBuffer’. The
object of the String is immutable. Once a string is created its content cannot be altered.
Java defines peer class of string called string buffer which allows strings to be altered. A
java string is not a character array and is not null terminated. Strings may be declared and
created as follows.
String stringname;
stringname=new String(“string”);
(or)
String strigname= “string”
e.g.,
String firstname;
firstname=new String(“anil”);
like arrays it is possible to get the length of the string using the length method of the
string calss.
int z=firstname.length();
java defines one operator for string objects i.e., plus(+). It is used to concatenate two
strings.
Ex:
String fullname=name1+name2;
String city= “new”+ “delhi”;

Ex:
class StringDemo
{
public static void main(String x[])
{
String strob1=”anil”;
String strob2=”sunil”;
String strob3=strob1+strob2;
System.out.println(“strob1+”\n”+strob2+”\n”+strob3);
}
}

String arrays
It is also possible to create and use arrays that contain strings. The statement
String s[ ]=new String[3];
Will create an of size 3 to hold the three string constants.
String methods
The String class defines a number of methods that allows us to accomplish a variety of
string manipulation tasks.
Character extraction:
The String class provides a number of ways in which characters can be extracted from a
String objects.
charAt()
61 | Packages and Interfaces In Java

To extract a single character from a string, we can refer directly to an individual character
via the charAt() method. It has this general form
char charAt(int n)

Here ‘n’ is the index of the character that you want to obtain. The value of ‘n’ must be
non negative and specify a location within the string. A charAt() method returns a
character at the specified location.
Ex:
char ch1;
ch1=”abc”.charAt(1);
assigns the value ‘b’ to ch1.

getChars()
getChars() method is used to extract more than one characters at a time. It has this
general form.
void getChars(int sourcestart, int sourceend, char target[ ], int
targetstart)

Here sourcestart specifies the index of the beginning of the substring and source end
specifies an index i.e, one past the end of the desired sub string. The array that will
receive the characters is specified by the target. The index within the target at which the
sub string will copied is passed in targetstart.
Ex
class GetCharsDemo
{ Output
public static void main(String x[ ]) demo
{
String s=”this is a demo of get chars method”;
int start=10,end=14;
char buf[ ]=new char[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf);
}
}

toCharArray()
It is used to convert all the characters in a string object into a character array. It has this
general form.
char[ ] toCharArray( )

Ex: char a[]=”sai sree”.toCharArray();

String comparison methods

equals() & equalsIgnoreCase()


equals() method is used to compare two strings for equality. It has this general form
boolean equals(object str)

Here, str is the string object being compared with the invoking string object. It returns
true if the strings contain the same characters in the same order and false otherwise. The
62 | Packages and Interfaces In Java

comparison is case-sensitive. To perform a comparison that ignore case differences, call


equalsIgnoreCase() method. it has the general form
boolean equalsIgnoreCase(object str)

Ex: Out put


class equalsDemo
hello equals hello -> true
{
hello equals bye -> false
public static void main(String x[])
hello equals HELLO -> false
{
String s1= “hello”,s2= “hello”,s3= “bye”,s4=
hello“HELLO”;
equalsIgnoreCase HELLO -> true

System.out.println(s1+“equals”+s2+“->”+s1.equals(s2));
System.out.println(s1+“equals”+s3+“->”+s1.equals(s3));
System.out.println(s1+“equals”+s4+“->”+s1.equals(s4));
System.out.println(s1+“equalsIgnoreCase”+s4+“-
>”+s1.equalsIgnoreCase(s2));
}
}
equals() verses = =
equals() method compares the character inside a string object where as == operator
compares two object references to see whether they refer to the same instance.
Ex:
class Equals
{ Output
public static void main(String x[]) hello equals hello true.
{
String s1=”hello”; Hello==hello false
String s2=new String(s1);
System.out.println(s1+”equals”+s2+s1.equals(s2));
System.out.println(s1+”==”+s2+(s1==s2));
}
}

compareTo( )
The String class method compareTo() has this general form
int compareTo(String str)
Here, str is the string being compared with the invoking string. The result of the
comparison is returned and interpreted as show below.
Value meaning
<0 the invoking string is less than str
>0 the invoking string is greater than str
=0 the two strings are equal
Ex.
Class SortString
{ static String array[ ] = {“now”, “is”, “the”, “time”, “for”,
“all”, “good”, “men”, “to”, “the”, “aid”,
“of”, “their”, “country”};
public static void main(String x[])
{
int n=array.length;
String temp;
63 | Packages and Interfaces In Java

for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(array[i].compareTo(array[j]) < 0)
{ temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
for(int i=0;i<n;i++) System.out.println(“ ”+array[i]);
}}
startWith() & endsWith()
The startwith() method determines whether a given string begins a specified string
conversely endswith() method determines whether a given string ends with a specified
string. They have the following general forms.
boolean satartWith(String str)
boolean endsWith(String str)
Here str is the string being tested. If the string is matches true is returned otherwise false
is returned.
Ex:
“sai sree”.endsWith(“sree”)
“sai sree”,startsWith(“sai”)
Are both true.
A second form of startsWith is as shown bellow.
boolean startsWith(String str,int Stringindex)

Here start index specifies the index into the invoking at which point the search will begin.
Ex: “Bharitha”.startsWith(“hari”,1) returns true.

Searching Strings
The string class provides two methods that allow you to search a string for a specified
character or substring.
indexOf() & lastIndexOf().
indexOf() searches for the first occurrence of character or sub string, lastIndexOf()
searches for the last occurrence of a character or substring.
The methods returns the index at which the character or sub string was found or -1 on
failure.
The general forms of these methods are
int indexOf(char ch);

Searches for the first occurrence


int lastIndexOf(char ch);

Searches for the last occurrence of char ch


int indexOf(String str);

Searches for the first occurrence of a sub string str


int lastIndexOf(String str);
64 | Packages and Interfaces In Java

Searches for the last occurrence of a sub string str


We can also specify a starting point for the search using these forms.
int indexOf(char ch,int startindex);

int indexOf(String str,int startindex);

int lastIndexOf(char ch,int startindex);

int lastIndexOf(String str,int startindex);

Modifying a string
substring()
substring() method is used to extract a substring from a given string. It has two forms.
String substring(int startindex);

Here startindex specifies the index at which the substring will begin. It returns a substring
that begins at start index to the end of the invoking string.
Ex: String s1=”this is a test”.substring(5);
puts “is a test” in to s1.
The second form allows to specify both beginning and ending index of the substring. This
has the following general form.
String substring(int startindex,int endindex);

Ex: String s1=”this is a test”.substring(5,7);


Puts “is” in to s1.
concat()
concat() method is used to concatenate two strings. This has the following general form.
String concat(String str);

Ex: String s1=“one”.concat(“two”)


Puts the string ‘onetwo’ into s1.
replace()
The replace() method replace all occurrence of one character in the invoking string with
another character . It has the following general form.
String replace(char original, char replacement)

String s= “hello”.replace(‘l’,’w’);
Sets ‘hewwo’ into ‘s’.
trim()
The trim() method return a copy of the invoking string from which any leading, trailing
white spaces have been removed. It has this general form.
String trim()

Ex. String s=” hello world “.trim();


This puts “hello world” into ‘s’.
toLowerCase() & toUppercase():
65 | Packages and Interfaces In Java

The method toLowerCase() converts all the characters in a string to lower case. The
toUppercase() method converts all characters into uppercase. Non alphabet characters
such as digits are unaffected. The general form of this method are
String toLowerCase();

String toUpperCase();

Ex:
String s1=”This is a test”.toLowerCase();
String s2=”this is a test”.toUpperCase();

Puts “this is ia test” in ‘s1’ and “THIS IS A TEST” in ‘s2’.

valueOf()
The valueOf() method converts data from its internal format into a human readable form .
It is a static method that is overloaded with in String for all of java building types, so that
each type can be converted properly into a string here are few of its forms.
static String valueOf(double num)

static String valueOf(long num)

static String valueOF(char ch[])

StringBuffer
StringBuffer is peer class that provides much of the functionalities of strings.
StringBuffer represents growable and readable character sequences. StringBuffer may
have characters and substring inserted in the middle or append to the end.
Constructors
StringBuffer defines these three constructors.
StringBuffer( )
StringBuffer( int )
StringBuffer( String str )
The no argument constructer reserves room for 16 characters. The second version accepts
an integer argument that explicitly sets the size of the buffer. The third version accepts
the String argument that sets the initial contents of the StringBuffer object and reserves
room for 16 more characters.
String buffer methods
Length( ) & capacity( )
The current length of StringBuffer can be found via the length method, while the total
allocated capacity can be found through the capacity method(). They have the following
general forms.
int length( )

int capacity( )
Output
Ex: buffer = HELLO
class SubDemo
{ length = 5
public static void main(String args[ ] ) capacity = 21
{
StringBuffer sb=new StringBuffer(“HELLO”);
66 | Packages and Interfaces In Java

System.out.println(“buffer =” + sb);
System.out.println(“length=” + sb.length()+ “\n capacity
=” + sb.capacity() );
}
}

ensureCapacity()
ensureCapacity() is used to set the size of the buffer to pre-allocate room for a certain
number of characters after StringBuffer has been constructed. It has this general form
void ensureCapacity (int size)

Here size specifies the size of the buffer.

setLength()
setLength() is used to set length of the Buffer within a String Buffer object. Its general
form is
void setLength (int capacity)

Here capacity specifies the length of the buffer and it must be non negative. When you
increase the size of the buffer, null characters are added to the end. If we call setLength()
with a value less than the current value then the character stored beyond the new length
will be lost.
charAt() & setCharAt()

The value of a single character can be obtained from a StringBuffer via a charAt()
method. We can set the value of a single character using setCharAt() method. Their
general forms are
char charAt (int where)

void setCharAt(int where, char ch)

For charAt(), where specifies the index of the character being obtained. For setCharAt(),
where specifies the index of the character being set and ‘ch’ specifies the new value of
the character. For both methods where must be non-negative and must not specify a
location beyond the end of the buffer.
Ex:
Class SetCharDemo
{
Output
public static void main(String args[ ])
{ buffer before = Hello
StringBuffer sb=new StringBuffer (“Hello”);
System.out.println (“buffer before =” + sb); Char[1] before = e
System.out.println (“charAt [1] before=” + sb.charAt(1) );
buffer after = Hi
sb.setCharAt(1,‘i’);
sb.setLength(2); Char[1] after = i
System.out.println(“buffer after =” + sb);
System.out.println( “char[1] after=” + sb.charAt(1) );
}
}

getChars()
67 | Packages and Interfaces In Java

getChars() method is used to copy a sub string of a string buffer into an array. It has this
general form
void getChars(int startindex, int endindex, char[ ] temp, int
targetindex)

append()
The append() method concatenates the string representation of any other type of data to
the end of the invoking StringBuffer. It has overloaded version for all the built-in in types
and for objects
StringBuffer append(int) StringBuffer (short)

StringBuffer (byte) StringBuffer (long)

StringBuffer (float) StringBuffer (double)

StringBuffer(Object)

Ex:
class AppendDemo Output
{
public static void main(String args[ ]) a=42!
{
String s;
int a=42;
StringBuffer sb=new StringBuffer(40);
s=sb.append(“a = ”).append(42).append(‘!’).tostring( );
System.out.println( S );
}
}

insert():

insert() method inserts one string into another. It is overloaded to accept the values of all
the simple type, strings and objects. These are few of its forms
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)

Here index specifies the index at which point the string will be inserted into the invoking
StringBuffer object
Ex :
class InsertDemo
{ Output
public static void main(String args[ ]) I Like java
{
StringBuffer sb=new StringBuffer(“ I java “);
sb.insert(2,”Like “);
System.out.println( sb );
}
}

reverse()
68 | Packages and Interfaces In Java

we can reverse the characters within a StringBuffer object using reverse() method. The
general form is
StringBuffer reverse()

Ex :
Class ReverseDemo Output
{ able was I ere I saw elbA
public static void main(String args[ ])
{
StringBuffer sb=new StringBuffer(“ Able was I ere I saw
elba “);
sb.reverse();
System.out.println(sb);
}
}

delete() & deleteCharAt()


delete() & deleteCharAt() are able to delete characters in the StringBuffer object. Their
general forms are
StringBuffer delete(int startindex, int endindex)

StringBuffer deleteCharAt(int loc)

The delete() method deletes a sequence of charecters. Here start index specifies the index
of the first character to remove and end index specifies an index one past the last
character to remove. The deleteCharAt() method deletes the character at the index
specified by loc.
Ex :
class DelDemo
{
public static void main(String args[ ]) Output
{
After delete : This a test
StringBuffer sb=new StringBuffer(“ This is a test “);
sb.delete(4,7); After delete charAt : his a test
System.out.println(“After delete:”+ sb );
sb.deleteCharAt(0);
System.out.println(“After delete charAt : “+sb );
}
}

replace()
The replace() method replaces one set of characters with another set inside a StringBuffer
object. It has the following form.
StringBuffer replace( int startindex, int endindex, String str)

The substring being replaced is specified by indexes startindex & endindex. The
replacement string is passed in str.
Ex :
class ReplaceDemo Output
{
public static void main(String args[ ]) After replace: This was a test.
{
StringBuffer sb=new StringBuffer(“ This is a test “);
sb.replace(5,7,“was”);
System.out.println(“After replace : ” + sb );
}
69 | Packages and Interfaces In Java

Substring()
The substring() method returns a portion of a StringBuffer. It has the following two
forms.
String substring(int startindex)

String substring(int startindex, int endindex)

The first form returns a substring that starts at startindex and runs to the end. The second
form returns the substrings that starts at startindex and runs through endindex-1

Interfaces
Interfaces are syntactically similar to class but they define only abstract methods and
final fields. This means that the interfaces cannot specify any code to implement these
methods and data fields contain only constants. Therefore, it is the responsibility of the
class that implements an interface to define the code for implementation of these
methods. Once it is defined any number of classes can implement an interface. The
general form of an interface definition is

access_specifier interface_name

Variable declaration;

Method declaration;

Here access_specifier is either public or not used. When no access_specifier is included,


then default access results. interface is the keyword and interface_name is any valid java
identifier .variables are declared as follows.
static final type variablename = value;

Method declaration contains only a list of methods without any body.


return_type methodname (argument list);

All the methods and variables are implicitly public if the interface is declared as public.
Ex:
interface item
{
static final int code=100;
static final String name=”fan”;
void display();
}

Implementing interfaces
Once an interface has been defined, one are more classes can implement that interface.
To implement an interface include implements clause in a class definition and then create
70 | Packages and Interfaces In Java

methods defined by the interface. The general form of the class that implements an
interface is as follows.
class calassname [extends superclassname] [implements
interface1, interface2……]

{ …………………

………………..

If a class implements more than one interface, the interfaces are separated with a coma(,).
If the class implements two interfaces that declare the same method then the same
method will be used by clients of either interface. The methods that implement an
interface must be declare as public. Also the type signature of implementing method must
match exactly the type signature specified in the interface definition.
Ex:
interface Area
{
final static float PI=3.4f;
abstract float compute(float x,float y);
}
class Rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute(float x,float y) Output
{ Area of circle = 154.00
return(PI*x*x);
} Area of Rectange = 49.00
}
class InterFaceTest
{
public static void main(String args[])
{
Circle c=new Circle();
Rectangle r=new Rectangle();
System.out.println("Area of circle=" + c.compute(7,0)+
"/nArea of Rectangle="
+ r.compute(7,7) );
}
}

We can also declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred to
by such a variable. If a class includes an interface but does not fully implement the
methods defined by that interface, then that class must be declared as abstract.
Extending interfaces
One interface can inherit another by the use of the keyword extends. That is an interface
can be sub interfaced from other interfaces. When a class implements an interface that
inherits another interface, it must provide implementations for all methods defined within
the interface inheritance chain.
71 | Packages and Interfaces In Java

Multiple Inheritance:
When a class is derived from a class and implemented one or more interfaces is called
multiple inheritance. Properties of class & various interfaces are transferred to single
derived class.

class A interface B Interface C

class D

Ex:
class Student
{
int rollnumber;
void getNumber(int n)
{ rollnumber = n; }
void putNumber()
{ System.out.println(“Roll Number = ” + rollnumber); }
}
class Test extends Student
{
float part1, part2;
void getMarks(float m1, float m2)
{ part1 = m1; part2 = m2;}
void putMarks()
{
System.out.println(“Marks Obtained :\nPart1 =” + part1 +
“\nPart2 =” + part2);
}
}

interface sports
{
float sportwt = 6.0f;
public void putWt();
}
class Results extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println(“Sports Weight =” + sportwt);
}
void display()
{
total = part1+part2;
putNumber();
putMarks();
putWt();
System.out.println(“Total = ”+ total);
}
}
Class MInherit
{
public static void main(String args[])
{
Results student1= new Results();
72 | Packages and Interfaces In Java

student1.getNumber(120);
student1.getMarks(20.5f, 32.5f);
student1.display();
}
}

Packages:
Packages are a way of grouping a variety of classes and/or interfaces together. Packages
are act as containers for classes. Packages have the following benefits.
1. The classes contained in the packages of other programmers can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is
two classes in two different packages can have the same name. They may be referred
by their fully qualified name, comprising the package name and the class name.
3. Packages provide away to hide classes thus preventing other programmers or
packages from accessing classes that are meant for internal use only.
4. Packages also provide away for separating design from coding. First we can design
classes and decide their relationships, and then we can implement the java code need
for the methods.
Creating Packages
A package can be created by simply including a package command as the first statement
in a java source file. Any classes declared within the file belong to the specified package.
If the package statement is omitted the class names are put in default packages which has
no name. The general form of the package statement is
Package packagename;

Ex:
Package MyPackage;
Public class FirstClass
{
body of the class
}
Here the package name is MyPackage. The class FirstClass is now considered a part of
this package. This listing would be saved as a file called FirstClass.java and located in a
dictionary named MyPackage. Here the case is significant. When the source file is
compiled java will create a .class file and store it in the same directory. Java also supports
the concept of package hierarchy. This is done by specifying multiple names in a package
statement, separated by dots.
Package firstpackage.secondpackage ;

But this package is needed to be stored in a sub directory firstpackage\secondpackage


A java package file can have more than one class definition in such cases, only one of the
classes may be declared as public and that class name with .java extension is the source
file name. When a source file with more than one class definition is compiled java creates
independent .class files for these classes
Ex:
package MyPackage;
class Balance
{
String sname;
double bal;
balance(String s, double b)
{
sname = s;
73 | Packages and Interfaces In Java

bal=b;
}
void show( )
{
System.out.println(sname+“ ”+bal);
}
}
public class AccountBalance
{
public static void main(String args[ ])
{
Balance current[ ]=new Balance[3];
current [0] = new Balance( ” jagan ”,25360.50);
current [1] = new Balance( ” manohar ”,30560.75);
current [2] = new Balance( ” rajashekar ”,15555.55);
for(int i=0;i<=2;i++)current[i].show( );
}
}

Accessing a package
They are two ways accessing a class stored in a package. The first approach is to use the
fully qualified class name of the class that we want you use. This is done by using the
package name containing the class and then appending the class name to it using the dot
operator.
Ex: java.awt.colour

It will refer the class color in awt package which is the sub package of java package. This
approach well suited when we need to access the class only once or we need not to have
access any other class in the package. When we want to use a class in a number of places
in the program or we may like to use many of the classes contained in the package, it can
be achieved by using import statement. The general form of import statement is
import packages1.[ package2].[ package3]. classname;

Here the package1 is the top level package and package2 is the name of the package that
is inside the package1 and so on. We can have any number of packages in a package
hierarchy. Finally the explicit classname is specified.
Ex: import firstpackage.secondpackage.myclass;

We can use another approach as follows


import packagename.*;

Here packagename may denote a single package or a hierarchy of packages. The *


implies that we can access all classes contained in the package.
Hiding Classes
When import a package using * (asterisk ) all public classes or imported. However, we
may prefer to not import certain classes. To hide classes from accessing from outside of
the package such classes should be declared not public
Ex:
package p1;
public class Y
{
body
}
class Z
74 | Packages and Interfaces In Java

{
bodyz
}

Here the class Z which is not declared as public is hidden from outside of the package p1.
This class can be seen and used only by other classes in the same package. A java source
file should contain only one public class and may include any number of non public
classes.
Static import
This feature eliminates the need of qualifying a static member with the class name. The
static import declaration is similar that of import. We can use the static import statements
to import static members from classes and use them without qualifying the class name.
The syntax for using the static import feature is
import static packagename [subpackagename].classname.
staticmembername;

import static package name [.subpackagename].classname.*;

Ex:
import static java.lang.math.*;
public class MathOp
{
public static circle (double r)
{
double area=PI*r*r;
System.out.println(“Area =”+area);
}
public static void main(String args[ ])
{
MathOp m1=new MathOp( );
m1.circle(2.3);
}
}

Java API Packages


Java API (Application Program interface) provides a large number of classes grouped
into different packages according to functionality. The following figure shows the
functional breakdown of packages that are frequently used in programs

java

lang util io awt net applett

The below table shows the classes that belong to each package

Package Name Contents

java.lang Language support classes that java compiler itself uses abd
therefore they are automatically imported. They include Strings,
75 | Packages and Interfaces In Java

Math, Threads and Exceptions


java.util Language utility classes such as Vectors, Hash Tables, Random
Numbers e.t.c.,
java.io Input/Output Suppot classes. They provide facilities for the input
and output of data
java.awt Set of classes for implementing graphical user interface, they
include Windows, Buttons, Lists and Menus
java.net Classes for networking
java.applet Classes for creating and implementing applets

WRAPPER CLASSES
Primitive data types may be converted in to object types by using wrapper classes
contained in the java.lang package. Below table shows a simple data types and their
corresponding wrapper class types.
Simple type Wrapper Class

short Short
byte Byte
int Int
long Long
float Float
double Double
char Char
Boolean Boolean

The wrapper class has a number of unique methods for handling primitive data types and
objects they are

For converting primitive to object numbers.


Constructor methods
Integer(int i), Integer(String str) throws NumberFormatException
Float(float f), Float(String str) throws NumberFormatException
Float(double d) throws NumberFormatException
Double(double d), Double(String str) throws NumberFormatException
Long (long l), long(String str) throws NumberFormatException
Byte (byte b), Byte(String str) throws NumberFormatException
Short(shorts), Short(String str) throws NumberFormatException
Character (character ch)
Boolean (boolean b), Boolean(String str)
Convecting object numbers to primitive numbers
All these methods are available in all wrapper classes except Character and Boolean.
byte byteValue ( ) – returns value as a byte
76 | Packages and Interfaces In Java

double doubleValue( ) – returns value as a double


float floatValue( ) – returns value as a float
int intValue( ) – returns value as a int
long longValue( ) – returns value as a long
short shortValue( ) – returns value as a short.
Converting object numbers to Strings
String toString( ) returns a string that contains the decimal equivalent of the invoking
object. This method is defined by all the wrapper class.
Converting String objects to Numeric objects
We can convert a string object to numeric object data type using valueOf ( ) methods
define by all the wrapper classes. It is a static method it takes a string object as argument.
Converting Numeric strings to primitive numbers
parseShort(), parseByte(), parseInt(), parseLong(), parseFloat(), parseDouble() methods
are defined by the corresponding wrapper classes Short, Float, Integer, Byte, Long,
Double. All these methods are static .They take a string object as argument and convert it
in to primitive numbers. These methods throw NumberFormaException.
Ex:
import java.io.*;
class Invest
{
public static void main(String args[ ])
{
float principle=new Float(0);
float interest=new Float(0);
int years=0;
try
{
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
System.out.println (“Enter Princple amount : “);
System.out.flush( );
String s=x.readLine( );
Principle = Float.valueOf( );
System.out.println(“Enter interest rate: “);
Interest = Float.valueOf(x.readLine());
System.out.println (“Enter Years: “);
years = Integer.parseInt (x.readLine());
}
catch(Exception e) {}
float value = loan (principle. Float value (), interest. Float
value(),years);
printLine( );
System.out.println(“ Final value =“ + value);
}
static float loan (float p, float I, int y)
{
int year=1;float sum =p;
while (year<=y)
{
sum=sum*(1+i);year++;
}
}
static void printLine( )
{
77 | Packages and Interfaces In Java

for(int i=1;i<=30,i++)
System.out.println (“= “);
System.out.println (“ “);
}
}

Enumerated types (or) Enum types


An enum type is a type whose field consists of a fixed set of constants. common example
includes compass directions and the days of the week because they are constants. The
names of an Enum type fields are in upper case letters. In java, we define Enum type by
using the enum key word.
Ex:
public enum Day
{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY}
enum types are used to represent a fixed set of constants. The enum declaration defines a
class. The enum class body can include methods and others fields. The compiler
automatically adds some special methods when it creates an enum. They have a static
values() method that returns an array containing all of the values of the enum in the order
they are declared
class WorkingDays
{
enum Days
{ SUNDAY,………, SATURDAY }
public static void main( String args [])
{
for ( Days d: Days.values() )
{
weekend(d);
}
}
public static void weekend(Days x)
{
if(x.equals(Days.SUNDAY))
{
System.out.println(“ Value is “+d+”is holiday”);
}
ElseSystem.out.println(“value =”+d+”is a working day “);
}
}

VECTORS
Vector class can be used to create a generic dynamic array known as "Vector". That can
hold objects of any type and any number. The objects do not have to be homogeneous.
Vector class consist the following constructors.
Vector( )

Vector(int size)

Vector( int size,int incr)

The first form creates a default vector, which has initial size of 10. The second form
creates a vector whose initial capacity specified by size. The third form creates a vector
whose initial capacity specified by size and whose increment is specified by incr. All
78 | Packages and Interfaces In Java

vectors starts with an initial capacity. After the initial capacity is reached the vector
automatically allocates space for additional objects. The amount of extra space allocated
during re-allocation is determined by the variable incr. If incr is not specified the vector
size is doubled by each re-allocation.Vector defines these protected data members
int capacityIncrement
int elementData[ ] (Object class array)
int elementCount
The increment value is stored in capacityIncrement. The number of elements currently in
the vector is stored in elementCount. The array that holds the vector is stored in
elementData. Vector possesses a number of advantages over arrays.
1. It is convenient to use vectors to store objects.
2. The vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects of different classes from the list as and when required.
A major constraint in using vector is it cannot stores simple data types, it can be only
store objects. The vector class supports the following methods that can be used to
manipulate the vector created

Method Description
final void addElement(Object element) Adds the element specified to the rest at the end.
int capacity( ) Returns the capacity of the vector.
boolean contains(Object element) Returns true if element is contained by the vector and
returns false if it is not.
void copyInto(Object array[ ]) Copies all items from list to array.
Object elementAt(int index) Returns the element at the location specified by index.
int indexOf(Object element) Returns the index of first occurrence of element if the
object is not present returns -1.
void insertElementAt(Object ele, int index) Inserts elements at the location specified by the index.
boolean isEmpty( ) Returns true if vector is empty otherwise false.
void removeAllElements( ) Removes all elements in the list.
void removeElement(int index) Removes the element at the specified index.
int size( ) Gives the number of objects present.
void trimToSize( ) Sets the vector capacity equal to the number of
elements that is currently holds.

Ex :
import java.util.*;
import java.io.DataInputStream;
class Student
{ int admno; String name;
Student()
{
try
{
DataInputStream x=new DataInputStream (System.in);
System.out.println(“Enter admission number :”);
admno=Integer.parseInt(x.readLine());
System.out.println(“Enter student name :”);
name=x.readLine();
79 | Packages and Interfaces In Java

}
catch(Exception e){ }
}
void display()
{
System.out.println(“Name is “+name+”admission number
is”+adm no);
}
}
class Staff
{
float salary; String name;
Staff()
{
try
{
DataInputStream x=new DataInputStream(System.in);
System.out.println(“Enter name :”);
name=x.readLine();
System.out.println(“Enter salary :”);
salary=Float.parseFloat(x.readLine());
}
catch(Exception e){}
}
viod display()
{
System.out.println(“Name is”+name+”salary is”+salary);
}
}
class Display
{
public static void main ( String args[ ])
{
Vector v=new Vector(2)
v.addElement(new Student());
v.addElement(new Staff());
for(int i=0;i<=1;i++)
{
if(v.elementAt(i) instanceof Student)
{
Student s1=(Student)v.elementAt(i);
s1.display();
}
else
{
Staff s2=(Staff)v.elementAt(i);
s2.diaplay();
}
}
}
}
80 | Multithreaded Programming And Applets

UNIT – 4
MULTITHREADED PROGRAMMING AND APPLETS

Multithreaded Programming
Multithread is a conceptual programming paradigm where a programming is divided into
two or more sub programs, which can be implemented at the same time in Parallel. For
example, one program can display animation on the screen while another may build the
next animation to be displayed. A thread is similar to a program that has Single flow of
control. It has beginning, a body, and an end and executes commands sequentially. Every
program will have at least one thread as shown below.
Class ABC
{ ………… Beginning
………… single thread
…………. Body of execution
…………. End
}
A unique property of java is its support for multithreading i.e. java enable us to use
multiple flows of control in developing program. Each flow of control may be thought of
as a separate tiny program (or module) known as thread that runs in parallel to others as
shown below.
Main Thread

Start Start Start

switching switching

Thread A Thread B Thread C

A program that contains multiple flows of control is called “multithread Programming”


The above figure illustrates a java program with four threads, one main and there others.
The main thread is actually the main method module, which is designed to create and
start the other three threads namely A,B and C.
Once initiated by the main thread the threads A, B and C run concurrently and share the
resource jointly. The ability of a language to support multithreads is referred to as
concurrency. Since, threads in java are subprograms of main application program and
share the same memory space they are known as lightweight threads (or) lightweight
process.
81 | Multithreaded Programming And Applets

Creating threads
Threads are implemented in the form of objects that contain a method called run( ). It
makes up the entire body of a thread and is the only method in which the thread’s
behaviour can be implement .A run( ) would appear as follows.
public void run( )
{
………………….
…………………. .. (Statements for implanting thread)
………………….
}
The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another method called
start( ). A new thread can be created in two ways.
1. By creating a thread class :
Define a class that extends Thread class and override its run( ) method with the
code required by the thread.
2. By converting a class to a thread:
Define a class that implements Runnable interface. The Runnable interface has
only one method, run( ) that is to be defined in the method with the code to be
executed by the thread.
Extending Thread class
To make a class runnable as thread by extending that class by java.lang.Thread. This
gives access to all the thread methods directly. It includes the following steps.
1. Declare the class as extending the Thread class
2. Implement the run( ) method.
3. Create a thread object and call the start( ) method.
Declaring the class
The Thread class can be extended as follows.
Class MyThread extends Thread
{
……………
……………
……………
}
Implementing the run( ) method
The run method has been inherited by the class MyThread. We have to override this
method. The basic implementation of run will look like these.
Public void run ( )
{
…………….
…………….
……………..
}
82 | Multithreaded Programming And Applets

Starting New thread


The thread can be started by writing the following
MyThread athread= new MyThread( );
athread.start( );

Ex:
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.print(“\t thread A:i=”+i);
}
System.out.print(“exit from A”);
}
}
Class B extends Thread
{
public void run()
{
for (int j=1;j<=5;j++)
{
System.out.print(“\t thread B: j=”+j);
}
System.out.print(“exist from B”);
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.print(“\t thread C:k=”+k);
}
System.out.print(“exist from C”);
}
}
Class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start( );
new C().start( );
}
}

Implementing the Runnable interface


The Runnable interface declares the run( ) method that is required for implementing
threads in the program. It includes the following steps
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
83 | Multithreaded Programming And Applets

3. Create a thread by defining an object that is instantiated from this runnable class as
the target of the thread .
4. Call the thread’s start( ) method to run the thread .
Ex.
Class X implements Runnable
{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.print(“it thread x:i=”+i)
}
System.out.print(“end of thread”);
}
}
Class RunnableTest
{
public Static void main(String args[])
{
X runnable=new X( );
Thread threadx=new Thread(runnable);
threadx.start( );
System.out.println(“End of main thread);
}
}
The main thread
When a java program starts up one thread begins running immediately. This is usually
called the main thread. It is the thread from which other child threads will be spawned.
Often it must be the last thread to finish execution. Although main thread is created
automatically, it can be controlled through a Thread object. A reference to the main
thread can be obtained by calling the method currentThread( ), which is public static
member of Thread class. Tts general form is
static Thread currentThread( )
This method returns reference to the thread in which it is called
Ex:
Class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread( );
System.out.println( “current thread: ” + t );
t.setName(“my thread”);
System.out.println( “After name change: ” + t );
try
{ Output
for(int i=5;i>0;i--)
{ Current thread: Thread [main, 5, Main]
System.out.print(i+”\t”);
After name change: Thread[my thread, 5, Main]
t.sleep(1000);
} 5 4 3 2 1
}
catch (interrupted Exception e)
{
System.out.print(“main thread interrupted”);
}
}
84 | Multithreaded Programming And Applets

}
When ‘t’ is used as an argument to println() this display in order: thread name, preoity
and the name of its group. By defult, the name of the main thread is main, default priority
value is five and main is also the name of the group of the threads to which this threads
belongs.
setName( ) & getName( )
We can set the name of the thread using setName( ) method and we can obtain the name
of the thread by calling getName( ) method. These methods are members of the Thread
class and are declared like this
final void setName(String threadName)

final String getName( )

Here thread name specifies the name of the thread.


Life cycle of Thread
During life time of a thread, there are many states it can enter. They include
1. New Born State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
A thread is always in one of these five States. It can move from one state to another via a
variety ways as shown below.
New Thread New Born

start
stop

stop Killed
Active Running Runnable Dead Thread
Thread

yield
stop
suspend resume
sleep notify
wait

Idle Thread Blocked

Newborn State
When we create a thread object the thread is born and is said to be in new born state. In
this state, the thread is not yet schedule for running. At this state we can do only one of
the following things Newborn
State
 Schedule if for running using start( ) method.
 Kill it using stop( ) method.
start stop
If we attempt to use any other method at this stage an Runnable Dead
State State
exception will be thrown
Runnable State
85 | Multithreaded Programming And Applets

The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joint the queue of threads that are
waiting for execution. If all the threads have equal priority then they are given time slots
for execution in round-robin fashion. The thread that relinquishes control joints the queue
at the end sand again waits for its turn. This process of assigning time to thread is known
as time slicing.
However if we want a thread to religious control to another thread to equal priority before
its turn comes, we can do so by using yield method.
yield

Running Runnable Threads


Thread

Running State
Running means that the processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread. A running thread may relinquish its control in one of the following situations.
1. It has been suspended using suspend( ) method. A suspended thread can be received
by using the resume( ) method
suspend

resume

Running Runnable suspended

2. It has been made to steep for a specified time. The thread re-enters the runnable state
as soon as the time period elapsed.
sleep(t)

after(t)

Running Runnable suspended


3. It has been told to wait until some event occurs. This is done using wait( ) method.
The thread can be scheduled to run again using notify( ) method.
wait

notify

Running Runnable suspended

Blocked State
A thread is said to be blocked when it is prevented from entering in to the runnable state
and subsequently the running state. This happens when the thread is sleeping ,suspended
or waiting in order to satisfy certain requirements.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run( ) method. However, a thread can be killed as soon as it is born or while
it is running or even when it is in blocked state thus causing premature death to it.
isAlive( ) & join( )
Two ways exist to determine whether a thread has finished. First isAlive( ) method
defined by Thread class. Its general form is
86 | Multithreaded Programming And Applets

final Boolean isAlive( )

The isAlive( ) method returns true if the thread up on which it is called is still running. It
returns false otherwise. The second way that is more commonly used to wait for a thread
to finish is called join() method. Its general form is

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Additional forms of
join( ) method allow to specify a maximum amount of time that the method want to wait
for the specified thread to terminate
final void join(long Milliseconds) throws InterruptedException.

final void join (long milliseconds, int nanoseconds) throws


InterruptedException.

Class NewThread implements runnable


{
String name;
Thread t;
NewThread(String threadname)
{
name=threadname;
T=new Thread(this, name)
System.out.print(“new thread” + t );
t.start( );
}
public void run( )
{
try
{
for (int i=5;i>0;i--)
{
System.out.print(name + “i” + I );
Thread.sleep(1000);
}
}
catch( InterruptedException e){}
System.out.print(name + “exiting”);
}
}
Class DemoJoin
{
public static void main(String args[])
{
NewThread ob1=new NewThread(“one”);
NewThread ob2=new NewThread(“two”);
NewThread ob3=new NewThread (“three”);
System.out.print(“thread one is alive :” + ob1.t.is
Alive( ) );
System.out.print(“thread two is alive :” +
ob2.t.isAlive( ) );
System.out.print(“thread three is alive :” + ob3.t.isalive( )
);
try
{
ob1.t.join( );
ob2.t.join( );
87 | Multithreaded Programming And Applets

ob3.t.join( );
}
catch (InterruptedException e){}
System.out.print(“thread one is alive :” + ob1.t.is
Alive( ) );
System.out.print(“thread two is alive :” +
ob2.t.isAlive( ) );
System.out.print(“thread three is alive :”+ ob3.t.is Alive( )
);
System.out.print(“main thread exiting”);
}
}

Thread priority
In java each thread is assigned a priority, which affects the order in which it is scheduled
for running. The threads of the same priority are given equal treatment by the java
scheduler and, therefore, they share the processor on a first-come, first-serve basis. Java
permits to set the priority of a thread using .the setPriority( ) method. The general form is
final void setPriority(int level)

Here, level specifies the new priority set in for the calling thread.
The thread class defines several priority constants (final variable)
MIN_PRIORITY=1
MAX_PRIORITY=10
NORM_PRIORITY=5
The level may assume one of these constants or any value between 1 to10. By assigning
priority to threads we can ensure that they are given the attention they deserved.
Whenever multiple threads are ready for execution the java chooses the higher priority
thread and executes it. However, if another thread of higher priority comes along, the
currently running thread will be preempted by the incoming thread thus forcing the
current thread to move the runnable state.The higher priority always preempts any lower
priority thread.
Ex:
class A extends Thread
{
public void run()
{
System.out.prilnt (“Thread A started”)
for (int i=l;i<=4;i++)
{
System.out.print(“\tfrom thread a : I =” + i );
for (int i=1;i<4;i++) System.out.print(“\t from thread A :
I = ”+ i );
System.out.print(“exit from A”);
}
}
}
Class B extends Thread
{
public void run( )
88 | Multithreaded Programming And Applets

{
System.out.print(“thread B started”);
for(int j=1;j<=4;j++) System.out.print(“\t from thread B : j
= ” + j );
System.out.print(“exit from B”);
}
}
Class C extends Thread
{
public void run( )
{
System.out.print(“thread C Start”);
for(int k=1;k=4;k++) System.out.print(“\ t from thread C :
k = ” + k);
System.out.print(“exit from c”);
}
}

Class Thread priority


{
public static void main(String args[])
{
A threadA=new A( );
B threadB=new B( );
C threadC=new C( );
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(4);
threadA.setPriority(Thread.MIN_PRIORITY);
threadA.Start( );
tthread B.Start( );
thread C.Start( );
System.out.print(“exit from main:”);
}
}

getPriority( )
getPriority( ) method of a Thread class can be used to obtain the current priority setting of
a thread. its general form is
final int getPriority( )

Class Clicker implements Runnable


{
int click; Thread t;
private volatile Boolean running;
public Clicker(int p)
{
click=0;
running=true;
t=new Thread(this);
t.setPriority (p);
}
public void run( )
{ while(running)click++; }
public void stop( )
89 | Multithreaded Programming And Applets

{ running=false; }
public void start( )
{ t.start( ); }
}
Class HiPri
{
public static void main(String a[])
{
Thread. currentThread( ).setPriority(10);
Clicker hi=new Clicker(7);
Clicker lo=new Clicker(4);
lo.start( );
hi.start( );
try
{ Thread. sleep(10000); }
catch(Exception e){}
lo.stop( );
hi.stop( );
try
{ hi.join( );
lo.join( );
}
Catch(Exception e){}
System.out.print(“low: ”+ lo.click );
System.out.print(“high : ”+ hi.click );
}
}
Synchronization
When two or more threads need to access to a shared resources, then they may compete
for the same resources and may lead to serious problems. The process which enables to
overcome this problem is known as Synchronization. Synchronization of code can be
done in two ways using synchronized methods or synchronized statements.
Synchronized method
When we declare a method synchronized. Java creates a monitor and hands it over to the
thread that calls the method first time. A monitor is an object that is used as a mutually
exclusive lock or mutex. Only one thread can own a monitor at a given time. While a
thread is inside a synchronized method all the other threads try to call it or any other
synchronized method on the same instance has to wait. To exit the monitor and relinquish
control of the object to the next waiting thread, the owner of the monitor simply returns
from the synchronized method. A synchronized method can be declared as given below.
synchronized void update( )
{
-------
-------
}

Ex
class Example
{
int count;
synchronized void display(String x,int temp)
{
count=temp;
for(int i=1;i<=count;i++)
{
System.out.print( x+" "+count);
90 | Multithreaded Programming And Applets

}
}
}
class Test extends Thread
{
Example e1; String name;
int c;
Test(Example temp, String w, int num)
{
e1=temp; name=w; c=num;
}
public void run( )
{
System.out.print("Entering into " + name );
e1.display(num, e);
System.out.print("Existing from " + name );
}
}
class ExampleSync
{
public static void main(String arg[ ])
{
Example e=new Example( );
Test t1=new Test(e,"t1",10);
t1.start( );
Test t2=new Test(e,"t2",5);
T2.start();
}
}

Synchronized Statement
We can synchronize access to objects of a class, that does not used synchronized
methods, by putting calls to the methods defined by this class inside a synchronized
block. The general form of the synchronized statement is
synchronized(object)
{
--------
-------- // Statements to syncronized//
}
Here, object is a reference to the object being synchronized. A synchronized block
ensures that a call to a method that is a member of object occurs only after the current
thread has successfully enter objects monitor.
Ex:
class Number
{
int a[ ];
Number( )
{
a=new int[20];
}
void even(int x)
{
if( x%2!=0) x++;
for(int i=0;i<=19;i++)
{
a[i]=x; x=x+2;
91 | Multithreaded Programming And Applets

}
}
void odd(int y)
{
if(y%2==0)
y++;
for(int i=0;i<=19;i++)
{
a[i]=y;
y=y+2;
}
}
void display(String s)
{
for(int i=0;i<=19;i++)
System.out.print(s + "->" + a[i] );
}
}
class EvenNumber extends Thread
{
Number n1;
EvenNumber(Number tmp1)
{
n1=tmp1;
}
public void run( )
{
synchronized(x)
{
x.even(20);
x1.display("t1");
}
}
}
class oddNumber extends Thread
{
Number n2;
oddNumber(Number tmp2)
{
n2=tmp2;
}
public void run( )
{
synchronized(n2)
{
n2.odd(t1);
n2.display("t2");
}
}
}
Class Number Sync
{
public static void main(String args[])
{
Number num = new Number();
EvenNumber enum = new EvenNumber(num);
OddNumber onum = new OddNumber(num);
onum.start();
enum.start();
}
92 | Multithreaded Programming And Applets

Deadlock
Deadlock is a special type of error which occurs when two threads have a circular
dependency on a pair of synchronized objects. For example, assume that the thread A
must access method1 before it can release method2, but the thread B cannot release
method1 until it gets hold of method2. Because these are mutually exclusive conditions a
dead lock occurs.
Ex
class A
{
int a1;
A( )
{
a1=30;
}
synchronized int geta( )
{
return a1;
}
synchronized int calculate(B tmp)
{
try
{
Thread sleep(10);
}
catch(Exception e) { }
return(a1 + tmp.getb() );
}
}

class B
{
int b1;
B( )
{
b1=40;
}
synchronized int getb( )
{
return b1;
}
synchronized int calculate(A.tmp)
{
try
{
Thread.sleep(10);
}
catch(Exception e) { }
return(b1- tmp geta( ));
}
}
93 | Multithreaded Programming And Applets

class Add extends Thread


{
A aref; B bref;
Add(A t1,B t2)
{
aref=t1;
bref=t2;
}
public void run( )
{
System.out.print("aref.calculate(bref));
}
}
class Sub extends Thread
{
A aref; B bref;
Sub(A t1,B t2)
{
aref=t1;
bref=t2;
}
public void run( )
{
System.out.print(bref.calculate(aref));
}
}
class DeadLock
{
public static void main(String args[ ])
{
A aobj = new A( );
B bobj = new B( );
Add addobj = new Add(aobj, bobj);
Sub subobj = new Sub(aobj, bobj);
aobj.start( );
subobj.start( );
}
}

wait( ), notify( ), notifyAll( )


The wait(), notify( ), notifyAll( ) methods are implemented as final methods in Object
class, so all classes have them. All these methods can be called only from within a
synchronized method.
wait( )
Tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify.
notify( )
Wakes up the first thread, that called wait( ) on the same object.
notifyAll( )
Wakes up all the threads that called wait( ) on the same object. The highest priority
thread will run first.
final void wait( ) throws InterruptedException( should be used
in try)
94 | Multithreaded Programming And Applets

final void notify( )

final void notifyAll( )

Ex 1 :-
class Q
{
int x;
boolean valueset = false;
synchronized void get( )
{
if( ! valueset )
{
try { wait( ); }
catch(Exception e) { }
}
System.out.print("Got : " + x);
valueset = false;
notify( );
}
synchronized void put(int tmp)
{
if( valueset )
{
try { wait( ) ; }
catch(Exception e) { }
}
x=tmp;
System.out.print(" put : " + x );
valueset = true;
notify( );
}
}
class Producer extends Thread
{
Q q1;
Producer(Q tmp){ q1=tmp; }
public void run( )
{
int i=0;
while(true) { q.put(i++); }
}
}

class Consumer extends Thread


{
Q q1;
Consumer(Q tmp){ q1=tmp; }
public void run( ){ while(true) q1.get( ); }
}
class WaitDemo
{
public static void main(String args[ ])
{
Q x=new Q( );
Producer p=new Producer(x);
Consumer c=new Consumer(x);
p.start( );
c.start( );
95 | Multithreaded Programming And Applets

}
}

Ex 2 :-
class primeNumber
{ int num;
boolean setvalue=false;
synchronized void getnum( )
{
if( ! setvalue )
{
try{wait( ); }
catch(Exception e) { }
}
System.out.print(num);
setvalue=false;
notify( );
}
synchronized void putnum(int x)
{
if(setvalue)
{
try { wait( ); }
catch(Exception e) {}
}
num=x;
setvalue=true;
notify( );
}
}
class Producer extends Thread
{ primeNumber p;
Producer(primeNumber tmp){ p=tmp; }
public void run( )
{
int i=5,j;
p.putnum(2);
p.putnum(3);
while(true)
{
for(j=3;j<=i/2;j=j+2)
{
if( i%j==0) break;
}
if(i==j)p.putnum (i);
i+=2;
}
}
}
class Consumer extends Thread
{
primeNumber p;
Consumer(primNumber tmp){ p=tmp;}
public void run( )
{ while(true) p.getnum( ); }
}
class primeThread
{
public static void main(String args[ ])
{
96 | Multithreaded Programming And Applets

primeNumber x=new primeNumber( );


Producer pr=new producer(x);
pr.start( ); cr.start( );
}
}
suspend( ), resume( )
The suspend( ) and resume( ) methods are defined by the Thread class, to pass and restart
the execution of a thread. They have the following form.
final void suspend( )

final void resume( )

Ex:-
class newThread extends Thread
{
String name;
NewThread(String tmp){ name=tmp; }
public void run( )
{ try
{ for(int i=15;i>0;i--)
{ System.out.println(name+":"+i);
Thread.sleep(200);
}
}
catch(InterruptedException e) {}
System.out.println(name+"Existing");
}
}
class suspendResume
{ public static void main(String args[ ])
{ NewThread ob1=new NewThread("one");
NewThread ob2=new NewThread("two");
ob.start( );
ob2.start( );
try
{ Thread.sleep(1000);
ob1.suspend( ); System.out.println("Suspending one");
Thread.sleep(1000);
ob1.resume( ); System.out.println("Resuming one");
ob2.suspend( ); System.out.println("Suspending two");
Thread.sleep(1000);
ob2.resume( ); System.out.println("Resuming two");
ob1.join( );
ob2.join( );
}
catch(Interrupted Exception e) { }
System.out.println("Main Thread Existing");
}
}

Managing Errors and Exceptions


It is common to make mistakes while developing as well as typing a program. A mistake
might lead to an error causing to program to produce unexpected result. Errors are the
wrongs that can make a program go wrong. An error may produce an incorrect output or
97 | Multithreaded Programming And Applets

may terminate the execution of the program abruptly or even may cause the system to
crash. Errors may be classified broadly in two types.
1. Compile time errors.
2. Run time errors.
Compile time Errors
Syntax errors will be detected and displayed by the java compiler and therefore these
errors are known as compile time errors. Whenever the compiler displays the errors it
will not create .class file. It is therefore necessary that we fix all the errors before we can
successfully compiled and run the program. Most of the compile time errors are due to
typing mistakes. The most common problems are
 Missing semicolons
 Missing (miss match of) brackets in class and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
 Incompatible types in assignments / initialization.
 Bad references to objects.
 Use of = in place of ==
Typographical errors are hard to find. We may have to check the code word by word
even characters by characters.
Run time errors
Sometimes a program may compiles successfully creating the class file but may not run
properly. Such programs may produce wrong result due to wrong logic or may terminate.
Most common runtime errors are
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into an array of an in compatible class or type.
 Trying to cast an instance of a class to one of its subclass.
 Passing parameters that is not in a valid range or value for a method.
 Trying to illegally change the state of a thread.
 Attempting to use a negative size for an array.
 Using null object references to access a method or variable.
 Converting invalid string to a number.
 Accessing a character that is out of bounds of a string.
When such errors are encountered java typically generates an error message and aborts
the program.
Exceptions
An exception is a condition that is caused by a run time error in a program. When the
java interpreter encounters an error such as dividing an integer by zero it creates an
exception object and throws it. If the exception objects is not catch and handled properly
the interpreter will display an error message and will terminate the program. If we want
the program to continue with the execution of the remaining code, then we should try to
catch the exception object thrown by the error condition and then display an appropriate
message for taking corrective actions. This task is known as exception handling. The
mechanisms suggest incorporation of a separate error handling code that performs the
following tasks.
1. Find the problems ( Hit the exception )
98 | Multithreaded Programming And Applets

2. Inform the error has occurred.( throw the exception )


3. Receive the error information.( catch the exception )
4. Take corrective actions.( handle the exception )
Some common exceptions are
Exception Type Cause Of Exception
ArithmeticException Caused by math errors such as division by zero.
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the wrong
type of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file.
IOException Caused by general I/O failures
NullPointerException Caused by referencing a null object.
NumberFormatException Caused when a conversion between strings and
numbers fails.
OutOfMemoryException Caused when there is no enough memory to
allocate a new object.
SecurityException Caused when an applet tries to perform an action
not allowed by the browser security settings.
StackOverFlowException Caused when system runs out of stack space.
StringIndexOutOfBoundException Caused when program attempts to access
nonexistent character position in a string.

Syntax Of Exception Handling Code

try block
Throws Statement that causes Exception
Exception the exception object creator
Object

catch block
Statements that Exception
handles the exception. handler

Java uses a key word “try” to preface a block of code that is likely to cause an error
condition and throw an exception. A catch block defines by the keyword “catch” catches
the exception thrown by the try block and handles it appropriately. The catch block is
immediately added after the try block

………
……..
try
{
99 | Multithreaded Programming And Applets

Statement;
}
catch (exception type e)
{
Statement;
}
………..
……….
The try block can have one are more statements that could generate an exception. If
anyone statement generates an exception the remaining statements in the block are
skipped and execution jumps to the catch block that is placed next to the try block.
The catch block can have one are more statements that are necessary to process the
exception. The catch statement is passed a signal parameter, which is reference to the
exception object thrown. If the catch parameter matches, then the exception is caught and
statement in catch block will be executed. Otherwise the default exception handler will
caused the execution to terminate.
Ex: 1
class Errors
{
public static void main ( String args[ ])
{
int a=10,b=5,c=5,x,y;
try
{ x=a/(b-c); }
catch( ArithmeticException e)
{ System.out.println(“ Divided by zero “); }
y=a(b+c);
System.out.println(“y = ” + y);
}
}

Ex:2
Class ClineInput
{
public static void main ( String args [ ])
{
int invalid=0,number,count=0;
for(int i=0; i<args.length; i++)
{
try
{ number=Integer.parseInt(args[i]) }
catch (NumberFormatException e)
{
invalid++;
System.out.println (“Invalid number = ”+ args[i]);
continue;
}
count++;
}
System.out.println (“valid numbers = ” + count);
System.out.println (“Invalid numbers = ” + invalid);
}
}

Multiple Catch Statements


100 | Multithreaded Programming And Applets

In some cases, more than one exception could be raised by a single price of code. To
handle it, it is possible to specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown each catch statement is inspected in
order, and first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continuous after the try/catch
block.
Ex:
class MultiCatch
{
public static void main(String x[])
{
try
{
int a = x.length;
System.out.println(“a=”+a);
int b=42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(“divided by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“array out of bound exception”);
}
System.out.println(“after try/catch block”);
}
}

Finally statement
Finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. The finally block will execute whether
or not an exception is thrown. If an exception is thrown, the finally block will execute
even if no catch statement matches the exception. Any time a method is about to return to
the caller from inside a try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the method returns. The finally
clause is optional. However, each try statement requires at least one catch or a finally
clause.
Ex:
Class FinallyDemo
{
static void procA()
{ int i;
try
{ i=20/(35-35); }
finally
{ System.out.println(“proc A finally”); }
}
static void procB()
{ try
{ System.out.println(“inside proc B”);
return;
}
finally
{ System.out.println(“proc B finally”)}
101 | Multithreaded Programming And Applets

static void procC()


{
try
{ int i=20/(35-35); }
catch(ArithmeticException e)
{ return; }
finally
{ System.out.println(“proc C finally”); }
}
public static void main(String x[])
{
try
{ procA(); }
catch(ArithmeticException e)
{ System.out.println(“exception caught”); }
procB();
procC();
}
}

Throw Statement
The exceptions are thrown by the java run time system automatically, whenever an error
occurrence. But it is also possible to throw an exception explicitly, using the throw
statement. The general form of throw is
throw ThrowableInstance;

Here ThrowableInstance must be an object of type Throwable or a subclass of


Throwable. Simple types such that int, char, as well as non-Throwable classes such as
String and Objects cannot be used as exceptions. There are two ways we can obtain a
Throwable object : Using a parameter in a catch clause, or creating one with new
operator. The flow of execution stops immediately after the throw statement; any
subsequence statement are not executed.
Ex:
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException(“Demo”);
}
catch(NullPointerException e)
{
System.out.println(“caught inside demoproc”);
throw e;
}
}
public static void main(String x[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println(recaught”+e);
102 | Multithreaded Programming And Applets

}
}
}

Here new is used to construct an instance of NullPointerException. All java’s built-in-


run-time exceptions have two constructors: one with no parameters and one that takes a
string parameter. This string is displayed when the object is used in print( ) or println( )
methods. It can also obtained by a call to getMessage( ) which is defined by a Throwable
class.
throws Statement:
If a method is capable of causing an exception that it does not handle, it must specify this
behaviour so that the callers of the method can guard themselves against that exception. It
can be done by including a throws clause in the method’s declaration. A throws clause
lists the type of the exception that method might throw. This is necessary for all
exceptions except those of type Error or RuntimeException, or any of their subclasses.
The general from of a method declaration that includes a throws clause is
type method_name(parameter list) throws exception-list

\\body of the method

Here exception-list is comma separated list of the exception that a method can throw
Ex:
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println(“inside throw one”);
throw new IllegalAccessException(“demo”);
}
public static void main(String x[])
{
try
{
throwOne();
}
catch(IllegalAccessException e)
{
System.out.println(“caught” + e);
}
}
}

Throwing own exceptions or creating own exceptions


In java it is possible to create our own exception types by defining user defined class as a
subclass of Exception class. The objects of that user defined class can be thrown using
the keyword throw. An object of a class that extends Exception can be thrown and
caught.
Ex:
class MyException extends Exception
{
MyException(String massage)
103 | Multithreaded Programming And Applets

{
super(message);
}
}

class TestMyException
{
public static void main(String x[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01) throw new MyException(“demo”);
}
catch(MyException e)
{
Sytem.out.println(“caught my exception”);
System.out.println(e.getMessage());
}
finally
{
System.out.println(“I am always here”);
}
}
}

Uses of exceptions:
Exception handling provides a powerful mechanism for controlling complex programs
that have many run time characteristics. It provides a clean way to handle errors and
unusual boundary conditions in the programs logic. Exception handling mechanism may
be effectively used to locate the type and place of errors.

APPLET PROGRAMMING
Applet are small java programs that are primarily used in internet computing. They can
be transported over the internet and run using the applet viewer or any web browser that
supports java. An applet can perform arithmetic operations, display graphics, play
sounds, accept user input, create animations and play interactive games. Applet enable
internet users to create and use fully interactive multimedia web documents. Java applets
therefore have begun to make a significant impact on the World Wide Web (www).
An applet developed locally and stored in a local system is known as local applet. When
web page is trying to find a local applet it does not need to use the internet. It simply
searches the directories in the local system and loads. A remote applet is that which is
developed by someone else and stored on a remote computer connected to the internet. If
the system is connected to the internet we can download and run the applet via internet.
Difference Between Applets And Applications
Both Applets and stand-alone applications are java programs but there are significant
difference between them. Applets are not full featured application programs. They are
usually written to accomplish a small task. Applets impose certain limitations and
restrictions in their design.
 Applets do not use the main( ) method for initiating the execution.
104 | Multithreaded Programming And Applets

 Applets cannot be run independently. They are run from inside a web page using
a HTML tag.
 Applets cannot read form or right to the files in the local computer.
 Applets cannot communicate with other servers on the net work.
 Applets cannot run any program from the local computer.
 Applets are restricted from using liberations from other languages such as c & c+
+.
Uses of applets
 When we need something dynamic to be included in the display of a web page.
For example an applet that displays daily sensitivity index on a web page that lists
share prices or an applet that displays a bar chart would add value to a page that
contains a database.
 When we require some flash outputs. For example, applets that produce sounds,
animations or some special effects.
 When we want to create a program and make it an available on the internet.
Creating Applet
The steps involved in developing and testing in applet are
1. Building an applet code (.java).
2. Create an executable applet (.class file).
3. Designing a web page using HTML tags.
4. Preparing <APPLET> tag
5. Incorporating <APPLET> tag into the web page
6. Testing an applet code.
Ex:
import java.awt.*;
import java.applet.*;
public class Test extends Applet
{
void paint(Graphics g)
{
g.drawString(“hello”,10,20);
}
}

<HTML>
<HEAD.
<TITLE>My First Applet </TITLE>
</HEAD>
<BODY>
<APPLET code=”Test” width=20 height=100>
</APPLET>
</BODY>
</HTML>

Building applet code


The applet code uses two classes, namely Applet, Graphics. The applet class which is
contained in the java.applet package provides life to the applet through its method such as
init(), paint() & start(). When applet is loaded java automatically calls a series of applet
class methods for starting, running and stopping the applet code. The paint() method of
the applet class displays the result of the applet code on the screen. The output may be
text, graphics or sound. The general form of applet code is
import java.awt.*;
105 | Multithreaded Programming And Applets

import java.applet.*;
public static appletname extends Applet
{
public void paint(Graphics g)
{
----------
---------
}
}
Applet Life Cycle
Every java applet inherits a set of default behaviours from the Applet class. As a result
when an applet is loaded it undergoes a series of changes in its state as shown below.

Born
Begin Initialization
(Load Applet)

start( )
stop( )

Running Idle
Display Stopped

start( )
paint( ) ) destroy( )

Dead
Destroyed End

The applet states include


1. Born on initialization state
2. Running state
3. Idle state
4. Dead or Destroyed state.
Initialization state (init() method)
Applet enters in the initialization state when it is first loaded. This is achieved by calling
the init() of Applet class. The initialization occurs only once in the applets life cycle.
Usually init() method override to provide any of the following behaviours to all applet.
 Create objects needed by the applet.
 Setup initial values
 Load images and fonts
 Setup colours
The general form of init() method is
public void init()
{
----
----
}
Running state (start()):
106 | Multithreaded Programming And Applets

Applets enters the running state when system calls the start() method. This occurs
automatically after the applet initialized. It is also called to restart an applet after it has
been stopped. We may override the start() method to create a thread that control the
applet.
The general form of the start() is
public void start()
{ ----
----
----
}
Idle State(stop()):
An applet becomes idle when it is stopped from running. Stopping occurs automatically
when leave the page containing the currently running applet. We can also explicitly call
the stop() method. Usually it is override to suspend threads that do not need to run when
the applet is not a visible. General form of stop() method is
public void stop()
{
-----
-----
-----
}
Dead state (destroy()):
An applet is said to be dead when it is removed from the memory. This occur
automatically by invoking the destroy() method when we quit the browser. This stage
occurs only once. We may override this method to clean up the resources and to kill the
threads. General form of destroy() is
public void destroy()
{
---
---
---
}
Display state(paint()):
Applet moves to display state whenever it has to perform some output operations on the
screen. This happens immediately after applet enters into the running state. The paint()
method is called to accomplish the task. We may override this method to display
anything on the screen. The general form is
public void paint(Graphics g)
{
---
---
---
}

Creating An Executable Applet:


Executable applet is nothing but the .class file of the applet which is obtained by
compiling the source code of the apple. Compiling an applet is exactly the same as
compiling an application. We can use java compiler top compile the applet.
Designing A Web Page
107 | Multithreaded Programming And Applets

In order to run a java applet it is necessary to have a web page that references the applet.
A web page is made up of text and HTML tags that can be interpreted by a web browser
or an applet viewer. Web pages are stored using a file extension .html. HTML files
should be stored in same directory as the compiled code of applets.
Adding Applet To HTM File:
Insert the applet tag (<APPLET>) in the page at the place where the output of the applet
must appear. The <APPLET> tag supplies the name of the applet to be loaded and tells
the browser how much space the applet required. The starting and ending tags of an
applet are <APPLET> and </APPLET>. The applet tag specifies 3 things.
 Name of the applet
 Width of the applet(in pixels)
 Height of the applet(in pixels)
Ex:
<applet code=”hello” width=200 height=100>
</applet>
Running The Applet:
To run an applet we require one of the following files.
 Java enabled web browser (such has HotJava & Netscape)
 Java applet viewer
If we use a java enabled web browser we will able to see the entire web page containing
the applet. If we use the applet viewer we will see only the applet output.
Ex: Applet viewer example.html
Note that the arguments of applet viewer is not the java file or .class file but rather .html
file.
Web Page Sections:
A webpage is made up of text and HTML tags that can be interpreted by a web browser.
A webpage is also known as HTML page or HTML document. A webpage can be
prepared using any ASCII text editor. A webpage is marked by an opening html
tag(<HTML>) and closing (</HTML>) and is divided into the following 3 major
sections.

<HTML>

<!--
…………………………. Comment
………………………….. Section
-->

<HEAD>
Head
Title Tag Section
</HEAD>
</HTML>

<BODY>
Body
Applet Tag
Section
</BODY>
108 | Multithreaded Programming And Applets

Comment Section
This section contains comments about the page. A comment line begins with <!--- and
with a -->. Web browser will ignore the text enclosed between them. The comments are
optional and can be included anywhere in the webpage.
Head Section
The head section is defined with a starting <HEAD> and closing </HEAD>. This section
usually contains a title for the web page as shown a below.
<HEAD>
<TITLE> welcome</TITLE>
</HEAD>
The text enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the
browser when it displays the page. The head section is also optional.
Body section
After the head section comes the body section. This section contains the entire
information about the page and its behaviour. In this section we can set up many tags to
indicate how our page must appear on the screen
<body>
<center>
<h1>welcome</h1>
</center>
</body>

Applet tag
The syntax of the applet tag in full form is as shown below.
<APPLET [codebase=codebase_url] code =applet
filename.class [alt=alternative text]

[name=applet_instance name] width=pixels


height=pixels [align=alignment]

[vspace=pixels] [hspace=pixels] >

[<param name=name1 value=value1>]

[<param name=name2 value=value2>]

</APPLET>

The attributes inside[ ] are optional and minimum required attributes are code, width and
height.
Attribute Meaning
code=AppletFilename.class specifies the name of the applet class to be loaded
specifies the url of the directory in which the applet
codebase = codebase_url
reside
109 | Multithreaded Programming And Applets

width=pixels specifies the width & height of the html page that will be
height=pixels reserved for the applet
it assigns a name to the applet so other applets on the
name= applet_instance_ name
same page may be refer this applet
it specifies where on the page the applet will appear
align=alignment possible values are top, bottom, left, right, middle,
absmiddle, absbottom, texttop and baseline.
hspace=pixels it specifies the horizontal blank space around the applet
vspace=pixels it specifies the vertical blank space around the applet.
non java browser will display this text where the applet
alt=alternative_text
would normally go.

Passing Parameters to the Applet


We can supply user defined parameters to an applet using the <PARAM>. Each
<PARAM> tag has name attribute and a value attribute. Inside the applet code, the applet
can refer to that parameters by names to find its values
EX:
<APPLET ………….. >
<PARAM NAME=COLOR VALUE=RED >
</APPLET>
Parameters are passed on an applet when it is loaded .We can define init() in the applet to
get hold of these parameters in the <PARAM>.This is done using getParameter(), which
takes one string argument representing the name of the parameter and returns a string
containing the value of that parameter.
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{
String str;
public void init()
{
str = getParameter(“string”);
if ( str == null) str =”Java”;
str = ”Hello”+str;
}
public void paint(Graphics g)
{
g.drawString(str,10,10);
}
}

Below html fill passes a parameter whose name is string and whose value is college to the
applet HelloJavaParam.
<HTML>
<HEAD>
<TITLE>Welcome </TITLE>
</HEAD>
<BODY>
<APPLET CODE = “HelloJavaParam” WIDTH=100
HEIGHT=200>
110 | Multithreaded Programming And Applets

<PARAM NAME = “String “ VALUE = “college”>


</APPLET>
</BODY>
</HTML>

HTML Tags
HTML supports large number of tags that can be used to control the style and format of
the display of the WebPages .Some important HTML tags and their functions are
Tags function
<HTML> ----- </HTML> Specifies the beginning and end of the HTML file.
<HEAD> ------ </HEAD> This tag may include details of Page. Usually
contains. <TITLE> tag within it
<TITLE> ------- </TITLE> Text contained in it will appear in the title bar.
<BODY> ------- </BODY> This tag contains the main text. It is the place where
<APPLET> tagis declared
<H1> ----- </H1> Used to display the various size headings H1
creates large heading and H6 creates smaller.
<H6> ---- </H6>
<CENTER> --- </CENTER> Place the text contained in it At the centre of the page
<APPLET> ------- </APPLET> Declares the Applet details.
<PARAM------> Supplies user defined Parameters to applet.
<B> --------- </B> Text this will be displayed Bold.
<BR> Line breaks tag.
<P> --------- </P> Paragraph tag.
<IMG-----> Used to insert images in the Page.
<HR> Draws a horizontal line
<A---> ----- </A> Used to add hyperlinks.
<FONT-----> --- </FONT> Using colour and size attributes of font tag, we Can
change the colour and size of the text
<!-- Used to add comments.

Display Numerical Values


In the applets we can display numerical values by first converting them into strings and
then using the drawString() method of the Graphics class. Numerical values can be
converted as string using valueOf() of string class
import java.awt.*;
import java.applet.*;
public class NumDisplay extends Applet
{
public void paint(Graphics g)
{
int num1=10,num2=20;
int sum=num1+num2;
String s= “sum:”+String.valueOf(sum);
g.drawString(s,10,10);
}
}
111 | Multithreaded Programming And Applets

Corresponding HTML file is


<HTML>
<HEAD>
<TITLE>SUM</TITLE>
</HEAD>
<BODY>
<APPLET CODE=”NumDisplay:” WIDTH=100 HEIGHT=200>
</APPLET>
</BODY>
</HTML>

Getting input from the user


Applets work in a graphical environment. Therefore, applets treat input as text strings. we
must first create an area of the serene in which user can type and edit input items. we can
do this by using the TextField class of the applet package. Once text fields are created for
receiving input, we can type values in the fields and edit them if necessary. As the text
fields contain items in a string form they need to be converted before they are used in
any computations. The results are then converted back to strings for display

Ex
import java .awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1,text2;
public void init()
{
text1= new TextField(8);
text2 = new TextField(8);
add(text1);
add(text2);
text1.setText(“0”);
text2.setText(“0”);
}
public void paint(Graphics g)
{
int x =0,y=0,z=0;
String s1,s2;
g.drawString(“Input a number in each box “,10,50);
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception e){}
b=x+y;
g.drawString(String.valueaOf(b),100,75);
}
public boolean action(Event event, Object obj)
{
repaint();
return true;
}
}
112 | Multithreaded Programming And Applets

Applet Display Methods


drawString():
drawstring() is used to output a string to an applet. It is a memmber of Graphics class.
Typically it is called from within the update() or paint(). It has the following general form
void drawstring(String m,int x,int y)

Here m is the stirng to be output beginning at x, y


setBackground(), setForeground():
To set the background color of an applet window use setBackground(). To set the
foreground colour use setForeground().These methods are defined by Component class.
They have the following general form.
void setBackground(Color newcolor)

void setForeground(Color newcolor)

AWT colour system allows us to specify any colour you want. Color class defines several
constants to specify a number of common colours. You can also create new colours using
the Color class constructor. It has this general form
Color( int, int, int)

getColor() and setColor()


By default graphic objects are drawn in the current foreground colour .We can change
this colour by calling the Graphics method setColor(). Its general form is
void setColor(Color newcolour)

We can also obtain the current colour by calling getColor(). Its general form is
Color getColor()

repaint()
repaint() is defined in Component class. It causes the awt runtime system to execute a call
to the applet update() method which in its default implementation calls paint(). The
repaint has four forms.
void repaint()

This causes the entire window to be repainted.


void repaint(int left, int top, int width, int height)

Its specifies a reason that will be repainted


void repaint (long maxdelay);

void repaint(long maxdelay, int left, int top, int width, int
height)

import java.awt.*;
import java.applet.*;
public class Banner extends Applet implements Runnable
{
String msg=”All glitters are not gold” ;
Thread t= null;
boolean stopflag;
public void init()
{
setBackground(Color.cyan);
113 | Multithreaded Programming And Applets

setForeground(Color.red);
stopflag=false;
}
public void start()
{
t= new Thread(this);
t.start();
}
public void run()
{
char ch;
for(; ;)
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg = msg.subString(1,msg.length());
msg+=ch;
if(stopflag)break;
}
catch(InterruptedException e){}
}
}

public void stop()


{
stopflag=true;
t= null;
}
public void paint(Graphics g)
{
g.drawString(msg,50,30);
}
}

<HTML>
<HEAD>
<TITLE>Banner</TITLE>
</HEAD>
<BODY>
<H1>Scrolling Banner</H1>
<APPLET CODE= “Banner” WIDTH=500 HEIGHT=200)
</APPLET>
</BODY>
</HTML>

Event Handling
The Delegation Event Model
The modern approach to handling events is based on the delegation event model. Its
concept is a source generates an event and sends in to one or more listeners. In this
scheme, the listeners simply waits until it receives an event. Once receivd, the listener
process the event and then returns. In this model listeners must register with a source in
order to receive on event notification.
Events
114 | Multithreaded Programming And Applets

The delegation model an event is an object that describes a state change in a source. It
can be generated as a consequence of a person interacting with the elements in a GUI.
Some of the activities that cause events to be generated are pressing a button, entering a
character via keyboard, selecting an item in a list and clicking the mouse.
Event Sources
A source is an object that generate an event. This occurs when the internal state of that
object changes in same way. Sources may generate more than one type of event. A source
must register listeners in order for the listeners to receive notifications about a specific
type of event. Each type of event as its own registration method . The general form is
public void addTypeListener(TypeListener el)

Here, type is the name of the event and ‘el’ is a reference to the event listener. When an
event occurs all registered listeners are notified and receive a copy of the event object.
Some Sources may allow only one listener to register. The general form such a method is
public void addTypeListener(TypeListener el)

throws
java.until.TooManyListeners Exception

A source also provides a method that allows listeners to unregister. The general form of
such method is
public void removeTypeListener(TypeListener el)

Event Listeners
A listener is an object that is notified when an event occurs. A listener must have been
register with one or more sources to receive notifications about specific type of events
and it must implement to receive and process these notifications. The methods that
receive and process events are defined in a set of interfaces in java.awt.event. Hence, a
listener must implement an appropriate interface.
Event Classes
At the root of the java event class hierarchy is Event Object, which is in java.util. It is a
super class for all events. It consist two methods
getSource()
toString()
The getSource() returns the source of the event. Its general form is
Object getSource()

The class AWTEvent, defined with in a java.awt package, is a subclass of EventObject. It


is the super class of all AWT-based events. Its getId() can be used to determine the type
of event. Its general form is
int getId().

The several types of events that are generated by various user interface elements are
Event class Description
Generated by when a button is pressed, a list item is double clicked
ActionEvent
or menu item is selected.
AdjustmentEvent Generated when a scrollbar is manipulated
115 | Multithreaded Programming And Applets

Generated when a component is moved, hidden, resized or becomes


ComponentEvent
visible.
ContainerEvent Generated when a component is added or removed from a container.
FocusEvent Generated when a component gains or losses keyboard focus.
ItemEvent Generated when checkbox or list item is clicked.
KeyEvent Generated when input is received from the keyboard.
Generated when the mouse is dragged, moved, clicked, pressed,
MouseEvent released Also generated when the mouse enters are exits a
component.
TextEvent Generated when the value of the text area or text field is changed.
Generated when a window is activated, closed, deactivated ,
WindowEvent
deiconified, iconified , opened or quit.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseMotions extends Applet implements
MouseMotionListener
{
String msg=”*”;
int mousex=0,mousey=0;
public void init()
{
add mouseMotionListener(this);
}
public void MouseDragged(MouseEvent me)
{
mousex = me.getX();
mousey =me.getY();
showStatus(“Dragging Mouse
At :”+mousex+”,”+mousey);
repaint();
}
public void mouseMoved ( MouseEvent me)
{
showStatus(“ Mouse Moving At: “ +me.getX() ”,”);
me.getY ();
}
public void paint(Graphics g)
{
g.drawString(msg, mousex, mousey )
}
116 | Multithreaded Programming And Applets

You might also like