Bca 3rd Java
Bca 3rd Java
Software: is a set of instructions, data or programs used to operate computers and execute
specific tasks.
Programming Languages: The languages that are used to write a program or set of instructions
are called "Programming languages".
Definition OOP stands for Object POP stands for Procedural Oriented
1
Oriented Programming. Programming.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 1
Java Programming
It emphasizes the concept of objects, which are instances of classes and encapsulate both
data (attributes) and behavior (methods).
OOP allows us to decompose a problem into a number of entities called Objects and then
build data functions (known as methods in java) around these entities.
Method Method
Data
Method Method
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 2
Java Programming
Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology to design a program using classes and objects.
1. Object: Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
“The instances (properties) of class is called object”
3. Data Abstraction: The act of representing essential features without including any
background details.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 3
Java Programming
4. Data encapsulation: Data encapsulation (Data Hiding) combines data and functions into a
single unit called class. Data encapsulation will prevent direct access to data. The data can be
accessed only through methods present inside the class.
Example-1: The real-world examples of encapsulation is Capsule.
Example-2: Another real-world example of encapsulation can be your school or office bag.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 4
Java Programming
The ability of an operator and function to take multiple forms is known as Polymorphism. i.e.
Function overloading and Operator Overloading
Example: Suppose you want to save two numbers for one person. You must have a function,
which will take the two numbers and the person’s name is same.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 5
Java Programming
Benefits of OOP
OOPs offers several benefits to both the program designer and the user.
Application of OOP
The areas for application of OOP include:
Real-time systems
Simulation and modeling
Object-oriented databases
Hypertext, hypermedia and expertext
AI and expert system
Neural networks and office automation systems
CIM/CAD/CAM systems
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 6
Java Programming
As we know that all programming language compilers convert the source code to machine code.
Same job done by Java Compiler to run a Java program, but the difference is that Java compiler
converts the source code into Intermediate code is called as bytecode. This machine is called the
Java Virtual machine and it exits only inside the computer memory.
Following figure shows the process of compilation.
In below figure illustrates how java works on a typical computer. The java object frame work
(java API) acts as an intermediary between the user programs and the virtual machine which in
turns acts as the intermediary between the operating system and the java object frame work.
Real machine
Operating system
Java virtual machine
user
Fig: Layers of Interaction for Java Programs
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 7
Java Programming
JAVA FUNDAMENTALS
JAVA HISTORY:
• Java was invented for the development of software for consumer electronic devices like
tvs, toasters, etc. The main aim had to make java simple, portable and reliable
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 8
Java Programming
FEATURES OF JAVA
3. Object- oriented
Java is truly object-oriented language.
In java, almost everything is an object.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 9
Java Programming
Security is an important feature of java and this is the strong reason that programmer use
this language for programming on internet.
5. Distributed
Java is called as distributed language for construct applications on networks which can
contribute both data and programs.
Java applications can open and access remote objects on internet easily. That means
multiple programmers at multiple remote locations to work together on single task.
8. High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of
intermediate byte code.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 10
Java Programming
Java architecture is also designed to reduce overheads during runtime. The incorporation of
multithreading improves the execution speed of program.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 11
Java Programming
Java Environment
Java environment includes a large number of development tools and hundreds of classes and
methods. The development tools are the part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java standard Library (JSL), also called as the
Application Program Interface (AIP).
The Java Development Kit comes with a collection of tools that are used for developing and
naming Java programs. They include:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 12
Java Programming
appletviewer Enables us to run java applets (without actually using a Java-compatible browser).
java Java Interpreter, which runs applets and applications by reading and interpreting
bytecode files.
javac The java compiler, which translates java source code to bytecode files that the
interpreter can understand.
javap Java disassembler, which enables us to convert bytecode files into a program
description
Utility packages: A collection of classes to provide utility functions such as date and time
functions.
Networking packages: A collection of classes for communicating with other computers via
internet.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 13
Java Programming
AWT package: The Abstract Window Tool Kit package contains classes that implements
platform-independent graphical user interface.
Applet package: This includes a set of classes that allows us to create Java applets.
Java is a general purpose, object-oriented programming language. We can develop two types of
java programs:
Stand-alone applications
Web applets
Stand-alone applications are programs written in java programs to carry out certain tasks on a
stand-alone local computer.
Applets are the small java programs developed for internet applications. An applet located an
distant computer (server) can be downloaded via internet and executed on a local computer
(client) using java-enabled browser.
Stand-alone programs can read and write files and perform certain operations that applets cannot
do. An applet can only run within a web browser.
Java
Source
code
Java Compiler
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 14
Java Programming
Output Output
class FirstProgram
{
public static void main(String args[ ])
{
System.out.println (“This is my first program”);
}
}
Class declaration:
The first line
class FirstProgram
declares a class, which is an object-oriented construct.
The file must be named “FirstProgram.java” to equivalent the class name containing the
main method.
Java is case sensitive. This program defines a class called “FirstProgram”.
A class is an object-oriented term. It is designed to perform a specific task. A Java class
is defined by its class name, an open curly brace, a list of methods and fields, and a close
curly brace.
The name of the class is made of alphabetical characters and digits without spaces; the
first character must be alphabetical.
Opening Brace:
Every class definition in java begins with an opening brace “{“ and ends with a matching closing
brace “}”.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 15
Java Programming
defines a method named main. Every java application program must include the main( ) method.
This is the starting point for the interpreter to begin the execution of the program.
A java application program can have any number of classes but only one of them must include
main method to initiate the execution.
This line contains the number of keywords: public, static and void.
public: The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
static: Next appears the keyword static, which declares this method as one that belongs
to the entire class and not a part of any objects of the class. The main must always be
declared as static since the interpreter uses this method before any objects are created.
void: The type modifier void states that the main method does not return any value .
All parameters to a method are declared inside a pair of parentheses. Here, Strings args[ ]
declares parameter named args, which contains an array of objects of the class type Stirng.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 16
Java Programming
A java program may contain many classes of which only one class defines a main method.
Classes contain data members and methods that operate on the data members of the class.
Methods may contain data type declarations and executable statements. To write a java program,
we first define classes and then put them together.
Documentation Section:
The documentation section comprises a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to refer to at a late stage. Comments
must explain why and what of classes and how of algorithms. In additions to the two styles of
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 17
Java Programming
comments, java also uses a third style of comment /**……*/ known as documentation
comment. This form of comment is used for generating documentation automatically.
Package statement
The first statement allowed in a java file is package statement. This statement declares a
package name and informs the compiler that the classes defined here belong to this package.
Import statements
The next thing after a package statement may be a number of import statements. This is similar
to the #include statement in c.
This statement instructs the interpreter to load the test class contained in the package student.
Using import statements, we can have accesses that are part of other named packages.
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 feature in the
program.
Class definitions
A java program may contain multiple class definitions. Classes are the primary and essential
elements of a java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 18
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 19
Java Programming
Syntax:
C:\javac filename.java
To compile the program, we must run the java compiler javac, with the name of the source file
on the command line as shown below:
javac Test.java
JAVA TOKENS
A java program basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements.
“The smallest individual units in a program are known as tokens. A java program is a collection
of tokens, comments and white spaces”.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 20
Java Programming
Literals
Operators
Separators
The Unicode is a 16-bit character coding system and currently supports more than 34000 defined
characters. However, most of us use only the basic ASCII characters which include letters, digits
and punctuation marks, used in normal English.
Keywords
Java language has reserved 50 words as keywords.
These keywords, combined with operators and separators according to syntax, from the
definition of the java language.
Since keywords have specific meaning in java, we cannot use them as names for variable,
classes, methods and so on.
All keywords are to be written in lower-case letters.
Since java is case-sensitive one can use these words as identifiers by changing one or
more letters to uppercase.
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 rule:
They can have alphabets, digits, and the underscore and dollar sign characters.
They must not begin with a digit.
Uppercase and lowercase letters are distinct
They can be of any length
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 21
Java Programming
Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be
descriptive and easily read. Java developers have followed some naming conventions.
Names of all public methods and instances variables start with a leading lowercase letter.
Ex: average, sum
When more than one words used in a name, the second and subsequent words are marked
with a leading uppercase letters. Ex: dayTemperature
totalMarks
All private and local variables use only lowercase letters combined with underscores.
Ex: length, batch_strength
All classes and interfaces start with a leading uppercase letters. Ex: Student, Vehicle.
Variables that represent constant values use all uppercase letters and underscores between
words. Ex: TOTAL, F_MAX, PRINCIPAL_AMOUNT
Literals / Constants
Literals in java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals.
They are:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
Separators
Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code.
Java separators:
Parenthesis ( ) used to enclose parameters in method definition and invocation, also used for
defining precedence in expression, containing expressions for flow control and surrounding cast
types.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 22
Java Programming
Braces { } used to contain the values of automatically initialized arrays and to define a block
of code for classes, methods, and local scopes
Brackets [ ] used to declare array types and for dereferencing array values.
Semicolon ; used to separate statements.
Comma , used to separate consecutive identifiers in a variable declaration, also used to
chain statements together inside a “for” statement
Period . used to separate package names from sub-package and classes; also used to
separate a 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 several types of statements:
Empty Statement : These do nothing and are used during program development as a
place holder.
Labeled Statement : Any statement may begin with a label. Such labels must not be
keywords, already declared local variables or previously used labels in this module.
Expression Statement : Most statements are expression statement. Java has seven
types of Expression statements: Assignment, Pre-Increment, Post-Increment, Pre-
decrement, Post-decrement, method call and allocation expression.
Selection Statement : These select one of several control flows. There are three types of
selection statements in java: if , if-else, and switch.
Iteration Statement : These specify how and when looping will take place. There are
three types of iteration statements: while, do-while and for.
Jump statement : Jump statements pass control to the beginning or end of the
current block or to a labeled statement. Such labels must be in the same block, and
continue labels must be on an iteration statement. The four types of jump statements are
break, continue, return and throw.
Synchronization statement: These are used for handling issues with multithreading.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 23
Java Programming
Guarding Statements : Guarding statements are used for safe handling of code
that may cause exceptions. These statements use the keywords: try, catch, and finally.
CONSTANTS
Constant means fixed value which is not change at the time of execution of program. In Java, there
are two types of constant as follows:
Numeric Constants
Integer constant
Real constant
Character Constants
Character constant
String constant
Integer Constant:
An Integer constant refers to a series of digits. There are three types of integer as follows:
a) Decimal integer: consists of a set of digits, 0 through 9 preceded by an optional minus sign.
Embedded spaces, commas and characters are not allowed in between digits.
For example:
23 411
7,00,000
b) Octal integer: consists of any combination of digits from the set 0 through 7 with a leading 0.
For example:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 24
Java Programming
011
00
0425
c) Hexadecimal integer It allows the sequence which is preceded by 0X or 0x and it also allows
alphabets from ‘A’ to ‘F’ or ‘a’ to ‘f’ (‘A’ to ‘F’ stands for the numbers ‘10’ to ‘15’) it is called
as Hexadecimal integer.
For example:
0x7
00X
0A2B
Real Constant:
Integer numbers inadequate to represent quantities that varies continuously. These quantities are
represented by numbers containing fractional parts. Such numbers are called real (or floating
point) constants.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 25
Java Programming
“END OF PROGRAM”
Data types
Every variable in java has a data type. Data types specify the size and type of values that the
variables can be stored. Java language is rich in its data types.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 26
Java Programming
Following table shows the datatypes with their size and ranges.
Data type Size (byte) Range
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308
Integer data type:
Integer data type can hold the numbers (the number can be positive number or negative number).
In Java, there are four types of integer as follows:
byte
short
int
long
We can make integer long by adding ‘l’ or ‘L’ at the end of the number.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 27
Java Programming
Variables
A variable is an identifier that denotes a storage location used to store data value. These variables
can be changed during the execution of the program. A variable may take different values at
different times during the execution of the program.
A variable name can be chosen by the programmer in a meaningful way so as to reflect what is
represents in the program.
Declaration of variables
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 28
Java Programming
In java, variables are the names of storage location. After designing suitable variable names, we
must declare them to the compiler. 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 first way to declare a variable: This specifies its data type, and reserves memory for it. It
assigns zero to primitive types and null to objects.
dataType variableName;
The second way to declare a variable: This specifies its data type, reserves memory for it, and
puts an initial value into that memory. The initial value must be of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves memory for each.
dataType variableNameOne, variableNameTwo;
The second way to declare two variables: both of the same data type, reserves memory, and puts
an initial value in each variable.
dataType variableNameI = initialValueI, variableNameII=initialValueII;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 29
Java Programming
1. Assignment statement
A simple method of giving value to a variable is through the assignment as follows:
VariableName= value;
Ex: initialValue= 0;
We can also assign string assignment expression as shown below:
X=Y=Z=0;
It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
type variableName = value;
ex: int total = 75.32;
2. Read statement
We may also give the values to variables interactively through the keyboard using the method
readLine( )
The readLine( ) method read the input from the keyboard as a string which is then converted to
the corresponding data type using the data type wrapper classes.
The readLine ( ) method which is invoked using an object of the class DataInputStream.
Program:
import java.io.DataInputStream;
class cc2
{
public static void main(String args[ ]) throws Exception
{
Output:
DataInputStream s1=new DataInputStream(System.in); C:\cc>java cc2
byte rollno; Enter roll number:
07
int marks1,marks2,marks3; Enter marks m1, m2,m3:
float avg; 66
77
System.out.println("Enter roll number:"); 88
rollno=Byte.parseByte(s1.readLine()); Roll number is=7
Average is=77.0
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 30
Java Programming
Scope of Variables
Java variables are actually classified into three kinds:
Instances variables
Class variables
Local variable
Instances 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.
Variable 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 closing brace}.
“The area of the program where the variable is accessible is called its scope.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 31
Java Programming
We can have program blocks within other program blocks (called nesting) as shown in fig:
{
int x=0;
{ .
Block 1
.
int n=5;
. Block 2
}
{
.
int m=15; Block 3
}
Symbolic Constant
We often use certain unique constant in a program. These constants may appear repeatedly in a
number of places in the program. One example of such a constant is 3.142, representing the
value of the mathematical constant “pi”. We face two problems in the subsequently use of such
programs. They are:
Modifiability
We may like change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of
calculations or the number 50 to 100 to process the test results of another class. In both cases, we
will have to search throughout and explicitly change the value of the constant whenever it has
been used. If any value is left unchanged, the program may produce disastrous outputs.
Understandability
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 32
Java Programming
When a numeric value appears in a program, its use is not always clear, especially when the
same value means different things in different places. For example: the number 50 may mean the
number of students at one place and the ‘pass marks’ at another place of the same program.
A constant declared as follows:
final type symbolic_name= value;
Type Casting
We often encounter situations where there is a need to store a value of one into a variable of
another type. In such situations, we must cast the value to be stored by preceding it with the type
name in parenthesis.
The syntax is
type variable1 = (type) variable2 ;
The process of converting one data type to another is called casting.
Ex : int m = 50;
byte n = (byte) m;
long count=(long)m;
The below table list those casts, which are guaranteed to result in no loss of information.
Form To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double
Automatic Conversion
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 33
Java Programming
For some types, it is possible to assign a value of one type to a variable of a different type
without a cast. Java does the conversion of the assigned value automatically. This is known as
automatic type conversion. Automatic type conversion only possible only if the destination
type has enough precession to store the source value.
For ex: byte b = 75;
int a= b;
The process of assigning a smaller type to a larger one is known as widening or promotion and
that of assigning a larger type to a smaller one is known as narrowing.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 34
Java Programming
“An operator is a symbol that takes one or more arguments and operators on them to produce a
result.”
Java supports a rich set of operators. Such as +, -, =, *. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators are used in
programs to manipulate data and variables.
Java operators can be classified into a number of related categories as below:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
Java provides all the basic arithmetic operators. Such as +, -, *, and /. They can operate on any
built-in numeric data type of java. We cannot use these operators on Boolean type. The unary
minus operator multiplies its single operand by -1. Therefore, a number preceded by a minus
sign changes its sign.
Table: Arithmetic Operators
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division (Remainder)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 36
Java Programming
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 both the operand in a single arithmetic expression such as a+b are integers, the expression
is called an integer expression, and the operation is called integer arithmetic. Integer arithmetic
always yields an integer value. Ex: if a and b are integers, then for a=14 and b=4 we have the
following results: a – b =10
a + b =18
a * b =56
a / b =3 (decimal part truncated)
a % b=2 (remainder of integer division)
a/b, when a and b are integer types, gives the result of division of a by b after truncating the
divisor. This operation is called the integer division.
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand
may assume values either in decimal or exponential form. Since floating point values are
rounded to the number of significant digits permissible, the final value is an approximation of the
correct result.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 37
Java Programming
Relation Operators
We often compare two quantities, and depending on their relation, take certain decisions. These
comparisons can be done with the help of relational operators.
An expression such as
a<b or x < 20
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 38
Java Programming
Java supports six relational operators. These operators and their meanings are shown in table:
Relational Operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and is of the following form:
ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them.
Logical Operators
Java has three logical operators.
Logical Operators
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 39
Java Programming
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to form compound conditions by
combining two or more relations. An example is:
A > B && x == 10
An expression of this kind which combines two or more relational expressions is termed as a
logical expression or compound relational expression.
Assignment Operators
Assignment Operators are used to assign the value of an expression to a variable. We have seen
the usual assignment operator, ‘=’. 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.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 40
Java Programming
x= x+(y+1);
The operator ++ adds 1 to the operand while - - subtracts 1. Both are unary operators and are
used in the following form:
++m; or m++;
- - m; or m - -;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 41
Java Programming
Conditional Operator
The character pair ? : is a ternary operator available in Java. This operator is used to construct
conditional expressions of the form
Exp1 ? Exp2 : Exp3
The Operator ? : works as follows: Exp1 is evaluated first. If it is nonzero (true), then the
expression Exp2 is evaluated and becomes the value of the conditional expression. If Exp1 is
false, Exp3 is evaluated and its value becomes the value of the conditional expression. Note that
only one of the expressions (either Exp2 or Exp3) is evaluated.
Bitwise Operators
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or double.
Bitwise Operators
Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 42
Java Programming
~ Bitwise complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
Special Operators
Java supports some special operators of interest such as instanceof operator and member
selection operator (.).
instanceof Operator
The instanceof 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 us to determine
whether the object belongs to a particular class or not.
Example: person instance student
is true if the object person belongs to the class student; otherwise it is false.
Dot Operator
The dot operator (.) is used to access the instance variables and methods of class objects.
Examples: person1.age // reference to the variable age
Person1.salary( ) // reference to the member method salary( )
Arithmetic Expressions
An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language. Java can handle any complex mathematical expressions. Some of the
examples of the java are:
Algebraic Expression Java Expressions
ab-c a*b-c
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 43
Java Programming
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = Expression;
Variable is any valid java variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is attempted.
X= a*b-c;
Y= b/c*a
Z= a-b/c+d;
Precedence of Arithmetic
An arithmetic expression without any parentheses will be evaluated from left to right using the
rules of precedence of operators. There are two distinct priority levels of arithmetic operators in
java.
High priority * / %
Low priority + -
The basic evaluation procedure includes two left-to-right passes through the expression. During
the first pass, the high priority operators are applied as they are encountered.
During the second pass, the low priority operators are applied as they are encountered.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 44
Java Programming
X= 9-12/3+3*2-1
First pass:
Step1: x=9 - 4+3*2-1 (12/3 evaluated)
Step2: x= 9 – 4+6-1 (3*2 evaluated)
Second pass:
Step3: x= 5+6-1 (9 – 4 evaluated)
Step4: x= 11 – 1 (5+6 evaluated)
Step5: x=10 (11-1 evaluated)
However, the order of evaluation can be changed by introducing parenthesis into an expression.
Consider the same expression with parenthesis as shown below:
9-12 / (3+3)*(2-1)
Whenever the parentheses are used, the expression within parentheses assumes highest priority.
If two or more sets of parentheses appear one after another as shown above, the expression
contained in the left-most set are evaluated first and the right-most in the last. Given below are
the new steps.
First pass:
Step1: 9-12/6*(2-1)
Step2: 9-12/6*1
Second pass:
Step3: 9-2*1
Step4: 9-2
Third pass:
Step5: 7
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 45
Java Programming
Each operator in java has a precedence associate with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. There are distinct levels of
precedence and an operator may belong to one of the levels. The operators at the higher level of
precedence are evaluated first. The operator of the same precedence are evaluated either from
left to right or from right to left, depending on the level. This is known as Associativity property
of an operator. Table shows a complete lists of operators, their precedence levels, their rules of
association. The groups are listed in the order of decreasing precedence (rank 1 indicates the
highest precedence level and 14 is the lowest).
Summary of java operators
Operator Description Associativity Rank
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 46
Java Programming
>>
>>> Right shift
Right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Type comparison
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Left to right 13
= Assignment operator Right to left 14
Op= Shorthand operator Right to left
Mathematical Functions
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of real-life
problems. Java supports these basic math functions through Math class defined in the java.lang
package. These functions should be used as follows:
Math.function_name( );
Math Functions
Function Action
sin(x) Returns the sine of the angle x in radians
cos(x) Returns the cosine of the angle x in radians
tan(x) Returns the tangent of the angle x in radians
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 47
Java Programming
Java language possesses such decision-making capabilities and supports the following statements
called control or decision-making statements.
1. if statement
2. switch statement
3. conditional operator
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 48
Java Programming
Flowchart:
Test
expressio
Prepared by: Sowmya Rani G S, Lecturer, Deptn of Computer Science, CTA Page 49
Java Programming
Statement-block
F
Statement-x
Next Statement
The statement block may be a single statement or group of statements. If the test expression is
true, the statement-block is executed; otherwise the statement-block will be skipped and the
execution will jump to the statement-x.
Statement-x
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 50
Java Programming
If the test expression is true, then the true block statement immediately following the if
statements are executed. Otherwise the false statements are executed.
If the test condition1 is true, it continues the second test. If the test condition2 is true, the
statement 1 will be evaluated. Otherwise the statement 2 will be evaluated and the condition 1 is
false, the statement 3 will be executed.
F
Test
condition
1
F T
Test
condition
2
Statement3
Prepared by: Sowmya Rani G S,Statement
Lecturer,2Dept of Computer Science, CTA
Statement1 Page 51
Statement-x
Java Programming
Ex: if (a>b)
{
if (a>c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if(c>b)
{
System.ou.println(c);
}
else
{
System.out.println(b);
}
}
The else if ladder
There is another way of putting ifs together when multipath decisions are 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 (marks > 79)
if ( condition1) grade=”distinction”;
statement1 else if(marks>59)
grade=”first class”
else if (condition2) else if(marks>49)
statement2 grade=”secondclass”
else if(condition3 else if(marks>35)
grade=”pass”;
statement3 else
……….. grade=”fail”;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 52
Java Programming
else if(condition n)
statement n;
else
default statement;
statement-x;
Flowchart:
T F
Condition
1
Statement1 T F
Condition
2
T F
Statement2
Condition
3
Statement3
Condition
n
Statement-x Default
Statement
Next statement
This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x. when all the n condition becomes
false, then the final else containing the default statement will be executed.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 53
Java Programming
switch (expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break2;
case value-3: block-3;
break3;
………..
……….
default: default block;
break;
}
Statement-x;
Flowchart:
expressio
n
Exp=value1
Block1
…………………………..
Exp=value2
Block2
Default
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA block Page 54
Java Programming
default
Statement x
The expression is an integer expression or characters, value1, value2, -----value n are constants
expression and are known as case labels. Each of these values should be unique within a switch
statement. Block1, Block2 --------------Block-n are the statements lists and may contain zero or
more statements. There is no need to put braces around these blocks but it is important to note
that case labels end with a colon ( : ).
When the switch is executed, the value of the expression is successively compound against the
values value1, value2--- value-n.
The break statement at the end of each block signals the end of a particular case and causes an
exit from switch statement transferring the control to the statement-x following the switch.
Example:
switch ( i )
{
case 1: grade = “Distinction”;
break;
case 2: grade = “first class”;
break;
case 3: grade = “second class”;
break;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 55
Java Programming
In looping, a sequence of statements is executed until some conditions for the termination of the
loop are satisfied. A program loop therefore consists of 2 segments, one known as the body of
the loop and other known as the control statement. The control statement tests certain conditions
and then directs the repeated execution of the statements contained in the body of the loop.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 56
Java Programming
Depending on the position of the control statements in the loop, a control structure may be
classified either as the entry controlled loop or as exit-controlled loop.
In entry-controlled loop, the control conditions are tested before the start of the loop execution.
If the conditions are not satisfied, then the body of the loop will not be executed.
In 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.
Test statements
conditio
n
The java language provides for three constructs for performing loop operations. They are
1. While construct
2. Do while construct
3. for construct
1. while statement: The simplest of all the looping structures in java is the while statement.
The basic format of the while statement is:
initialization
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 57
Java Programming
while (condition)
{
Body of the loop;
}
The while is an entry controlled loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. 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
of repeated execution of the body continued until the test condition finally 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.
Ex: …..
…..
Sum=0;
N=1;
while(N<=10)
{
Sum= Sum+ n*n;
N=N+1;
}
2. The do statement
In this statement the body of the loop is first executed before the test is performed. The general
form of do statement is:
Initialization
do
{
Body of the loop;
}
while (condition);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 58
Java Programming
The do while statement is an exit-controlled loop statement. On reacting the do statement, the
program proceeds to evaluate the body of the loop first. At the end of the loop, the test condition
in the while statement is evaluated. If the condition is true, this program continues to evaluate the
body of the loop once again. This process continues as long as the condition is true. When the
condition becomes false, the loop will be terminated and the control goes to the statement that
appears immediately of the while statement.
Ex: ……
……
i= 1;
sum=0
do
{
sum=sum+1;
i=i+2;
}
while( sum < 40 || i<10);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 59
Java Programming
an assignment statement and the new value of the control variable is again tested to see
whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is
again executed. This process continues till the value of the control variable fails to satisfy
the test conditions.
Ex: for(x=0 ; x<=9; x=x+1)
{
System.out.println(x);
}
Jumps in loops
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. When the break statement is encountered inside a loop, the loop is immediately
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 60
Java Programming
exited and the program continues with the statement immediately following the loop. When the
loops are nested, the break would only exit from the loop containing it. i.e break will exit only a
single loop.
Ex: while(…..)
{
……
if (condition)
break;
}
……
Skipping a part of loop: During the loop operation, it may be necessary to skip a part of
the body of the loop under certain conditions.
Java supports another statements called the continue statement. The continue, as the name
implies causes the loop to be continued with the next iteration after skipping any statements in
between.
The continue statements tells the compiler skips the following statement and continue with the
next iteration.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 61
Java Programming
………
………
}
Labelled loops
In java, we can give a label to a block of statements. A label is any valid java variable name. to
give a label to a loop, place it before the loop with a colon at the end.
Ex: loop1: for (…….)
{
….
….
}
A block of statement can be labeled as shown below:
block1: {
….
}
block 2: {
……
}
{
…..
}
{
…..
}
Array in Java
An array refers to a data structure that contains homogeneous elements. This means that all the
elements in the array are of the same data type. Let's take an example:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 62
Java Programming
This is an array of seven elements. All the elements are integers and homogeneous. The green
box below the array is called the index, which always starts from zero and goes up to n-1
elements. In this case, as there are seven elements, the index is from zero to six.
Here, the type is int, String, double, or long. Var-name is the variable name of the array.
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of the
program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:
In this example, we have an array of five elements. They are stored in a single line or adjacent
memory locations.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 63
Java Programming
Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We use a for
loop to print the elements of the array. The output of this is as follows:
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper
corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three columns.
Brackets separate the rows, and the number of elements separates the columns. For this, we use
two for loops: one for rows and one for each element in the row. When we execute this program,
the result will be as follows:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 64
Java Programming
3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than two
rows and columns using the following code:
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will always be
two.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 65
Java Programming
Class provides 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. Calling a specific method in an object is described as sending the object a
message.
Defining a Class:
A class is a 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 using declarations that are
similar to the basic type declarations.
In java, these variables are termed as instances of classes, which are the actual objects.
Everything inside the square brackets is optional. classname and super classname are any valid
java identifier. The keyword extends indicates that the properties of the superclassname. Classes
are extended to the classname class. This concept is known as Inheritance.
Fields Declaration:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 66
Java Programming
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variable because they are created whenever an object of the
class in instantiated. We can declare the instance variables exactly the same way as declare local
variables.
Ex: class Rectangle
{
int length;
int width;
}
The class Rectangle contains 2 integer type instance variables.
int length, width;
Method Declaration
Methods are declared inside the body of the class but immediately after the declaration of
instance variables.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 67
Java Programming
The type specifies the type of the value the method would return. The methodname is a valid
identifier. The parameter_list is always enclosed in parenthesis. This list contains variable names
and types of all the values we want to give to the method as input. The variables in the list are
separated by comma.
(int m, float x, float y) // three parameter
( ) // empty list
Let us consider, the Rectangle class again and add a method getData( ) to it.
class Rectagle
{
int length;
int width;
Creating Objects
An object in java is essentially a block of memory that contains spaces to store the entire
instance variables. Creating an object is also referred to as instantiating an object.
Object in java are created using the new operator. The new operator creates an object of the
specified class and returns a reference to that object.
Ex: Rectangle rect1; //declare the object
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 68
Java Programming
The first statement declares a variable to hold the object reference and the second one actually
assigns the object reference to the variable.
Here objectname is the name of the object, variablename is the name of the instance variable
inside object that we wish to access, methodname is the method that we wish to call and
parameter_list is a comma separated list of actual values that must match in type and number
with the parameter list of the method name declared in the class.
The instance variable of the Rectangle class may be accessed and assigned values as follows:
rect1.length =15;
rect1.width = 10;
rect2.length= 20
rect2.width =12;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 69
Java Programming
length =x;
width =y;
}
int rectArea( )
{
int area=length*width;
return(area);
}
}
Constructors
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 70
Java Programming
Java supports a special type of method, called a constructor, that enable an object to initialize
itself when it is created.
Constructors have the same name as the class itself. Secondly, they do not specify a return type,
not even void. This is because they return the instance of the class itself.
Let us consider Rectangle class again. We can now replace the getData method by a constructor
method as shown below:
class Rectangle
{
int length;
int width;
Rectangle(int x, int y) // defining constructor
{
length = x;
width = y;
}
int rectArea( )
{
return (length*width);
}
}
class RectangleArea
{
public static void main(String args[ ])
{
Rectangle rect1=new Rectangle(15, 10); // calling constructor
int area1=rect1.rectArea( );
System.out.println(“Area1=”+area1);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 71
Java Programming
}
}
Method Overloading
In java, it is possible to create methods that have the same name, but different parameters list and
different definitions. This is called method overloading.
Method overloading is used when objects are required to perform similar tasks but using
different input parameters. When we call a method in a object, java matches up the methodname
first and then the number and type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.
int area( )
{
return (length * width);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 72
Java Programming
}
}
Here, we are overloading the constructor method Room( ). An object representing a rectangular
room1 will be created as.
On the other hand, if the room is square, then we may create the corresponding object as
Static members
We have seen that a class basically contains 2 sections. One declares variables and the other
declares methods. These variables and methods are called instance variables and instance
methods. This is because every time the class is instantiated, a new copy of each of them is
created. They are accessed using the objects (with dot operator).
Let us assume that we want to define a member that is common to all the objects and accessed
without using a particular object. i.e the member belongs to the class as a whole rather than the
objects created from the class. Such members can be defined as follows:
The members that are declared static as shown above are called static members. Since these
members are associated with the class itself rather than individual objects, the static variables
and static methods are often referred to as class variables and class methods.
Static variables are used. When we want to have a variable common to all instances of a class.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 73
Java Programming
class MathApplication
{
public static void main(String args[ ])
{
float a=MathOperation.mul(4.0, 5.0);
float b=MathOperation.divide(a, 2.0);
System.out.println(“b=”+b);
}
}
Note that static methods are called using class names. Static methods have several restrictions:
1. They can only call other static methods.
2. They can only access static data.
3. They cannot refer to this or super in anyway.
Nesting of Methods
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 74
Java Programming
A method can be called by using its name by another method of the same class. This is known as
Nesting of methods.
int largest( )
{
if (m>=n)
return m;
else
return n;
}
void display( )
{
int large = largest( ); // calling a method
System.out.println(“largest value=”+large);
}
}
class NestingTest
{
public static void main(String args[ ])
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 75
Java Programming
{
Nesting nest=new Nesting(50,40);
Nest.display( );
}
}
The inheritance allows subclasses to inherit all the variables and methods of their parent classes.
Inheritance may take different forms:
Single inheritance (only one super class)
Multiple inheritance (several super classes)
Hierarchical inheritance (one super class, many subclasses)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 76
Java Programming
Java does not directly implement multiple inheritance. However, this concept is implemented
using a secondary inheritance path in the form of interfaces.
A A
B B C D
A B
A
B
C
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 77
Java Programming
Defining a Subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
Variables declaration;
Method declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname. The subclass will now contain its own variables and methods as well those of the
superclass.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 78
Java Programming
{
super (x,y); // pass values to super class
height=z;
}
int volume( )
{
return (length*width*height);
}
}
class InherTest
{
public static void main(String args[ ] )
{
AnotherRoom room1=new AnotherRoom(14, 12, 10);
int area1= room1.area( ); // superclass method
int volume1 = room1.volume( ); // baseclass method
System.out.println(“Area1= “+area1);
System.out.println(“Volume=”+volume1);
}
}
Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method of
the superclass. The keyword super is used subject to the following conditions:
super may only be used within a subclass constructor method
The call to superclass constructor must appear as the first statement within the subclass
constructor
The parameters in the super call must match the order and type of the instance variable
declaration in the superclass.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 79
Java Programming
Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a super
class. Java supports this concept and use it extensively in building its class library.
A
Super class
B Intermediate Superclass
C Subclass
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.
}
class C extends B // Second level
{
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 80
Java Programming
Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the hierarchical design of
a program. Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below the level.
B C D
Overriding Methods
There may be the occasions when we want an object to respond to the same method but have
different behavior when that method is called. That means, we should override the method
defined in the superclass. This is possible by defining a method in the subclass that has the same
name, same arguments and same return type as a method in the subclass. Then, when that
methods is called, the method defined in the subclass is invoked and executed instead of the one
in the super class. This is known as overriding.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 81
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 82
Java Programming
All methods and variables can be overridden by default in subclasses. If we wish to prevent the
subclasses from overriding the members of the superclass, we can declare them as final using the
keyword final as a modifier.
Ex: final int SIZE =100;
final void showstatus( );
Making a method final ensures that the functionality defined in this method will never be altered
in any way. Similarly, the value of a final variable can never be changed.
Final Classes
Sometimes we may like to prevent a class being further subclasses for security reasons. A class
that cannot be subclassed is called a final class. This can be achieved in java using the keyword
final as follows:
final class Aclass {…….}
final class Bclass extends Someclass {…….}
Finalizer
We have seen that a constructor method is used to initialize an object when it is declared. This
process is known as initialization. Similarly, java supports concept finalization, which is just
opposite to initialization. We know that java run-time is an automatic garbage collecting system.
It automatically frees up the memory resources used by the objects. But objects may hold other
non-object resources such as file descriptions or window system fonts. The garbage collector
cannot free these resources. In order to free these resources we must use a finalize( ) and can be
added to any class.
The finalizer method is simply finalize( ) and can be added to any class. Java calls that method
whenever it is about to reclaim the space for that object. The finalize method should explicitly
define the tasks to be performed.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 83
Java Programming
In the above syntax, the method contains an argument called varargs in which object is the type
of an argument, ellipsis ( ) is the key to varargs and arguments is the name of the variables.
Visibility Control
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 84
Java Programming
The visibility modifiers is also known as access modifiers. Java provides three types of visibility
modifiers: public, private and protected. They provide different levels of protection.
public Access: Any variable or method is visible to the entire class in which it is defined.
What if we want to make it visible to all classes outside this class? This is possible by simply
declaring the variable or method as public.
Ex: public int number;
public void sum( )
friendly Access: In many of our examples, we have not used public modifier, yet they
were still accessible in other classes in the program. When no access modifier is specified, the
member defaults to a limited version of public accessibility known as “friendly” level of access.
The difference between the public access and the friendly access is that the public modifier
makes fields visible in all classes, regardless of their packages while friendly access makes fields
visible only in the same package, but not in other packages. A package is a group of related
classes stored separately.
protected Access: The visibility level of a “protected” fields lies in between the public
access and friendly access. i.e the protected modifier makes the fields visible not only to all
classes in the same package but also to subclasses in other packages. Note-that non-subclasses in
other packages cannot access the “protected” members.
private: private fields enjoy the highest degree of protection. They are accessible only
with their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared as final. It prevents the
method from being subclasses. Also note that we cannot override a non-private method in a
subclass and then make it private.
private protected Access: A field can be declared with two keywords private and
protected together.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 85
Java Programming
This gives the visibility level in between the “protected” access and “private” access. This
modifier makes the fields visible in all subclasses regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same package.
Rules:
Given below are some simple rules for applying appropriate access modifiers.
Use public if the field is to be visible everywhere.
Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
Use “default” if the field is to be visible everywhere in the current package only.
Use private protected if the field is to be visible only in subclasses, regardless of
packages.
Use private if the field is not to be visible anywhere except in its own class.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 86
Java Programming
Arrays:
An array is a group of contiguous or related items that share a common name A particular value
is indicated by writing a number called index number or subscript in brackets after the array
name.
For : students[10];
Represents the group of students. While the complete set of values is referred to as an array, the
individual values are called elements.
One-dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one-dimensional array.
Ex: if we want to represent a set of five numbers, say (35, 40, 20, 57, 19), by an array variable
number, then we may create the variable Number as follows:
int Number [ ]= new int[5];
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 87
Java Programming
Number[0]
Number[1]
Number[2]
Number[3]
Number[4]
Creating an array
Like any other variables, arrays must be declared and created in the computer memory before
they are used. Creation of an array involves three steps.
1. Declaring the array
2. Creating the array
3. Putting values into the memory locations
Declaration of Arrays:
Arrays in java may be declared in tow forms:
Form 1: type arrayname[ ];
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 88
Java Programming
float avg[ ];
int[ ] counter;
float[ ] marks;
Creation of arrays:
After declaring an array, we need not create it in the memory. Java allows is to create arrays
using new operator only.
arrayname = new type[size];
This line create necessary memory locations for the arrays number as int type. Now the variable
number refers to an array of 5 integers.
It is also possible to combine the two steps- declaration and creation-into one as shown below:
int number[ ]= new int [5];
Initialization:
The final step is to put values into the array created. This process is known as initialization. This
is done using the array subscripts as shown below:
arrayname[subscript]=value;
Example: number[0]=35;
We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
type arrayname[ ]= {list of values};
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 89
Java Programming
The array initializer is a list of values separated by commas and surrounded by curly braces.
Note that no size is given. The compiler allocates enough space for all the elements specified in
the list.
Example: int number[ ]={35, 40, 20, 57, 19);
Array length
In java, all arrays store the allocated size in a variable named length. We can obtain the length of
the array a using a.length.
// sort begins
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 90
Java Programming
for(int i=0;i<n;i++)
{
for(j=0;j<i+1;; j++)
{
if (number[i] < number [j])
{
int temp=number[i];
number[i]= number[j];
number[j]=temp;
}
}
}
System.out.println(“sorted list”);
for ( int i=0; i<n; i++)
{
System.out.println(“ “+number[i]);
}
System.out.println(“ “);
}
}
Two-dimensional Arrays
Java allows us to define tables of items by using two dimensional arrays. The table can be
represented in java as
Table[rowsize] [colsize] ;
Two dimensional array are stored in memory as shown below. Here the first index selects the
row and the second index selects the column within that row.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 91
Java Programming
For creating the two dimensional arrays, we must follow the same steps that of simple arrays. We
may create a two-dimensional array,
int myArray[ ][ ];
myArray= new int[3][4];
or
int myArray[ ][ ] = new int[3][4];
Like one dimensional array, two-dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces.
We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[ ][ ] = {
{0, 0, 0},
{1, 1, 1}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 92
Java Programming
Note the syntax of the above statements. Commas are required after each brace that closes off a
row except in the case of the last row.
We can refer to a value stored in a two dimensional array by using subscripts for both the column
and row of the corresponding element.
Example: int value = table[1][2];
This retrieves the value stored in the second row and third column of table matrix.
These statements create a two dimensional array as having different lengths for each row as
shown in fig:
x[0][1]
x[0]
x[1] x[1][3]
x[2] x[2][2]
Strings
Strings manipulation is the most common part of many java programs. A string represents a
sequence of characters enclosed within double quotes. The easiest way to represent a sequence of
characters in java is by using a character array.
Example: char charArray[ ] = new char[4];
charArray[0] = ‘J’;
charArray[1] = ‘A’;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 93
Java Programming
charArray[2] = ‘V’;
charArray[3] = ‘A’;
In java, strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class.
Example:
String firstName;
firstName = new String(“smitha”);
Like arrays, it is also possible to get the length of strings using the length method of the String
class.
int m = firstName.length( );
Note the use of parentheses here. Java strings can be concatenated using the + operator.
Example:
String fullName = name1 + name2;
String city1 = “New” + “Delhi”;
String Array
We can also create and use arrays that contain strings. The statement
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 94
Java Programming
String Methods
The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks.
StringBuffer class
StringBuffer is a peer class of String. While String creates of fixed _length. StringBuffer creates
strings of flexible length that can be modified in terms of both length and content.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 95
Java Programming
Vectors
The vector class contained in the java.util package. This 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. Arrays can be easily implemented as vectors.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 96
Java Programming
Note that a vector can be declared without specifying any size explicitly. A vector without size
can be accommodating an unknown number of items. Even, when the size is specified, this can
be overlooked and a different number of items may be put into the vector. Remember, in
contrast, an array must always have its size specified.
A major constraint in using vectors is that we cannot directly store simple data type in a vector.
We can only store objects. Therefore, we need to convert simple types to objects. This can done
by using wrapper classes.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 97
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 98
Java Programming
Wrapper classes
Vectors cannot handle primitive data types like int, float, long, char and double. Primitive data
types may be converted into object types by using the wrapper classes contained in the java.lang
package.
The below table shows the wrapper classes for converting simple types
Simple type wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Defining Interfaces
An interface is basically a kind of class. Like class, interface contain methods and variables but
with a major difference. The difference is that interfaces define only abstract methods and final
fields. This means that interfaces do not specify any code to implement these methods and data
fields contain only constants.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 99
Java Programming
The syntax for defining an interface is very similar to that for defining a class. The general form
of an interface definition is:
interface InterfaceName
{
Variable declaration;
Method declaration;
}
Here, interface is the keyword and interface name is any valid java variable. Variables are
declared as follows:
static final type variableName= value;
Note that all variables are declared as constants. Methods declaration will contain only a list of
methods without anybody statements.
return-type methodName(parameter-list);
Ex: Here is an example of an interface definition that contain 2 variables and one method.
interface Item
{
static final int code=1001;
static final String name= “fan”;
void display( );
}
Note that the code for the method is not included in the interface and the method declaration
simply ends with a semicolon.
Extending Interfaces
Like classes, interface can also be extended. i.e an interface can be sub interfaced from other
interfaces. The new sub interfaces will inherit all the members of the super interface in the
manner similar to subclass. This can be achieved using the keyword extends as shown below:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 100
Java Programming
Implementing Interfaces
Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interfaces. This is done as follows:
class classname implements interfacename
{
Body of class name
}
Here the class name “implements” the interface interfacename. A more general form of
implementation is:
class classname extends superclass implements interface1, interface2,……
{
Body of classname
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 101
Java Programming
This shows that a class can extended another class while implementing interface.
class Interface
{
public static void main(String args[ ])
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 102
Java Programming
{
Rectangle rect=new Rectangle( );
Circle cir= new Circle( );
Area area; // interface object
area= rect; // area refers to rect object
System.out.println(“Area of Rectangle”+area.compute(10,20));
area= cir;
System.out.println(“Area of circle”+ area.compute(10,0));
}
}
Ex: interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method(int size)
{
……
if (size < n)
…….
}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 103
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 104
Java Programming
interface Sports
{
float sportWt=6.0F;
void putWt( );
}
class MultipleInheritance
{
public static void main(String args[ ] )
{
Result student1=new Result( );
student1.getNumber(1234);
student1.getMarks(27.5F, 33.0F);
student1.display( )
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 105
Java Programming
}
}
Packages are java’s way of grouping a variety of classes and/or interfaces together. The grouping
is usually done according to functionality. In fact, packages acts as “containers” for classes. By
organizing our classes into packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 106
Java Programming
2. In packages, classes can be unique compared with classes in other packages. i.e, 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 a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”. First we can design
classes and decide their relationships, and then we can implement the java code needed
for the methods. It is possible to change the implementation of any method without
affecting the rest of the design.
Java packages are classified into two types: the first category is known as Java API packages and
the second category is known as user defined packages.
Java
net apple
lang util io awt
t
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 107
Java Programming
Java
awt Package containing
awt package
Color
Graphics
package containing
Font:
Prepared by: Sowmya Rani G: S, Lecturer, Dept of Computer Science, CTA Page 108
Java Programming
classes
Image
classes containing
methods
There are two ways of accessing classes’ stores in a package. The first approach is to use the
fully qualified class name of the class that we want to use. This is done by using the package
name containing the class and then appending the class name to it using the dot operator. For
example: if we want to refer to the class Color in the awt package, then we may do so as
follows.
java.awt.Color
Notice that awt is a package within the package java and the hierarchy is represented by
separating the levels with dots.
We might want to use a class contained in a package. We may achieve this easily as follows:
import packagename.classname;
or
import packagename.*;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 109
Java Programming
These are known as import statements and must appear at the top of the file, before any class
declarations, import is a keyword.
The first statement allows the specified class in the specified package to be imported. For
Example, the statement
import java.awt.Color;
imports the class Color and therefore the class name can now be directly used in the program.
There is no need to use the package name to qualify the class.
The second statement imports every class contained in the specified package. For Example, the
statement
import java.awt.*;
Naming Conventions
Packages can be named using the standard java naming rules. By convention, however packages
begin with lowercase letters. This makes it easily for user to distinguish package names from
class names when looking at an explicit reference to a class. We know that all class names, again
by convention, begin with an uppercase letter. For example,
double y= java. lang . Math . sqrt(x);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 110
Java Programming
This statement uses a fully qualified class name Math to invoke the method sqrt( ). Note that
methods begin with lowercase letters.
Creating Packages
Now, let us see how to create our own packages. We must first declare the name of the package
using the package keyword followed by a package name. This is must be first statement in a java
source file. Then we define a class, just as we normally define a class.
Here is an example: package firstPackage // package declaration
public class FirstClass // class definition
{
Body of class
}
Here the package name is firstPackage. 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 directory
named firstPackage. When source file is completed. 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. Ex,
package firstPackage . secondPackage;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 111
Java Programming
This approach allows us to group related classes into a package and then group related packages
into a larger package. Remember to store this package in a subdirectory named
firstPackage/secondPackage.
Accessing a Package
Java system packages can be accessed either using a fully qualified class name or using a
shortcut approach through the import statement. We use the import statement when there are
many references to a particular package or the package name is too long and unwieldy.
The import statement can be used to search a list of packages for a particular class. The general
form of import statement for searching a class is as follows:
import package1 [.package2] [.package3].classname;
Here package1 is the name of the top level package, package2 is the name of the package that is
the explicit classname is specified.
Note that the statement must be end with a semicolon (;). The import statement should appear
before any class definitions in a source file. Multiple import statements are allowed. The
following is an example of importing a particular class:
import firstPackage.secondPackage.Myclass;
Using a Package
The listing below shows a package named package1 containing a single class ClassA.
package package1;
public class ClassA
{
public void display( )
{
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 112
Java Programming
System.out.println(“Class A”);
}
}
This source file should be named as ClassA.java and stored in the subdirectory package1 as
stated earlier. Now compile this java file. The resultant ClassA.class will be stored in the same
subdirectory.
import package1.ClassA;
class PackageTest1
{
public static void main(Sting args[ ])
{
ClassA objectA = new ClassA( );
objectA.displayA( );
}
}
This listing shows a simple program that imports the class ClassA from the package package1.
The source file should be saved as PackageTest1.java and then compiled. The source file and
the compiled file would be saved in the directory of which package1 was a subdirectory
Now let us consider another package named package2 containing again a single class as shows
below:
package package2;
public class ClassB
{
protected int m=10;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 113
Java Programming
As usual, the source file and the compiled file of this package are located in the subdirectory
package2.
class PackageTest2
{
public static void main(String args[ ])
{
ClassA objectA = new ClassA( );
ClassB objectB = new ClassB( );
objectA.dispalyA( );
objectB.displayB( );
}
}
This program may be saved as PackageTest2.java, compiled and run to obtain the results. The
output will be as under
Class A
Class B
M=10
Adding class to a package
It is simple to add a class to an existing package. Consider the following package:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 114
Java Programming
package p1;
public ClassA
{
// body of A
}
The package1 contains one public class by name A. suppose we want to add another classB to
this package. This can be done as follows:
Note that we can also add a non-public class to a package using the same procedure.
Now, the package p1 will contain both the classes A and B. A statement like
import p1. *;
will import both of them.
If we want to create a package with multiple public classes in it, we may follow the following
steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are
stored.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 115
Java Programming
3. Create classes that are to be placed in the package in separate source files and declare the
package statement
package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed,
the package would contain .class files of all the source files.
Hiding classes
When we import a package using asterisk ( * ), all public classes are imported. However, we may
prefer to “not import” certain classes. i.e we may like to hide these classes from accessing from
outside of the package. Such classes should be declared “not public”.
Example:
package p1;
public class X // public class available outside
{
// body of x
}
class Y
{
// body of Y
}
Here, the class Y which is not declared public is hidden from outside of the package p1. This
class can be seen and used only by other classes in the same package.
Now, consider the following code, which imports the package p1 that contains classes X and Y.
import p1.*;
X objectX; // classX is available here
Y objectY; // Y is not available here
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 116
Java Programming
Static import
This feature eliminates the need of qualifying a static member with the class name. The static
import declaration is similar to that of import. We can use the import statement to import classes
from packages and use them without qualifying the package. Similarly, we can use the static
import static members from classes and use them without qualifying the class name.
Before introducing the static import feature, we had to use the static member with the qualifying
classname. For Example: consider the following code that contains the static member PI;
In the above code, PI is the static member of the class, Math. So the static member PI is used in
the above program with the qualified class name called Math.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 117
Java Programming
{
MathOperation obj = new MathOperation( );
Obj.circle( 2.3);
}
}
A thread is similar to a program that has a single flow of control. It has a beginning, a body, and
an end executes commands sequentially.
A unique property of java is its support multithreading. i.e java enables us to use multiple flows
of control in developing programs. Each flow of control may be thought of as a separate tiny
program (or module) known as thread that runs in parallel to others. A program that contains
multiple flows of control is known as multithreaded program.
In figure illustrates a java program with four threads, one main and three others. The main thread
is actually the main method module, which designed to create and start the other three threads,
namely A, B and C.
Main thread
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 118
Java Programming
…………………
…………………
………………… Main method module
…………………
………..
………………… …………………
………………… ………………… …………………
………………… ………………… …………………
………………… Switching ………………… Switching …………………
……….. ……….. …………………
………..
Once initiated by the main thread, the threads A, B, and C run concurrently and share the
resources jointly. The ability of a language to support multithreads is referred to as concurrency.
Since threads in java are subprograms of a main application program and share the same memory
space, they are known as light weight threads or lightweight process.
The java interpreter handles the switching of control between the threads in such a way that it
appears they are running concurrently.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 119
Java Programming
Creating Threads
Creating threads in java is simple. Threads are implemented in the form of objects that contain a
method called run( ). The run( ) methods is the heart and soul of any thread. It makes up the
entire body of a thread and is the only method in which the thread’s behavior can be
implemented. A typical run( ) would appear as follows:
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 thread method called start( ).
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.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 120
Java Programming
We can make our class runnable as thread by extending the class java.lang.Thread. This gives
us access to all the thread methods directly. It includes the following steps:
2. Implement the run( ) method that is responsible for execution the sequence of code that
the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
The run( ) method has been inherited by the class MyThread. We have to override this method
in order to implement the code to be executed by our thread. The basic implementation of run( )
will look like this.
public void run( )
{
…….
……. // thread code here
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 121
Java Programming
…….
}
When we start the new thread, java calls the thread’s run( ) method, so it is the run( ) where all
the action takes place.
To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
athread.start( ); // invokes run( ) method
The first line instantiates the new object of class MyThread. Note that this statement just creates
the object. The thread will run this object is not running. The thread is in a newborn state.
The second line calls the start( ) method causing the thread to move into the runnable state. Then,
the java runtime will schedule the thread to run by invoking its run( ) method. Now, the thread
is said to be in the running state.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 122
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 123
Java Programming
class ThreadTest
{
public static void main(String args[ ])
{
new A( ).start( );
new B( ).start( );
new C( ).start( );
}
}
Stopping and Blocking a Thread
Stopping a Thread:
Whenever we want to stop a thread from running further, we may do so by calling its stop( )
method, like:
aThread.stop( );
This statement causes the thread to move to the dead state. A thread will also move the dead
state automatically when it reaches the end of its method. The stop( ) method may be used
when the premature death of a thread is desired.
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods.
sleep( ) //blocked for a specified time
suspend( ) //blocked until further orders
wait( ) // blocked until certain condition occurs
These methods cause the thread to go into the blocked (or not-runnable) state. The threas will
return to the runnable state when the specified time is elapsed in the case of sleep( ), the
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 124
Java Programming
resume( ) method is invoked in the case of suspend( ), and the notify( ) method is called in the
case of wait( ).
A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in figure. New Born
New Thread
Start stop
Active stop
Running yield Runnabl Dead
Thread e killed
thread
suspend resume
sleep notify stop
wait
Blocked
Idle Thread
(not runnable)
Fig: State transition Diagram of a thread
Newborn State
When we create a thread object, the thread is born and is said to be in newborn state. The thread
is not yet scheduled for running. At this state, we can do only one of the following things with it:
Schedule it for running using start( ) method
Kill it using stop( ) method.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 125
Java Programming
Is scheduled, it moves to the runnable state. If we attempt to use any other method at this stage,
an exception will be thrown.
New
Born
start stop
Runnabl
Dead
e state
State
Runnable State
The runnable state means that the thread is ready for execution and is waiting for the availability
of the processor. i.e the thread has joined the queue of threads that are waiting for execution. If
all threads have equal priority, then they are given time slots for execution in round robin
fashion, ie, first come first serve. This process of assigning time to threads is known as time-
slicing.
However, if we want a thread to relinquish control to another thread to equal priority before its
turn comes, we can do so by using the yield( ) method
yeild
…. ……..
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 126
Java Programming
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 revived by
using the resume( ) method. This approach is useful when we want to suspend a thread
for some time due to certain reasons, but do not want to kill it.
suspend
resume
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 127
Java Programming
2. It has been made to sleep. We can put a thread to sleep for a specific time period using
the method sleep (time) where time is in milliseconds. This means that the thread is out
of the queue during this time period. The thread re-enters the runnable state as soon as
this time period is elapsed.
sleep(t)
after(t)
3. It has been told to wait until some event occurs. This is done using the wait( ) method.
The thread can be scheduled to run again using the notify( ) method.
wait
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 128
Java Programming
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing its
run( ) method. It is a natural death. However, we can kill it by sending the stop message to it at
any state thus causing a premature death to it. a thread can be killed as soon it is born, or while it
is running, or even when it is in “not runnable” (blocked) condition.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 129
Java Programming
{
for (int j=1; j<=5; j++)
{
System.out.println(“\t From Thread B: j= “+j);
if ( j==3) stop( );
}
Sytem.out.println(“Exit from B”);
}
}
class ThreadMethods
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 130
Java Programming
{
public static void main(String args[ ])
{
A threadA= new A( );
B threadB= new B( );
C threadC= new C( );
Thread Exceptions
Note that the call to sleep( ) method is enclosed in a try block and followed by a catch block.
This is necessary because the sleep( ) method throws an exception, which should be caught. If
we fail to catch the exception, program will not compile.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 131
Java Programming
Whenever we call a thread method that is likely to throw an exception, we have to supply an
appropriate exception handler to catch it. The catch statement may take one of the following
forms:
catch (ThreadException e)
{
…
… // killed thread
}
catch (InterruptedException e)
{
…
… // cannot handle it in the current state
}
catch(IllegalArgumentException e)
{
…
… // ileegal method argument
}
catch(Exception e)
{
…
… // Any other
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 132
Java Programming
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 us to set the priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority is set. The thread class defines
several priority constants:
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10. Note that the
default setting is NORM_PRIORITY.
Synchronization
We have seen threads that use their own data and methods provided inside their run( ) methods.
What happens when they try to use data and methods outside themselves? On such occasions,
they may compete for the same resources and may lead to serious problems. For example, one
thread may try to read a record from a file while another is still writing to the same file.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 133
Java Programming
Depending on the situation, we may get strange results. Java enables us to overcome this
problem using a technique known as synchronization.
In case of java, the keyword synchronized helps to solve such problems by keeping a watch on
such locations. For example, the method that will read information from a file and the method
that will update the same file may be declared as synchronized. Example:
synchronized void update( )
{
…. //code here is synchronized
….
}
When we declare a method synchronized, java creates a “monitor” and hands it over to the
thread that calls the method first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of code. A monitor is like a key and the thread that holds the
key can only open the lock.
Whenever a thread has completed its work of using synchronized method, it will hand over the
monitor to the next thread that is ready to use the same resources.
Thread A
synchronized method2( )
{
synchronized method1( )
{
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 134
Java Programming
…..
}
}
Thread B
synchronized method1( )
{
synchronized method2( )
{
…..
}
}
The Runnable interface declares the run( ) method that is required for implementing threads in
our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
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 start( ) method to run the thread.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 135
Java Programming
}
}
class RunnableTest
{
public static void main(String args[ ])
{
X runnable=new X( );
Thread thread=new Thread (runnable);
threadX.start( );
system.out.println(“End of main thread”);
}
}
A mistake might lead to an error causing to program to produce unexpected results. Errors are
the wrongs that can make a program go wrong.
Types of Errors
Errors may broadly classify into two categories: Compile-time errors
Run-time errors
Compile-Time Errors
All 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 an error, it will not create the
.class file. It is therefore necessary that we fix all the errors before we can successfully compile
and run the program.
class Error1
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 136
Java Programming
{
public static void main(String arg[ ] )
{
System.out.println(“Hello Java!”) // missing ;
}
}
The java compiler does a nice job of telling us where the errors are in the program. For ex, if we
have missed the semicolon at the end of print statement in the program, the following message
will be displayed in the screen:
Most of the compile-time errors are due to trying mistakes. Typographical errors are hard to find.
We may have to check the code word by word, or even character by character. The most
common problems are:
Missing semicolons
Missing or mismatch of brackets in classes 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 = = operator
Run-time Errors
Sometimes, a program may compile successfully creating the .class file but may not return
properly. Such programs may produce wrong results due to wrong logic or may terminate due to
errors such as stack overflow.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 137
Java Programming
The below program illustrates how run time error causes termination of execution of the
program.
class Error2
{
public static void main(String args[ ])
{
int a=10;
int b=5;
int c=5;
int x=a/(b+c);
System.out.println(“ y =”+y);
}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 138
Java Programming
This program is syntactically correct and therefore does not cause any problem during
compilation. However, while executing, it displays the following message and stops without
executing further statements.
java.lang.ArithmeticException: / by zero
at Error2.main(Error2.java:10)
When java run-time tries to execute a division by zero, it generates an error condition, which
causes the program to stop after displaying an appropriate message.
Exceptions
An Exception is a condition that is caused by a run-time error in the 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 object is not caught and handled properly, the interpreter will display an error
message as shown in the output of program 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 purpose of exception handling mechanism is to provide a means to detect and report an
“exceptional circumstances” so that appropriate action can be taken. The mechanism suggests
incorporation on a separate error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred ( Throw the exception)
3. Receive the error information (catch the exception)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 139
Java Programming
The error handling code basically consists of two segments, one to detect errors and to throw
exceptions and the other to catch exceptions and to take appropriate actions,
When writing programs, we must always be on the lookout for places in the program where an
exception could be generated. Some common exceptions that we must watch out for catching are
listed in table below:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 140
Java Programming
The basic concepts of exception handling are throwing an exception and catching it. this is
illustrated in figure:
try block
Statement that
Exception object
causes an exception
creator
catch block
Java uses a keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception. A catch block defined by the keyword catch “catches” the exception
“thrown” by the try block and handles it appropriately. The catch block is added immediately
after the try block.
The following example illustrates the use of simple try and catch statements.
……..
……..
try
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 141
Java Programming
{
Statement; // generates an exception
}
catch (Exception–type e)
{
Statement; // process the exception
}
…….
…….
The try block can have one or 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 too can have one or more statements that are necessary to process the execution.
Remember that every try statement should be followed by at least one catch statement;
otherwise compilation error will occur.
class Error3
{
public static void main(String args[ ])
{
int a = 10;
int b = 5;
int c = 5;
int x, y;
try
{
x= a / (b/c); // exception here
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 142
Java Programming
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
y= a / (b+c);
System.out.println(“ y= “+y);
}
}
This displays the following output:
Divisible by zero
y=1
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 143
Java Programming
.
catch(Exception-type-n e)
{
Statement; //process excpetion type n
}
….
….
When an exception in a try block is generated, the java treats the multiple catch statements. The
first statement whose parameter matches with the exception object will be executed, and the
remaining statements will be skipped.
Note that java does not require any processing of the exception at all. We can simply have a
catch statement with an empty block to avoid program abortion.
Example:
catch(Exception e);
The catch statement simply ends with a semicolon, which does nothing. This statement will catch
an exception and then ignore it.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 144
Java Programming
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“wrong data type”);
}
int y= a[1] / a[0];
System.out.println(“y= “ +y);
}
}
The above program uses a chain of catch blocks and, when run, produces the following output.
Array index error
y=2
Note that the array element a[2] does not exist because array a is defined to have only two
elements, a[0] and a[1]. Therefore, the index 2 is outside the array boundary thus causing the
block
catch(ArrayIndexOutOfBoundsException e)
to catch and handle the error. Remaining catch blocks are skipped.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 145
Java Programming
Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements. finally block can be used to
handle any exception generated within a try block. It may be added immediately after the try
block or after the last catch block as shown below:
try try
{ {
….. ….
….. ….
} or }
finally catch(…..)
{ {
….. ….
….. ….
} }
catch( …. )
{
….
….
}
.
.
finally
{
…..
}
When finally block is defined, this is guaranteed to execute, regardless of whether or not in
exception is thrown. As a result, we can use it to perform certain house-keeping operations such
as closing files and releasing system resources.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 146
Java Programming
In program, we may include the last two statements include a finally block as shown below:
finally
{
int y= a[1] / a[0];
System.out.println(“y = “+y);
}
When we would like to throw our own exceptions. We can do this by using the keyword throw
as follows:
throw new Throwable_subclass;
The below program demonstrates the use of a user-defined subclass of Throwable class. Note
that Exception is a subclass of Throwable and therefore MyException is a subclass of
Throwable class. An object of a class that extends Throwable can be thrown and caught.
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 147
Java Programming
class TestMyException
{
public static void main(String args[ ])
{
int x=5, y=1000;
try
{
float z=(float) x / (float) y;
if (z < 0.01)
{
throw new MyException(“Number is too small”);
}
}
catch (MyException e)
{
System.out.println(“ caught my exception”);
System.out.println(e.getMessage( ));
}
finally ( )
{
System.out.println(“I am always here”);
}
}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 148
Java Programming
The exception handling mechanism can be used to hide errors from rest of the program. It is
possible that the programmers may misuse this technique for hiding errors rather than debugging
the code. Exception handling mechanism may be effectively used to locate the type and place of
errors. Once we identify the errors, we must try to find out why these errors occur before we
cover them up with exception handlers.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 149
Java Programming
Applets are small java programs that are primarily used in internet computing. They can be
transported over the internet from one computer to another and run using the Applet Viewer or
any web browser that supports java.
We can embed applets into web pages in two ways. One, we can write our own applets and
embed them into web pages. Second, we can download an applet from a remote computer system
and then embed it into a web page.
An applet developed locally and stored in a local system is known as a local applet.
A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet.
Although both the applets and stand-alone applications are java programs, there are significant
differences between them. Applets are not full-featured application programs. They are usually
written to accomplish a small task or a component of a task. Since they are usually designed for
use on the internet, they impose certain limitations and restrictions in their design.
Applets do not use the main( ) method for initiating the execution of the code. Applets,
when loaded, automatically call certain methods of Applet class to start and execute the
applet code.
Unlike, stand-alone applications, applets cannot be run independently. They are run from
inside a web page using a special feature known as HTML tag.
Applets cannot read from or write to these files in the local computer.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 150
Java Programming
Before we try to write applets, we must make sure that java is installed properly and also ensure
that either the java appletviewer or java enabled browser is available. The steps involved in
developing and testing in applet are:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 151
Java Programming
The paint( ) method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics or sound. The paint( )method, which
requires a Graphics object as an argument is defined as follows:
This requires that the applet code imports the java.awt package that contains the Graphics class.
import java.awt.*;
import java.applet.*;
………..
………..
public class appletclassname extends Applet
{
……….
public void paint(Graphics g)
{
…….
…….
}
…….
}
The appletclassname is the main class for the applet. When the applet is loaded, java creates an
instance of this class, and then a series of Applet class methods are called on that instance to
execute the code.
import java.awt.*;
import java.applet.*;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 152
Java Programming
Every java applet inherits a set of default behaviors from the Applet class. As a result, when an
applet is loaded, it undergoes a series of changes in its state as shown in figure:
start( )
stop( )
Runnin
g Idle
display stopped
paint( ) start( )
destroy( )
Exit of Browser
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 153
Java Programming
Initialization State
Applet enters the initialization state when it is first loaded. This is achieved by calling the init( )
method of Applet class. The applet is born. At this stage, we may do the following, if required.
The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors
mentioned above, we must override the init( ) method.
Running State
Applet enters the running state when the system calls the start( ) method of Applet class. This
occurs automatically after the applet is initialized. Note that, unlike init( ) method, the start( )
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 154
Java Programming
method may be called more than once. We may override the start( ) method to create a thread to
control the applet.
An applet becomes idle when it is stopped from running. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the stop(
) method explicitly. If we use a thread to run the applet, then we must use stop( ) method to
terminate the thread. We can achieve this by overriding the stop( ) method:
Dead State
An Applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage
occurs only once in the applet’s life cycle.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 155
Java Programming
…. // Action
….
}
Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint( )
method is called to accomplish this task. Almost every applet will have a paint( ) method.
Executable Applet is nothing but the .class file of the applet, which is obtained by compiling the
source code of the applet. Compiling an Applet is exactly the same as compiling an application.
Therefore, we can use the java compiler to compile the applet.
Let us consider the HelloJava applet created. this applet has been stored in a file called
HelloJava. Here are the steps required for compiling the HelloJava applet.
1. Move to the directory containing the source code and type the following command:
javac HelloJava.java
2. The compiled output file called HelloJava.class is placed in the same directory as the
source.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 156
Java Programming
3. If any error message is received, then we must check for errors, correct them and compile
the applet again.
A web page is basically made up of text and HTML tags that can be interpreted by a Web
browser or an applet viewer. A Web page is also known as HTML page or HTML document.
Web pages are stored using a file extension .html such as MyApplet.html. Such files are
referred to as HTML files. HTML files should be stored in the some directory as the compiled
code of the applets.
A web page is marked by an opening HTML tag <HTML> and a closing HTML tag </HTML>
and is divided into the following three major sections:
1. Comment section (Optional)
2. Head section (Optional)
3. Body section
a. Comment section
This section contains comments about the web page. A comment line begins with a <! and ends
with a >. Web browsers will ignore the text enclosed between them.
b. Head section
The head section is defined with a starting <HEAD> tag and a closing </HEAD> tag. This
section usually contains a title for the web page as shown below:
<HEAD>
<TITLE> WELCOME TO JAVA APPLET </TITLE>
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 157
Java Programming
</HEAD>
The text enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the web
browser when it display the page. The head section is also optional.
<HTML>
<!
….
>
<HEAD>
Title tag
</HEAD>
</HTML>
<BODY>
Applet tag
</BODY>
<BODY>
<CENTER>
<H1> Welcome to the World of Applets <H1>
<CENTER>
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 158
Java Programming
<BR>
<APPLET …>
</APPLET>
<BODY>
Applet Tag
Note that we have include a pair of <APPLET…> and <APPLET> tag in the body section. The
<APPLET…> tag supplies the name of the applet to be loaded and tells the browser how much
space the applet requires. The ellipsis in the tag <APPLET…> indicates that it contain certain
attributes that must specified. The <APPLET> tag given below specifies the minimum
requirements to place the HelloJava applet on a web page:
<APPLET
CODE = HelloJava.class
WIDTH = 400
HEIGHT =200 >
</APPLET>
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 159
Java Programming
Now we can put together the various components of the Web page and create a file known as
HTML file. Insert the <APPLET> tag in the page at the place where the output of the applet
must appear. Following is the content of the HTML file that is embedded with the <APPLET>
tag of our HelloJava applet.
<HTML>
<! This page includes a welcome title in the title bar and also displays a welcome message. Then
it specifies the applet to be loaded and executed.
>
<HEAD>
<TITLE>
Welcome to Java Applets
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> WELCOME TO THE WORLD OF APPLETS </H1>
</CENTER>
<BR>
<CENTER>
<APPLET
CODE = HelloJava.class
WIDTH = 400
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 160
Java Programming
HEIGHT = 200>
</APPLET>
</CENTER>
</BODY>
</HTML>
We must name this file as HelloJava.html and save it in the same directory as the compiled
applet.
HelloJava.java
HelloJava.class
HelloJava.html
If we use java-enabled Web browser, we will be able to see the entire Web page containing the
applet. If we use the appletviewer tool, we will only see the applet output.
Note that the argument of the appletviewer is not the .java file or the .class file, but rather .html
file.
We can supply user-defined parameter to an applet using <PARAM…> tag has a name attribute
such as color, and a value attribute such as red. Inside the applet code, the applet can refer to
that parameter by name to find its value. For example, we can change the color of the text
displayed to red by an applet using a <PARAM…> tag as follows:
<APPLET …..>
<PARAM = color VALUE = “red”>
</APPLET>
Similarly we can change the text to be displayed by an applet by supplying new text to the applet
through a <PARAM …> tag as follows:
Passing parameters to an applet code using <PARAM> tag is something similar to passing
parameters to the main( ) method using command line arguments. To set up and handle
parameters, we need to do two things:
1. Include appropriate <PARAM..> tags in the HTML document.
2. Provide code in the applet to parse these parameters.
Parameters are passed on an applet when it is loaded. We can define the init( ) method in the
applet to get hold of the parameters defined in the <PARAM> tags. This is done by using the
getParameter( ) method, which takes one string argument representing the name of the
parameter and returns a string containing the value of that parameter.
The below program shows another version of HelloJava applet. Compile it so that we have a
class file.
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 162
Java Programming
{
String str;
public void init( )
{
str= getparameter(“String”):
if(str==null)
str = “Java”;
str= “Hello”+ str;
}
public void paint(Graphics g )
{
g.drawString(str, 10,100);
}
}
Now let us create HTML file that contains this applet. Program shows a web page that passes a
parameter whose NAME is “string” and whose VALUE is APPLET!” to the applet
HelloJavaParam.
<HTML>
< ! Parameterized HTML file>
<HEAD>
<TITLE> welcome to java applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE = HelloJavaParam.class
WIDTH = 400
HIGHT = 200>
<PARAM NAME = “string”
VALUE = “Applet!”>
</APPLET>
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 163
Java Programming
</BODY>
</HTML>
Save this file as HelloJavaParam.html and then run the applet using the applet viewer as follows:
appletviewer HelloJavaParam.html
We can align the output of the applet using the ALIGN attribute. This attribute can have one of
the nine values:
For example: ALGN = LEFT will display the output at the left margin of the page.
The below table list important HTML tags and their functions:
Tags Function
<HEAD> …</HEAD> This tag may include details about the web page. Usually contains
<TITLE> tag within it.
<TITLE>….</TITLE> The text contained in it will appear in the title bar of the browser.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 164
Java Programming
<BODY>….</BODY> This tag contains the main text of the web page. It is the place
where the <APPLET> tag is declared
<H1>….</H1> Header tags. Used to display headings. <H!> creates the largest
font header, while <H6> creates the smallest one.
<H6>….</H6>
<BR> Line break tag. This will skip a line. Does not have an end tag.
<P> para tag. This tag moves us to the next line and starts a paragraph
of text. No end tag is necessary.
<FONT…> …</FONT> we can change the color and size of the text that lies in between
<FONT> and </FONT > tags using COLOR and SIZE attributes in
the tag <FONT…>
<!.....> Any text starting with a <! Mark and ending with a > mark is
ignored by the web browser. We may add comments here. A
comment tag may be placed anywhere in a web page.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 165
Java Programming
In applets, we can display numerical values by first converting them into strings and then using
the drawstring( ) method of Graphics class. We can do this easily by calling the ValueOf( )
method of String class.
Once text fields are created for receiving input, we can type the values in the fields and edit
them.
Next step is to retrieve the items from the fields for display of calculations. Remember, the text
fields contain items in string form. They need to be converted to the right form, before they are
used in any computations. The results are then converted back to strings for display.
{
TextField text1, text2;
public void init( )
{
text1= new TextField (8);
text2 = new TextFiled(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, s;
g.drawString(“Input a number in each box”. 10,50);
try
{
s1= text1.getText( );
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 167
Java Programming
x = Integer.parseInt(s1);
s2=text2.getText( );
y = Integer.parseInt(s2);
}
catch(Exception ex)
{
}
z=x+y;
s= String.valueOf(z);
g.drawString(“THE SUM IS :”, 10, 75);
g.drawString(s, 100, 75);
}
public Boolean action( Event e, Object o)
{
repaint( );
return true;
}
}
Run the applet UserIn using the following steps:
1. Type and save the program (.java file)
2. Compile the applet (.class file)
3. Write HTML document (.html file)
<html>
<applet
code= UserIn.class
width=300
height=200>
</applet>
</html>
4. Use the appletviewer to display the results.
Introduction
One of the most important features of java is its ability to draw graphics. We can write java
applets that draw lines, figures of different shapes, images, and text in different fonts and styles.
We can also incorporate different colors in display.
Every applet has its own area of the screen known as canvas, where it creates its display. The
size of an applet space is decided by attributes of the <APPLET…> tag. A java applet draws
graphical image inside its space using the coordinate system.
Java coordinate system has the origin(0,0) in the upper-left corner. Positive x values are to the
right, and positive y values are to the bottom. The values of coordinates x and y are in pixels.
Java Graphics class includes methods for drawing many different types of shapes, from simple
lines to polygons to text in a variety of fonts. We have already seen how to display text using the
point( ) method and a Graphics object.
To draw a shape on the screen, we may call one of the methods available in the Graphics class.
The table shows the most commonly used drawing methods in the Graphics class. All the
drawing methods have arguments representing end points, corners, or starting locations of a
shape as values in the applet’s coordinate system.
(0,0) (80,0)
(20,20)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 169
Java Programming
(60,60)
(0,80)
The below table shows the drawing methods of the Graphics Class:
Method Description
clearRect( ) Erases a rectangle area of the canvas
copyArea( ) Copies a rectangular area of the canvas to another area
drawArc( ) Draws a hollow arc
drawLine( ) Draw a straight line
drawOval( ) Draw a hollow oval
drawPolygon( ) Draws a hollow polygon
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners
drawString( ) Draws a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled oval
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws a filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font
setColor( ) Sets the drawing color
setFont( ) Sets the font
The simplest shape we can draw with the Graphics class is a line. The drawLine( )
method takes two pair of coordinates, (x1, y1) and (x2, y2) as arguments and draws a line
between them. For Example: the following statement draws a straight line from the coordinate
point (10,10) to (50,50).
g.drawLine(10,10, 50,50);
Similarly, we can draw a rectangle using the drawRect( ) method. This method takes
four arguments. The first two represents the x and y coordinates of the top left corner of the
rectangle and remaining two represent the width and height of the rectangle. For example: the
statement with draw a rectangle starting at (10, 60) having a width of 40 pixels and a height of 30
pixels.
g.drawRect(10, 60, 40, 30);
(x, y) width
height
Rectangle
We can draw a solid box by using the method fillRect( ). This also takes four parameters
corresponding to the starting point, the width and the height of the rectangle. For example: the
statement, g.fillRect(60, 10, 30, 80);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 171
Java Programming
import java.awt.*;
import java.applet.*;
public class LineRect extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10, 50,50);
g.drawRect(10,60, 40, 30);
g.fillRect(60, 10, 30, 80);
g.drawRoundRect(10, 100, 80, 50, 10, 10);
g.fillRoundRect(20, 110, 60, 30, 5,5);
g.drawLine(100, 10, 230, 140);
g.drawLine(100,140,230,10);
}
}
<APPLET
CODE=LineRect.class
WIDTH=250
HEIGHT=200>
</APPLET>
The drawOval( ) method can be used to draw a circle or an ellipses. The drawOval( ) methods
takes four arguments: the first two represent the top left corner of the imaginary rectangle and the
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 172
Java Programming
other two represent the width and height of the oval itself. Note that if the width and height are
the same, the oval becomes a circle. The oval’s coordinates are actually the coordinates of
enclosing rectangles.
height
width
Like rectangle methods, the drawOval( ) method draws outline of an oval, and the fillOval( )
method draws a solid oval. The code segment shown below draws a filled circle within an oval.
Drawing Arcs
An arc is a part of an oval. In fact, we can think of an oval as a series of arcs that are connected
together in an orderly manner. The drawArc( ) designed to draw arcs takes six arguments. The
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 173
Java Programming
first four are the same as the arguments for drawOval( ) method and the last two represents the
starting angle of the arc and the number of degrees around the arc.
90’
180’
180’ 0’
270’
Fig: Arc as a part of an oval
We can also draw an arc in backward direction by specifying the sweep angle as negative. For
example: if the last argument is -135’ and the starting angle is 45’, then the arc is drawn as
shown below:
45’
-135’
270’
Fig: Drawing an arc in clockwise directions
We can use the fillArc( ) method to fill the arc. Filled arcs are drawn as if they were sections of a
pie. Instead of joining the two end points, they are joined to the center of the oval.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 174
Java Programming
Drawing Polygons
Polygons are shape with many sides. A polygon may be considered a set of lines connected
together. The end of the first line is the beginning of the second line, the end of the second line is
the beginning of the third and so on. This suggests that we can draw a polygon with a sides using
the drawLine( ) method n times succession. For example: the code given below will draw a
polygon of three sides.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 175
Java Programming
{
g.drawLine(10,20,170,40);
g.drawLine(170,40,80,140);
g.drawLine(80,140, 10,20);
}
We can draw polygons more conveniently using the drawPolygon( ) method of Graphics class.
This method takes three arguments:
An array of integers containing x coordinates
An array of integers containing y coordinates
An integer for the total number of points
It is obvious that x and y arrays should be of the same size and we must repeat the first point at
the end of the array for closing the polygon.
Ex: public void paint(Graphics g)
{
int xPoints [ ] = {10,170,80,10};
int yPoints [ ] = {20, 40, 140, 20};
int nPoints [ ] = xPoints.length;
g.drawPolygon (xPoints, yPoints , nPoints);
}
We can also draw a filled polygon by using the fillPolygon( ) method.
W an applet to draw polygons
import java.awt.*;
import java.applet.*;
public class Poly extends Applet
{
public void paint(Graphics g)
int x1 [ ] = {20, 120, 220, 20};
{
int y1 [ ] = {20, 120, 20, 20}; g.drawPolygon(x1,y1,n1);
int n1 =4; g.fillPolygon(x2,y2,n2);
}
int x2 [ ] ={120, 220, 220, 120};
}
int y2 [ ] = {120, 20, 220, 120};
int n2 = 4;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 176
Java Programming
Introduction
A file is a collection of related records placed in a particular area on the disk. A record is
composed of several fields and a field is a group of characters. Characters in java are Unicode
characters composed of two bytes, each byte containing eight binary digits, 0 or 1.
Concept of Streams
Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices. A stream presents a uniform, easy-to-use,
object oriented interface between the program and the input/output devices.
A stream in java is a path along which data flows. It has a source(of data) and a destination (for
that data). Both the source and the destination may be physical devices or programs or other
streams in the same program.
The concept of sending data from one stream to another has made streams in java a powerful tool
for file processing. We can build a complex file processing sequence using a series of simple
stream operations. This feature can be used to filter data along the pipeline of streams so that we
obtain data in a desired format.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 177
Java Programming
Java streams are classified into two basic types: namely, input stream and output stream. An
input stream extracts (reads) data from the source file and sends it to the program. Similarly, an
output stream takes data from the program and sends it to the destination file.
Stream classes
The java.io package contains large number of classes that provide capabilities for processing all
types of data. These classes may be categorized into two groups based on the data type on which
they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
Java Stream
Classes
Input
Java Programming
Input stream classes: Input stream classes that are used to read 8-bit bytes include a super class
known as InputStream and a number of sub classes for supporting various input-related
functions.
Object
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 179
Java Programming
InputStream
FileInputStream SequenceInputStream
PipeInputStrea ObjectInputStream
m
ByteArrayInputStream StringBufferInputStream
FilterInputStream
BufferedInputStream PushbackInputStream
DataInputStream
DataInput
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 180
Java Programming
The super class InputStream is an abstract class, and, therefore, we cannot create instances of
this class. Rather, we must use the subclasses that inherit from this class.
The InputStream class defines methods for performing input functions such as
Reading bytes
Closing streams
Method Description
3. read (byte b[ ], int n, int m) Reads m bytes into b starting from the nth byte
Output Stream Classes: Output stream classes are derived from the base class OutputStream.
The output stream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 181
Java Programming
The OutputStream includes methods that are designed to perform the following tasks:
writing bytes
closing streams
flushing streams
Object
OutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 182
Java Programming
Method Description
3. write(byte b[ ], int n, int m) writes m bytes from array b starting from nth byte
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 183
Java Programming
Character stream classes were not a part of the language when it was released in 1995. They
were added later when the version 1.1 was announced. Character streams can be used to read and
write 16-bit Unicode characters. Like byte streams, there are two kinds of character stream
classes, namely, reader stream classes and writer stream classes.
Reader stream classes are designed to read character from the files. Reader class is the base
class for all other classes in this group. These classes are functionally very similar to the input
stream classes, expect input streams use bytes as their fundamental unit of information, while
reader streams use characters.
Object
Reader
BufferedReader StringReader
CharArrayReade PipeReader
r
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 184
Java Programming
InputStreamReader FilterReader
FileReader PushbackReader
The Reader class contains methods that are identical to those available in the InputStream
class, except Reader is designed to handle characters. Therefore, reader classes can perform all
the functions implemented by the input stream classes.
Like output stream classes, the writer stream classes are designed to perform all output
operations on files. Only difference is that while output stream classes are designed to write
bytes, the writer stream classes are designed to write characters.
The writer class is an abstract class which acts as a base class for all the other writer stream
classes. This base class provides support for all output operations by defining methods that are
identical to those in OutputStream class.
Object
writer
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 185
Java Programming
PrintWriter
BufferedWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
OutputStreamWriter
FileWriter
Using Streams
The various types of input and output stream classes used for handling both the 16-bit characters
and 8-bits bytes. Although all the classes are known as i/o classes, not all of them are used for
reading and writing operations only. Some perform operations such as buffering, filtering, data
conversion, counting and concatenation while carrying out i/o tasks.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 186
Java Programming
The java.io package supports many other classes for performing certain specialized functions.
They include among others:
Stream Tokenizer
The RandomAccessFile enables us to read and write bytes, text and java data types to any
location in a file (when used with appropriate access permissions). This class extends object
class and implements DataInput and DataOutput interfaces. This forces the
RandomAccessFile to implement the methods described in both these interfaces.
Object
Interface Interface
DataInput DataOutput
RandomAccessFile
The class Stream Tokenizer, a subclass of object can be used for breaking up a stream of text
from an input text file into meaningful pieces called tokens. The behavior of the Stream
Tokenizer class is similar to that of the String Tokenizer class (of java.util package) that
breaks a string into its component tokens.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 187
Java Programming
The java.io package includes a class known as the File class that provides supports for creating
files and directories. The class includes several constructs for instantiating the File objects. This
class also contains several methods for supporting the operations such as
Creating a file
Opening a file
Closing a file
Deleting a file
Getting the name of a file
Getting the size of a file
Checking the existence of a file
Renaming a file
Checking whether the file is writable
Checking whether the file is readable
When creating files and performing i/o operations on them, the system may generate i/o related
exceptions.
EOFException signals that an end of the file or end of stream has been reached
unexpectedly during input
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 188
Java Programming
Each i/o statement or group of i/o statements must have an exception handler around it as shown
below or the method must declare that it throws an IOException.
try
{
…………
………… // I/O statements
}
catch(IOException e)
{
………….. // Message output statement
}
Creation of Files
If we want to create and use a disk file, we need to decide the following about the file and its
intended purpose:
Suitable name for the file
Data type to be stored
Purpose (reading, writing, or updating)
Method of creating the file
A filename is a unique string of characters that helps identify a file on the disk. The length of a
filename and characters allowed are dependent on the OS on which the Java program is
executed. A filename may contain two parts, a primary name and an optional period with
extension. Examples:
input.dat salary
test.doc student.txt
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 189
Java Programming
inventory rand.dat
Data type is important to decide the type of file stream classes to be used for handling the data.
We should decide whether the data to be handled is in the form of characters, bytes or primitive
type.
The purpose of using a file must also be decided before using it. For example, we should know
whether the file is created for reading only, or writing only, or both the operations.
As we know, for using a file, it must be opened first. This is done by creating a file stream and
then liking it to the filename. A file stream can be defined using the classes of
Reader/InputStream for reading data and Writer/OutputStream for writing data.
Source or
Destination Characters Bytes
Read Write Read Write
Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream
File FileReader FileWriter FileInputStream FileOutputStream
Pipe PipedReader PipedWriter PipedInputSttream PipedOutputStream
There are two ways of initializing the file stream objects. All of the constructors require that we
provide the name of the file either directly, or indirectly by giving a file object that has already
been assigned a filename.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 190
Java Programming
The indirect approach uses a file object that has been initialized with the desired filename. This
is illustrated by the following code:
…………
…………
File inFile; //declare a file object
InFile = new File(“test.dat”) // Assign the filename to
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 191
Java Programming
fis “test.dat”
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 192
Java Programming
int ch;
while ( (ch = ins.read( )) != -1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close( );
outs.close( );
}
Catch(IOException e)
{}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 193
Java Programming
}
}
It is possible to combine two or more input stream into a single input stream. This process is
known as concatenation of files and is achieved using the SequenceInputStream class. One of
the constructors of this class takes two InputStream objects as arguments and combines them to
construct a single input stream.
Java also supports creation of buffers to store temporarily data that is read from or written to a
stream. The process is known as buffere i/o operation. A buffer sits between the program and the
source or destination and functions like a filter. Buffers can be created using the
BufferedInputStream and BufferedOutputStream.
The Random Access File class supported by the Java.io package allows us to create files that
can be used for reading and writing data with random access. That is, we can “jump around” in
the file while using the file. Such files are known as random access files.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 194
Java Programming
A file can be created and opened for random access by giving a mode string as a parameter to the
constructor when we open the file. We can use one of the following two mode strings:
“r” for reading only
“rw” for both reading and writing
System.out.println(file.readerChar( ));
System.out.println(file.readInt( ) );
System.out.println(file.readDouble( ));
file.seek(2);
System.out.println(file.length( ));
File.writeBoolean(false( );
file.seek(4);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 195
Java Programming
System.out.println(file.readBoolean( ));
file.close( );
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 196
Java Programming
Object Streams: we can read and write characters, bytes and primitive data types. It is
also possible to perform input and output operations on objects using the object streams.
The object streams are created using the ObjectInputStream and ObjectOutputStream
classes. In this case, we may declare records as objects and use the object classes to write
and read these objects from files. As mentioned in the beginning, this process is known as
object serislization.
Piped Stream: Piped stream provide functionality for threads to communicate and
exchange data between them. There are two threads use pipes for communication. The
write thread sends data to the read thread through a pipeline that connects an object of
PipedInputStream to an object of PipedOutputStream. The objects inputPipe and
outputPipe are connected using the connect( ) method.
Filtered Streams: Java supports two abstract classes, namely, FilterInputStream and
FilterOutputStream that provide the basic capability to create input and output streams
for filtering input/output in a number of ways. These streams, known as filters, sits
between an input stream and an output stream and perform some optional processing on
the data they transfer.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 197
Java Programming
Event handling
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 198
Java Programming
• time intervals
– We can also implement simple GUI objects in Java such as buttons.
• The way event handling works is this:
– Any operating system that supports GUIs constantly monitors events such as
keystrokes and mouse clicks.
– The operating system reports these events to programs that are running.
– The programs decide what, if anything, they want to do with these events.
• In Java, you control how to handle these events by setting up event source objects and
event listener objects.
• Event sources are objects like buttons and scroll bars.
• Event listeners can be any object.
• Here is how to set up event sources and listeners:
– A listener object is an instance of a class that implements a listener interface.
– An event source is an object that can register listener objects and send them event
objects.
– The event source sends out event objects to all the registered listeners when that
event occurs.
– The listener objects will then use information in the event object to determine
their reaction to the event.
Registering Listeners
• So, how do you set this up in Java.
• First, you create an event source object like a button.
– JButton button = new JButton(“Ok”);
• Second, instantiate an object that implements a listener interface.
– ActionListener listener = new ColorAction(Color.red);
– where ColorAction implements ActionListener
• Third, register the listener object with the event source object.
– button.addActionListener(listener);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 199
Java Programming
• Note: JButton objects require an ActionListener interface. Other objects may require
different interfaces
– The ActionListener interface requires the programmer to override the
actionPerformed method that accepts an Event object.
• So, now when the button is clicked, the JButton object creates an ActionEvent object
(which is a subclass of an Event object) and calls the actionPerformed method in listener
object (ColorAction).
• Note, multiple listeners can be registered to one event source.
• An object that implements the WindowListener interfact must override these methods:
– void windowOpened(WindowEvent e);
– void windowClosing(WindowEvent e);
– void windowClosed(WindowEvent e);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 200
Java Programming
• To make it easier for programmers, the designers of Java supplied adapter classes.
– Each AWT listener interface with more than one method comes with a companion
adapter class.
– These adapter classes implement all the methods in the interface but does nothing
with them.
– This means that the adapter classes satisfy all the technical requirements for
implementing the listener interface.
– You can then just extend your class from these adapter classes if you don’t need
to extend it from anything else.
Adapter Classes
• The adapter class for the WindowListener interface is WindowAdapter. You can use it
like this:
– class Terminator extends WindowAdapter {…}
• Creating a listener class that extends the WindowAdapter is even easier than that. There is
no need to give a name to the listener object.
– frame.addWindowListener(new Terminator());
• You can go even further by using an anonymous inner class:
– frame.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 201
Java Programming
}
});
• You can see how much less code there is.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 202
Java Programming
– WindowEvent
• (the window state changed)
– ContainerEvent
• (a component has been added or removed)
Java – Networking
The term network programming refers to writing programs that execute across multiple devices (computers),
in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-
level communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of
data to be transmitted between applications.
Socket Programming: This is most widely used concept in Networking and it has been explained in
very detail.
URL Processing: This would be covered separately. Click here to learn about URL Processing in
Java language.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 203
Java Programming
Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client program creates
a socket on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for
the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
The server instantiates a ServerSocket object, denoting which port number communication is to occur
on.
The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and port
number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of
communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an
OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and
the client's InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are
following usefull classes providing complete set of methods to implement sockets.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 204
Java Programming
Attempts to create a server socket bound to the specified port. An exception occurs if the port is
already bound by another application.
Similar to the previous constructor, the backlog parameter specifies how many incoming clients
to store in a wait queue.
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on
Creates an unbound server socket. When using this constructor, use the bind() method when you
are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it means that your application has successfully
bound to the specified port and is ready for client requests.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 205
Java Programming
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you.
Waits for an incoming client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocks indefinitely
Sets the time-out value for how long the server socket waits for a client during the accept().
Binds the socket to the specified server and port in the SocketAddress object. Use this method if
you instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this
new Socket. A TCP connection now exists between the client and server, and communication can begin.
The Socket class has five constructors that a client uses to connect to a server:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 206
Java Programming
This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.
3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.
4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String
5 public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to
connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and
server have a Socket object, so these methods can be invoked by both the client and server.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 207
Java Programming
This method connects the socket to the specified host. This method is needed only when you
instantiated the Socket using the no-argument constructor.
This method returns the address of the other computer that this socket is connected to.
Returns the input stream of the socket. The input stream is connected to the output stream of the
remote socket.
Returns the output stream of the socket. The output stream is connected to the input stream of the
remote socket
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 208
Java Programming
Closes the socket, which makes this Socket object no longer capable of connecting again to any
server
4 String getHostAddress()
5 String getHostName()
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 209
Java Programming
7 String toString()
import java.net.*;
import java.io.*;
try
+ client.getRemoteSocketAddress());
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 210
Java Programming
DataOutputStream out =
new DataOutputStream(outToServer);
+ client.getLocalSocketAddress());
DataInputStream in =
new DataInputStream(inFromServer);
client.close();
}catch(IOException e)
e.printStackTrace();
import java.net.*;
import java.io.*;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 211
Java Programming
serverSocket.setSoTimeout(10000);
while(true)
try
serverSocket.getLocalPort() + "...");
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
+ server.getLocalSocketAddress() + "\nGoodbye!");
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 212
Java Programming
server.close();
}catch(SocketTimeoutException s)
break;
}catch(IOException e)
e.printStackTrace();
break;
try
t.start();
}catch(IOException e)
e.printStackTrace();
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 213
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 214
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 215
Java Programming
Swing Features
Besides the large array of components in Swing and the fact that they are lightweight, Swing
introduces many other innovations.
Borders
We can draw borders in many different styles around components using the setborder( ) method.
Graphics Debugging
Tooltips
We can use the setToolTipText method of JComponent to give components a tooltip, one of
those small windows that appear when the mouse hovers over a component and gives
explanatory text.
Easy Scrolling
We can set the appearance of applets and applications to one of three standard looks. Windows,
Motif (Unix) or Metal (Standard swing look).
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 216
Java Programming
One of the differences between the AWT and Swing is that, when we redraw items on the screen
of AWT, the update method is called first to redraw the item’s background and programmers
often override update method to just call the paint method directly to avoid flickering. In Swing,
on the other hand the update method does not redraw the item’s background because components
can be transparent; instead update just calls paint method directly.
Japplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For
example, JApplet supports various “panes,” such as the content pane, the glass pane, and the root
pane.
When adding a component to an instance of JApplet, do not invoke the add( ) method of the
applet. Instead, call add( ) for the content pane of the JApplet object. The content pane can be
obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 217
Java Programming
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file named filename. The second form uses the image in the
resource identified by url. The ImageIcon class implements the Icon interface that declares the
methods shown here:
Swing labels are instances of the JLabel class, which extends JComponent. It can display text
and/or an icon. Some of its constructors are shown here:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument is either LEFT,
RIGHT,CENTER, LEADING, or TRAILING. These constants are defined in the
SwingConstants interface, along with several others used by the Swing classes. The icon and text
associated with the label can be read and written by the following methods:
Icon getIcon( )
String getText( )
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 218
Java Programming
void setIcon(Icon i)
void setText(String s)
Here, i and s are the icon and text, respectively. The following example illustrates how to create
and display a label containing both an icon and a string. The applet begins by getting its content
pane. Next, an ImageIcon object is created for the file IC.jpg. This is used as the second
argument to the JLabel constructor. The first and last arguments for the JLabel constructor are
the label text and the alignment. Finally, the label is added to the content pane.
import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet> */
public class JLabelDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
contentPane.add(jl);
}
}
Text Fields
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows us to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 219
Java Programming
JTextField(String s)
Here, s is the string to be presented, and cols is the number of columns in the text field. The
following example illustrates how to create a text field. The applet begins by getting its content
pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is
created and is added to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
Buttons
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, we can associate an icon with a Swing button. Swing buttons are subclasses of the
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 220
Java Programming
Abstract Button class, which extends JComponent. Abstract Button contains many methods that
allow us to control the behavior of buttons, check box and radio buttons. For example, we can
define different icons that are displayed for the component when it is disabled, pressed, or
selected. Another icon can be used as rollover icon, which is displayed when the mouse is
positioned over that component. The following are the methods that control this behavior:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for these different conditions. The text associated
with a button can be read and written via the following methods:
String getText( )
void setText(String s)
Here, s is the text to be associated with the button. Concrete subclasses of AbstractButton
generate action events when they are pressed. Listeners register and un-register for these events
via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener. Abstract Button is a superclass for push buttons, check boxes, and
radio buttons.
JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon string, or
both to be associated with the push button. Some of its constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button. The following example displays four
push buttons and a text field. Each button displays an icon that represents the flag of a country.
When a button is pressed, the name of that country is displayed in the text field. The applet
begins by getting its content pane and setting the layout manager of that pane. Four image
buttons are created and added to the content pane.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 221
Java Programming
Next, the applet is registered to receive action events that are generated by the buttons. A text
field is then created and added to the applet. Finally, a handler for action events displays the
command string that is associated with the button. The text field is used to present this string.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("green.jpg");
JButton jb = new JButton(france);
jb.setActionCommand("Green");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon germany = new ImageIcon("red.jpg");
jb = new JButton(germany);
jb.setActionCommand("Red");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("yellow.jpg");
jb = new JButton(italy);
jb.setActionCommand("Yellow");
jb.addActionListener(this);
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 222
Java Programming
contentPane.add(jb);
ImageIcon japan = new ImageIcon("black.jpg");
jb = new JButton(japan);
jb.setActionCommand("Black");
jb.addActionListener(this);
contentPane.add(jb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}
}
Check Boxes
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of Abstract Button. It is immediate super -class is JToggleButton, which
provides support for two -state buttons. Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 223
Java Programming
Here, i is the icon for the button. The text is specified by s. If state is true, the check box is
initially selected. Otherwise, it is not. The state of the check box can be changed via the
following method:
Here, state is true if the check box should be checked. The following example illustrates how to
create an applet that displays four check boxes and a text field. When a check box is pressed, its
text is displayed in the text field the content pane for the JApplet object is obtained, and a flow
layout is assigned as its layout manager. Next, four check boxes are added to the content pane,
and icons are assigned for the normal, rollover, and selected states.
The applet is then registered to receive item events. Finally, a text field is added to the content
pane. When a check box is selected or deselected, an item event is generated. This is handled by
itemState Changed( ). Inside item State Changed( ), the getItem( ) method gets the JCheckBox
object that generated the event. The getText( ) method gets the text for that check box and uses it
to set the text inside the text field.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 224
Java Programming
contentPane.setLayout(new FlowLayout());
JCheckBox cb = new JCheckBox("C", true);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", false);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", false);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", false);
cb.addItemListener(this);
contentPane.add(cb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
Radio Buttons
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
Abstract Button. Its immediate super -class is JToggle Button, which provides support for two-
state buttons. Some of its constructors are shown here:
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 225
Java Programming
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state istrue, the button is initially
selected. Otherwise, it is not. Radio buttons must be configured into a group. Only one of the
buttons in that group can be selected at any time. For example, if a user presses a radio button
that is in a group, any previously selected button in that group is automatically deselected. The
ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for
this purpose. Elements are then added to the button group via the following method:
Here, ab is a reference to the button to be added to the group. The following example illustrates
how to use radio buttons. Three radio buttons and one text field are created. When a radio button
is pressed, its text is displayed in the text field. First, the content pane for the JApplet object is
obtained and a flow layout is assigned as its layout manager. Next, three radio buttons are added
to the content pane. Then, a button group is defined and the buttons are added to it.
Finally, a text field is added to the content pane. Radio button presses generate action events that
are handled by action Performed(). The get Action Command() method gets the text that is
associated with a radio button and uses it to set the text field.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=400 height=50>
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 226
Java Programming
</applet>
*/
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 227
Java Programming
}
}
Combo Boxes
Swing provides a combo box (a combination of a text field and a dropdown list) through the
JComboBox class, which extends JComponent. A combo box normally displays one entry.
However, it can also display a drop -down list that allows a user to select a different entry. We
can also type our selection into the text field. Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
JComboBox(Objects obj[])
Here, v is a vector that initializes the combo box and obj is the array of objects. Items are added
to the list of choices via the addItem( ) method, whose signature is shown here:
Important Methods:
It returns true if the JComboBox is editable. By default, a combo box is not editable.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 228
Java Programming
It sets the maximum number of rows the JComboBox displays. If the number of objects in the
model is greater than ‘count’, the combo box uses a scrollbar.
It sets the selected item in the combo box display area to the object in the argument. If anObject
is in the list, the display area shows anObject selected.
It inserts an item ‘anObject’ into the item list at a given ‘index’. public void remove Item(Object
anObject)
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=100>
</applet>
*/
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 229
Java Programming
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 230
Java Programming
The framework had to allow different types of collections to work in a similar manner and
with a high degree of interoperability.
Towards this end, the entire collections framework is designed around a set of standard interfaces.
Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces
are provided that you may use as-is and you may also implement your own collection, if you
choose.
A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of
the appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are fully
integrated with collections.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 231
Java Programming
This enables you to work with groups of objects; it is at the top of the collections
hierarchy.
3 The Set
This extends Collection to handle sets, which must contain unique elements
4 The SortedSet
5 The Map
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in ascending order.
8 The Enumeration
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 232
Java Programming
This is legacy interface and defines the methods by which you can enumerate (obtain
one at a time) the elements in a collection of objects. This legacy interface has been
superceded by Iterator.
1 AbstractCollection
2 AbstractList
3 AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random
access of its elements.
4 LinkedList
5 ArrayList
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 233
Java Programming
6 AbstractSet
7 HashSet
8 LinkedHashSet
9 TreeSet
10 AbstractMap
11 HashMap
12 TreeMap
13 WeakHashMap
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 234
Java Programming
14 LinkedHashMap
15 IdentityHashMap
The following legacy classes defined by java.util have been discussed in previous tutorial:
1 Vector
This implements a dynamic array. It is similar to ArrayList, but with some differences.
2 Stack
3 Dictionary
4 Hashtable
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 235
Java Programming
5 Properties
6 BitSet
A BitSet class creates a special type of array that holds bit values. This array can
increase in size as needed.
Several of the methods can throw a ClassCastException, which occurs when an attempt is made
to compare incompatible types, or an UnsupportedOperationException, which occurs when an
attempt is made to modify an unmodifiable collection.
Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All
are immutable.
The easiest way to do this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 236
Java Programming
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator
extends Iterator to allow bidirectional traversal of a list and the modification of elements.
Here is a list of all the methods with examples provided by Iterator and ListIterator
interfaces.
This interface lets us sort a given collection any number of different ways. Also this interface
can be used to sort any instances of any class (even classes we cannot modify).
Here is a list of all the methods with examples provided by Comparator Interface.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 237
Java Programming
Although it does not mention it specifically, this objective involves one of the new objectives for
the Java2 version of the exam, a knowledge of the collection classes. The exam questions on
these new collections are fairly basic, requiring a knowledge of where and how you might use
them, rather than a detailed knowledge of the fields and methods.
The Java 2 API includes new interfaces and classes to enhance the collections available. Earlier
versions of Java included
vector
hashtable
array
BitSet
Of these, only array was included in the objectives for the 1.1 certification exam. One of the
noticeable omissions from Java 1.1 was support for sorting, a very common requirement in any
programming situation,
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 238
Java Programming
At the root of the Collection API is the Collection interface. This gives you a series of common
methods that all collection classes will have. You would probably never create your own class
that implements Collection as Java supplies a series of sub-interfaces and classes that uses
the Collection interface.
Sets
Maps
Classes that implement the Collection interface store objects as elements rather than primitives.
This approach has the drawback that creating objects has a performance overhead and the
elements must be cast back from Object to the appropriate type before being used. It also means
that the collections do not check that the elements are all of the same type, as an object can be
just about anything.
A Set
A Set is a collection interface that cannot contain duplicate elements. It thus matches nicely onto
concepts such as a record set returned from a relational database. Part of the magic of
the Set interface is in the add method.
add(Object o)
Any object passed to the add method must implement the equals method so the value can be
compared with existing objects in the class. If the set already contains this object the call
to add leaves the set unchanged and returns false. The idea of returning falsewhen attempting to
add an element seems more like the approach used in C/C++ than Java. Most similar Java
methods would seem to throw an Exception in this type of situation.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 239
Java Programming
A List
add
remove
clear
The JDK documentation gives the example of using List to manage an actual GUI list control
containing a list of the names of the Planets.
A Map
Map is an interface, classes that implement it cannot contain duplicate keys, and it is similar to a
hashtable.
The big advantage of the collections over arrays is that the collections are growable, you do not
have to assign the size at creation time. The drawback of collections is that they only store
objects and not primitives and this comes with an inevitable performance overhead. Arrays do
not directly support sorting, but this can be overcome by using the static methods of the
Collections. Here is an example.
import java.util.*;
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 240
Java Programming
Sort(){
String s[] = new String[4];
s[0]="z";
s[1]="b";
s[2]="c";
s[3]="a";
Arrays.sort(s);
for(int i=0;i< s.length;i++)
System.out.println(s[i]);
}
}
Using Vectors
The following example illustrates how you can add objects of different classes to a Vector. This
contrasts with arrays where every element must be of the same type. The code then walks
through each object printing to the standard output. This implicitly access the toString() method
of each object.
import java.awt.*;
import java.util.*;
public class Vec{
public static void main(String argv[]){
Vec v = new Vec();
v.amethod();
}//End of main
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 241
Java Programming
Prior to Java2 the Vector class was the main way of creating a re-sizable data structure. Elements
can be removed from the Vector class with the remove method.
Using Hashtables
Hashtables are a little like the Visual Basic concept of a Collection used with a key. It acts like
a Vector, except that instead of referring to elements by number, you refer to them by key.
The hash part of the name refers to a math term dealing with creating indexes. A hashtable can
offer the benefit over a Vector of faster look ups.
BitSet
A BitSet as its name implies, stores a sequence of Bits. Don't be misled by the "set" part of its
name its not a set in the mathematical or database sense, nor is it related to the Sets available in
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 242
Java Programming
Java2. It is more appropriate to think of it as a bit vector. A BitSet may useful for the efficient
storage of bits where the bits are used to represent true/false values. The alternative of using
some sort of collection containing Boolean values can be less efficient.
It’s efficient only from the standpoint of size; if you’re looking for efficient access, it is slightly
slower than using an array of some native type.
The BitSet is somewhat of a novelty class which you may never have a need for. I suspect that it
might be handy for the purposes of cryptography or the processing of images. Please let me
know if you come across a question relating to it in the Java2 exam.
JDBC ARCHITECTURE
INTRODUCTION TO JDBC
JDBC stands for Java Database Connectivity. It is set of Java API’s(application programming
interface) used for executing SQL statements. This API consists of a set of classes and interfaces
to enable programmers to write pure Java Database applications.
JDBC is a software layer that allows developers to write real client –server projects in Java.
JDBC does not concern itself with specific DBMS functions. JDBC API defines how an
application opens a connection, communicates with a database, executes SQL statements, and
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 243
Java Programming
retrieves query result. Following fig. will illustrate the role of JDBC. JDBC is based on the
X/OPEN call level interface (CLI) for SQL.
Call Level Interface is a library of function calls that supports SQL statements. CLI requires
neither host variables nor other embedded SQL concepts that would make it less flexible from a
programmer’s perspective. It is still possible, however, to maintain and use specific functions of
a database management system when accessing the database through a CLI.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.
In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that
can communicate with the particular data source being accessed. A user's commands are delivered to
the database or other data source, and the results of those statements are sent back to the user. The
data source may be located on another machine to which the user is connected via a network. This is
referred to as a client/server configuration, with the user's machine as the client, and the machine housing
the data source as the server. The network can be an intranet, which, for example, connects employees
within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results back to
the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive
because the middle tier makes it possible to maintain control over access and the kinds of updates that
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 244
Java Programming
can be made to corporate data. Another advantage is that it simplifies the deployment of applications.
Finally, in many cases, the three-tier architecture can provide performance advantages.
Until recently, the middle tier has often been written in languages such as C or C++, which offer fast
performance. However, with the introduction of optimizing compilers that translate Java bytecode into
efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is
fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to
take advantage of Java's robustness, multithreading, and security features.
With enterprises increasingly using the Java programming language for writing server code, the JDBC
API is being used more and more in the middle tier of a three-tier architecture. Some of the features that
make JDBC a server technology are its support for connection pooling, distributed transactions, and
disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 245
Java Programming
applet. With increasing inclination of programmers towards Java, knowledge about JDBC is
essential.
There are two types of interfaces – low –level interface and high-level interface. While high
level interfaces are user-friendly, low-level interfaces are not. JDBC is a low-level API
interface, ie. It used to invoke or call SQL commands directly. The required SQL statements
are passed as strings to Java methods.
Some of the current trend that are being developed to add more features to JDBC are
embedded SQL for java and direct mapping of relational database to java classes.
Embedded SQL enables mixing of java into SQL statements. These statements are
translated into JDBC calls using SQL Processor. In this type of direct mapping of relational
database tables to java, each row of the table becomes an instance of the class and each
column value corresponds to an attribute of that instance. Mapping is being provided that
makes rows of multiple tables to form a java class.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 246