JAVA NOTES
JAVA NOTES
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
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
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
HTML ByteCode
Java web browser document
Applet Tag
request HTML document
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).
Documentation Section
8 | Java Fundamentals
Package Statement
Import Statements
Interface Statements
Class Definitions
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
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.
These specify how and when looping will take place. There are three
Iteration statement types of iteration statements:
Guarding statements are used for safe handling of code that may
Guarding statement cause exceptions. These statements use the keywords try, catch, and
finally
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
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
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
floating-
Integer Character Boolean
point
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;
E.g.,
initialvalue = 0;
finalvalue = 100;
yes = ‘x’;
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
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
}
}
Exercise
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
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
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
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
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;
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.
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(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 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.
..............................
default :
default Block;
break;
}
Statement – x;
Test
Expression
False
Body of the loop
True Test
Expression
True
Body of the loop
False
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
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 1 2 3 5 8 13 21
{
Body of the loop
}
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++)
{
……………….
……………….
}
}
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
………….
………….
}
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 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;
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
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
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;
}
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);
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
A A B
B
C
A
A
B
B C D
C
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
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.
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);
}
}
Multilevel Inheritance:-
The procedure of deriving a class from another derived class is named as multilevel
inheritance.
50 | Java Fundamentals
A 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() );
}
}
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
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
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 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
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};
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();
}
}
}
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( )
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
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);
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);
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()
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();
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)
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)
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)
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(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)
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);
}
}
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)
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;
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 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 ;
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;
{
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;
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
The below table shows the classes that belong to each package
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
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(int i=1;i<=30,i++)
System.out.println (“= “);
System.out.println (“ “);
}
}
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)
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
switching switching
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
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( );
}
}
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)
start
stop
stop Killed
Active Running Runnable Dead Thread
Thread
yield
stop
suspend resume
sleep notify
wait
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 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
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)
notify
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
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
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.
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”);
}
}
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( )
{ 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
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++); }
}
}
}
}
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
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");
}
}
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
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);
}
}
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
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 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);
}
}
}
{
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>
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
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)
{
---
---
---
}
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]
</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.
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
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.
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
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)
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()
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){}
}
}
<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 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
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