Java
Java
Mukthagangotri, Mysore-570006
Editorial Committee
Dr. D M Mahesha MCA.,PhD Chairman
BOS Chairman,
Assistant Professor & Programme co-ordinator(PG)
DoS&R in Computer Science,
Karnataka State Open University, Mysuru-570 006.
Copy Right
Registrar,
Karnataka State Open University,
Mukthagantoghri, Mysore 570 006.
Printed and Published on behalf of Karnataka State Open University, Mysore-570 006 by
the Registrar (Administration)-2022
TABLE OF CONTENTS
BLOCK 1I
BLOCK 1II
BLOCK 1V
UNIT-13 Text and binary i/o classes, object i/o, random access files 302-321
Object Oriented Programming with Java is introductory computer programming course that
uses Java as the language of instruction and OOP concepts enhances the simplicity and power
in handling. It is suitable for use in an introductory programming course and for people who
are trying to learn programming on their own. There are no prerequisites beyond a general
familiarity with the ideas of computers and programs. There is enough material for a full course
at this-level programming. The whole course is comprised of 4 Blocks of 16 units’ total.
UNIT 1: INTRODUCTION TO JAVA
Structure
1.0 Objectives
1.1 Introduction
1.2 Java and Its Salient Features
1.3 Fundamentals of Java Programming ,Data Types, Variables, Operators, Control
Structures, Including Selection Looping
1.4 Introduction to OOP’s
1.5 Summary
1.6 Key words
1.7 Questions for Self Study
1.8 Suggested readings
1.0 OBJECTIVES
1
1.1 INTRODUCTION
This unit introduces us to Java and its salient features. It lists the newly added
features in Java 2. This unit lays a firm groundwork to Java, explaining in brief
the various data types, literals, operators and programming constructs available.
This unit also gives us a brief introduction to the Object-Oriented Programming
Structure (OOPS).
The popularity of Java is due to its unique technology that is designed on the basis of
three key elements. They are the usage of applets, powerful programming language
constructs and a rich set of significant object classes.
The compiler generates bytecode (a set of instructions that resemble machine code
but are not specific to any processor) instead of machine code and the interpreter
executes the Java program
The disadvantage of using bytecode is the execution speed. Since system specific
programs run directly on the hardware, they are faster than the Java bytecodes that is
processed by the interpreter. In order to write a Java program, an editor, a Java
compiler and a Java Runtime Environment are needed.
The editor can be a Notepad, WordPad, MS-DOS editor etc. The easiest way to get a
Java Compiler and Runtime Environment is to download Sun's Java Development Kit.
2
This provides system input and output capabilities and other utility functions in
addition to classes that support networking, common Internet protocols and user
interface toolkit functions.
Features of Java
Java was designed to meet all the real world requirements with its key features, which
are explained in the following paragraphs. The features of Java are also known as
Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform
independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
3
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple and powerful: Java is very easy to learn, and its syntax is simple,
clean and easy to understand. According to Sun Microsystem, Java language is
a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
4
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules. Basic OOPs concepts such as
Object, Class, Inheritance, Polymorphism, Abstracton and Encapsulation.
Portable:
Java Program written in one environment can be executed in another
Environment. Run on any Environment
In Java, the same mechanism that gives security also helps in portability. Many types
of computers and operating systems are in use throughout the world and are
connected to the Internet. For downloading programs through different platforms
connected to the Internet, some portable, executable code is needed. Java’s answer to
these problems is its well- designed architecture.
Platform Independent:
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in which
a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming
Interface)
5
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere
(WORA).
Secure : Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
o No explicit pointer
o Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
6
etc.
Today everyone is worried about safety and security. People feel that conducting
commerce over the Internet is as safe as printing their credit card number on the first
page of a Newspaper. Threatening of viruses and system hackers also exists. To
overcome all these fears Java has safety and security as its key design principle.
Using Java Compatible Browser, anyone can safely download Java applets without
the fear of viral infection or malicious intent. Java achieves this protection by
confining a Java program to the Java execution environment and by making it
inaccessible to other parts of the computer. We can download applets with confidence
that no harm will be done and no security will breached.
Robust:
Early identification and Checking of errors. This can be achieved with the help
of Garbage Collection, Exception Handling.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Most programs in use today fail for one of the two reasons: memory management or
exceptional conditions. Thus, the ability to create robust programs was given a high
priority in the design of Java. Java forces the user to find mistakes in the early stages
7
of program development. At the same time, Java frees the user from having to worry
about many of the most common causes of programming errors Java checks code at
compilation time. However, It also checks the code at run time.
Architecture-neutral:
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
Irrespective of architecture, the memory allocated to the varibles will not vary.
8
The Java designers worked hard in attaining their goal "write once; run anywhere,
anytime, forever" and as a result the Java Virtual Machine was developed. A main
issue for the Java designers was that of code longevity and portability. One of the
main problems is the execution speed of the program. Since Java is Architecture-
neutral it generates bytecode that resembles machine code, and are not specific to any
processor.
Java is designed for the distributed environment for the Internet, because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not entirely different
from accessing a file. Original Version of Java (OAK) included features for intra-
address-space messaging. This allowed objects on two different computers to execute
procedures remotely. Java has recently revived these interfaces in a package called
Remote Method Invocation (RMI).
Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes. It means
9
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
Java programs carry with them extensive amounts of run-time information that is used
to verify and resolve accesses to objects at run time. Using this concept it is possible
to dynamically link code. Dynamic property of Java adds strength to the applet
environment, which small fragments of byte code may be dynamically updated on a
running system.
10
1.3 Fundamentals of Java Programming, Data Types, Variables, Operators,
Control Structures, Including Selection Looping
Developing a Java Program
The Sun's Java Development Kit (JDK) provides all features to write programs. The
JDK is available for systems running Windows NT, Windows 95 and Solaris 2.3 or
higher. Java applications are general programs written in the Java language that do not
require a browser to run. The Java source file is created in a plain text editor and can
also be created in an editor that saves files in plain ASCII without any formatting
characters. To type in a program, in UNIX systems, the vi or pico editors are used
whereas in Windows, the Notepad or DOS editor is employed. A Java program has
two main parts - a class definition that encloses the entire program and a method
called main that contains the body. Once the program is typed in, it is saved as a file
with an extension of .java. Usually, Java files have the same name as their class
definition. This file is then compiled using javac. The javac program should be in the
execution path for compilation of the Java code. Once completed, a file by the same
name, but with the .class extension is created. This is the Java bytecode file. The
bytecode.is then run using the Java interpreter. In the JDK, the Java interpreter is
called java. To execute this, java followed by the file name without the .class
extension is typed at the DOS prompt. The above compilation and execution
procedure works only if Sun's Java compiler is used.
The following example depicts the writing of a Java program. Compile and execute
the program.
Example 2.1
• Open a new file in the editor and type the following script
1: Class First {
2: public static void main (String args[ ]) {
3: System.out.println(“WELCOME TO JAVA CLASS”);
4: }
5: }
11
Save the file as First.java.
Compile by typing javac First.java on the command line.
On successful compilation execute the program by typing java First,
on the command line.
The output of the program appears as follows:
In addition to compilation and execution, both Java compiler and the Java interpreter
check the Java source code and bytecode to make sure that the Java programmer has
not overrun buffers, stack frames etc.
Class declaration is done in line no. 1. Every Java application program has a
main( ) method. It is the first function run when the program is executed. The void
keyword preceding main( ) indicates that it does not return any values. public
indicates that the method is global, static denotes that main( ) is a class method
and can be called without creating an object. Line 3 gives the syntax for printing a
string onto the screen. The curly braces are used to enclose the class and main
function.
Note: The line numbers given are not part of the source code and should not be
typed so.
For effective and easy programming, any programming language offers the user data
types, expressions and operators. These features are present in Java and are
elucidated in the following paragraphs.
Data Types
Every variable declared should have a name, a type and a value. Java provides
different data types that include character, double, float, integer, string, boolean etc.
12
These are primitive types as they are built into the Java language and are not actual
objects thus making it easier to use them. The data types in Java are machine
independent. New types are declared by a class definition and objects of this class
can be created. There are times when the data types are required to be true objects.
Wrapper classes are provided for the primitive types for this purpose. The wrapper
classes for the primitive data types have the same name as the primitive type, but
with the first letter capitalized. The advantage of using wrappers is that when an
object is passed to a method, the method is able to work on the object itself.
Another advantage is that the user can derive his/her own classes from Java's built-
in wrapper classes
Integer
Integers are used for storing integer values. There are four kinds of integer types in
Java. Each of these can hold a different range of values. The values can either be
positive or negative. Depending on the range of values that it should hold, the type of
integer is chosen. If the value becomes too large, it will be truncated. The table for the
range of values is given below:
Table 2.1
Float
Float is used to store numbers with decimal part. There are two floating point data
types in Java namely, the float (32 bits, single precision) and the double (64 bits,
double precision).
13
Character
It is used-for storing individual characters. The char type has 16 bits of precision and
it is unsigned.
Boolean
Boolean data types hold either a true or a false value. These are not stored as
numeric values and cannot be used as such.
Variables
Variables are locations in the memory that can hold values. Before assigning any
value to a variable, it must be declared. Java has three kinds of variables namely,
Instance variables
Local variables
Class variables
Instance variables are used to define attributes or the state of a particular object. These
are used to store information needed by multiple methods in the objects.
All three kinds of varibles are declared in the same way,but class and instance
varibles are alone are acessed in a different manner.
Declaring Variables
Variables can be declared anywhere in the method definition and can be initialized
14
during their declaration. They are commonly declared before usage at the beginning
of the definition. Variables with the same data type can be declared together. Local
variables must be given a value before usage.
Variable Names
Variable names. in Java can start with a letter, an underscore ( _ ), or a dollar sign ($)
but cannot begin with a number. The second character onwards can include any letter
or number. Java is case sensitive and also uses the Unicode character set.
Variable Types
Variable types can be any data type that Java supports - the eight primitive types, the
name of a class or Interface and an array.
Assigning Values
Values are assigned to variables using the assignment operator "equal to" (=).
The following example demonstrates declaration, initiation and display of variables.
Example 2.2
1: class Second {
2: public static void main (String args[ ]) {
3: int x = 90;
4: short y = 4;
5: float z = 10.87f;
6: String name = "Aarti";
7: System.out.println("The integer value is " + x);
8: System.out.println("\nThe Short value is " + y);
9: System.out.println("\n The float value is " + z);
10: System.out.println(" \n The string value is " + name);
11: }
12: }
Note: The line numbers given are not part of the source code and should not be
15
typed so.
Save this file as Second.java and compile using javac Second.java at DOS
prompt.
On successful compilation, execute the program using java Second
The output is displayed as shown below:
The lines 3 - 6 depict the declaration, initialization and naming of-various data types.
The values of the declared variables are printed from lines 7 - 10. The + operator is
used here as a concatenation operator which is dealt later
Note: The line numbers given are not part of the source code and should not be
typed so.
Literals
A Literal represents a value of a certain type where the type describes the
behaviour of the value.
Number literals
Character literals
Boolean literals
String literals
Number
There are several integer literals such as int, long, octal, hexadecimal, etc. 4 is an
16
example of a decimal integer literal of type into If a decimal integer literal is larger
than the int, it is declared to be of type long. A number can be made long by
appending L or l to it.
Negative integers are preceded by the minus sign. These integers can also be
expressed as octal or hexadecimal. A leading 0 to the integer indicates that the
number is an octal integer. For example, 0987 is an octal integer. A leading Ox to the
integer indicates that the number is a hexadecimal integer, example, 0xaf94 is a
hexadecimal number.
Floating point literals have a decimal part and an integer part. Floating point literals
result in floating point numbers of type double. By appending f to a number, it can
be changed as type float. Exponents can be used in floating point literals by using
the letter E or e followed by the exponent.
Boolean
Character
Character literals are expressed by a single character enclosed within single quotes.
Characters are stored as Unicode characters. Table 2.2 lists the special codes that
represent non-printable characters and characters from Unicode character set.
Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
\' Single quote
\" Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode
Table 2.2
character
17
The letter 'd' in the octal, hex and the Unicode escapes represent a number or a
hexadecimal digit . Java does not include character codes for the bell and the vertical
tab.
StrIng
A string is a combination of characters. String literals are a set of characters that are
enclosed within double quotes. As they are real objects, it is possible to
concatenate, modify and test them. For example, "This is a test string" represents a
string. Strings can contain character constants and Unicode characters.
When a string literal is declared Java automatically creates an instance of the class
String and initializes it with the value specified.
Expressions
Expressions are the simplest form of statements in Java. These statements return a
value that can be assigned to a variable. The following are examples for
expressions:
X+ 15
count/2
total-l
Operators
Arithmetic Operators
Java has five basic arithmetic operators. Each of these operators takes two operands,
one on either side of the operator. The list of arithmetic operators is given below:
18
Operator Meaning Example
+ Addition 8 + 10
- Subtraction 10- 8
* Multiplication 20 * 84
/ Division 10 / 5
% Modulus 10%6
Table 2.3
The subtraction operator is also used to negate a single operand. Integer division
results in an integer. Any remainder due to integer division is ignored. Modulus
gives the remainder once the division has been completed. For integer types, the result
is an int regardless of the type of the operands. If anyone or both the operands is of
type long, then the result is also long. If one operand is an int and the other is float,
then the result is a float.
Note: The line numbers given are not part of the source code and should not be
typed so.
19
Save this file as Three.java and compile using javac Three.java at DOS prompt.
On successful compilation, execute the source code using: java Three
The output appears as shown below:
The value of x + y is 30
The value of z - y is 5.9799995
Notice the usage of the various arithmetic operators from lines 6 - 10.
Assignment Operators
The assignment operators used in C and C++ are also used in Java. A selection of .
assignment operators is given.
Expression Meaning
x+=y x=x+y
x -= y x=x-y
x *= y x=x*y
x/=Y x = x/ y
x=y x=y
Table 2.4
20
Example 2.4
• Open a new file in the editor and type the following script.
1: class assign{
2: public static void main(String args[ ]) {
3: int a=1;
.: int b=2;
5: int c=3;
6: a+=5;
7: b*=4;
8: c+=a*b;
9: c%=6;
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Save this file as assign.java and compile using javac assign.java at the
DOS prompt.
On successful compilation, execute the source code using: java assign
The output appears as shown below:
a=6
b=8
c=3
21
Incrementing and Decrementing
++a (Pre increment operator): Increment "a" by 1, then use the new value
of "a" in the expression in which "a" resides.
a++ (Post increment operator): Use the current value of "a" in the
expression in which "a" resides and then increment "a" by 1.
--b (Pre decrement operator): Decrement "b" by 1, then use the new value
of "b" in the expression in which "b" resides .
.b- -(Post decrement operator): Use the current value of "b" in the
expression in which "b" resides and then decrement "b" by 1.
Example 2.5 demonstrates the usage of the increment and decrement operators.
Example 2.5
Open a new file in the editor and type the following script.
1: class IncDec {
2: public static void main (String args[ ]) {
3: int a =1;
4: int b=2;
5: int c=++b;
6: int d=a++;
7: c++;
8: System.out.println(" a = " + a) ;
9: System.out.println(" b = " + b) ;
10: System.out.println(" c = " + c) ;
11: System.out.println(" d = " + d);
12: }
13: }
22
Save this file as InDec.java and compile using javac InDec.java at the DOS
prompt. \
On successful compilation, execute the source code using: java IncDec
The output appears as given below:
a=2
b=3
c=4
d=1
Comparison Operators
There are several expressions for testing equality and magnitude. All these
expressions return a boolean value. Table 2.5 enlists the comparison operators.
Logical Operators
The AND operator (& or &&) returns true only if both sides in an expression are
true. If anyone side fails, the operator returns false. For example, consider the
following statement
23
This condition is true if and only if both the simple conditions are true. In the &&
operator, if the left side of the expression returns false, the whole expression returns
false and the right side is totally neglected. The & operator evaluates both sides
irrespective of outcome.
The | or | | is used for OR combination. This returns true if any of the expressions is
true. Only if all the conditions are false, the expression is false. Consider the
following statement
The above condition is true if either of the two conditions is true. The | | evaluates
the left expression first and if it returns true, never evaluates the right side
expression. A single | evaluates both the expressions regardless of the outcome.
The XOR operator indicated by ^, returns true only if its operands are different. If
both its operands are similar (true-true, false-false), it returns false.
The ! operator is used for NOT. The value of NOT is negation of the expression.
Bitwise Operators
The bitwise operators are inherited from C and C++. They are used to perform
operations on individual bits in integers. A list of the bitwise operators available is
given in Table 2.6.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
« Left Shift
» Right Shift
»» Zero fill right shift
~ Bitwise Complement
«= Left Shift assignment
»= Right Shift assignment
>>>= Zero fill right shift
assignment
24
x&=y AND assignment
x !=y OR assignment
x ^=v XOR assignment
Table 2.6
1: class Bitop {
2: public static void main (String args[ ]) {
3: int a=1;
4: int b=2;
5: int c=3;
6: a=a|4;
7: b>>=1;
8: c<<=1;
9: a=a^c;
10: System.out.println ("a=" +a);
11: System.out.println ("b=" +b);
12: System.out.println ("c=" +c);
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
typed so.
a=3
25
b=l
c=6
Operator Precedence
The order in which the expressions are evaluated and their overall value
is determined by Operator precedence.
Operator Notes
[ ], ( ), . [ ] is used for arrays. ( ) group expressions. Dot is used
to access methods and variables within objects and
classes.
++, --, !, - , instance of Returns true or false based on whether the object is an
instance of the named class or any of that class's
superclass.
New (type) expression The new operator is used to create instances of classes
*, /, % Multiplication, division, modulus Modulus
+, - Addition, subtraction
<< , >> Bitwise left and right shift
<, >, <=, >= Relational comparison tests
& AND •
^ XOR
| OR
&& Logical AND
|| Logical OR
?: Ternary operator
=, +=, - =, *=, /=, %=, Assignment
^=
Table 2.7
26
Programming Constructs
Programming constructs in Java are the if construct and ternary operator, switch
statement the while, do while and for loops.
The If Construct
The if else construct executes different bits of code based on successful completion
of a condition, that returns only boolean values. If the execution is unsuccessful, the
sets of instructions under else are executed.
if (condition)
body of loop;
else
body of loop;
The following example illustrates usage of the if else construct and logical operators.
Example2.7
Open a new file in the editor and type the following script.
class Four {
public static void main (String args[]) { int month = 4;
String season;
if (month = =12 I I month ==1 II month ==2) {
season="Winter";
}
else if (month = =3 I I month ==4 II month ==5){
season="Springll;
}
else if (month = =6 I I month = =7 II month ==8){
season="Summer";
}
27
else if (month = =9 I I month ==10 I I month ==11) {
season="Autumn";
}
else{
season="Invalid month";
System.out.println ("April is in " + season + ".");
}
}
Save this as Four.java and compile using javac Four.java at the DOS prompt.
On successful compilation execute, using java Four.
The output of the program is given below:
April is in Spring.
This example uses several if-else statements to determine which season a particular
month is in.
Conditional Operator
where, <test> is the condition to be tested. If the condition returns true then the
statement given in <pass> will be executed. Otherwise, the statement given in
<fail> will be executed.
Example 2.8
• Open a new file in the editor and enter the following code:
28
1: class Ternary
Save this file as Five.java and compile using javac Five.java at the DOS prompt.
On successful compilation execute using java Five.
The output is given below:
Note the usage of conditional operator at line number 6. If the value of the variable i
is than j, then z contains the value of i, else it contains the value of j.
The while loop executes a set of code repeatedly until the condition returns false.
The
syntax for the while loop is given below:
while (<condition> ) {
where <condition> is the condition to be tested. If the condition returns true then
the statements inside the <body of the loop> are executed. Else, the loop is not
29
executed.
The do while loop is similar to the while loop except that the condition to be evaluated
is given at the end. Hence the loop is executed at least once even when the condition
is false. The syntax for the do while loop is as follows:
do{
Example 2.9
• Open a new file in the editor and type the following script
1: class Fibo
2: public static void main (String args l l ) {
3: int max = 25;
4: int prev =0;
5: int next=1;
6: int sum;
8: {
13: }
14: }
15: }
Note: The line numbers given are not part of the source code and should not be
typed so.
30
Save this file as Fibo.java and compile using javac Fibo.java at DOS prompt.
On successful compilation, execute using java Fibo.
The output appears as given below:
The while loop, shown from line 7 - 13, is executed as long as the value of the
variable next is less than or equal to 25. This program generates the Fibonacci series
The for loop repeats a set of statements a certain number of times until a condition is
matched. It is commonly used for simple iteration. The for loop appears as shown.
In the first part a variable is initialized to a value. The second part consists of a test
condition that returns only a boolean. The last part is an expression, evaluated every
time the loop is executed. The following example depicts the usage of the for loop.
Example 2.10
• Open a new file in the editor and type the following script.
class ForDemo {
public static void main (String args[ ])
{
31
int i;
for (i =0;i < 10;i=i+2)
{
if ((i%2) == 0)
System.out.println ("The number" + i +" is a even number");
}
}
}
Switch Statement
The switch statement dispatches control to the different parts of the code based on
the value of a single variable or expression. The value of expression is compared
with each of the literal values in the case statements. If they match, the following
code sequence is executed. Otherwise an optional default statement is executed. The
general syntax of the switch
statement is as follows:
switch (<test>) {
case <valueOne>:
<resultOne>;
break;
32
case <valueTwo>:
<resultTwo>;
break;
default :
<defaultResult>;
}
1: class season {
3: int v = 4;
4: switch(v) {
5: case 1:
6: case 2:
7: case 3:
9: break;
10: case 4:
11: case 5:
12: case 6:
14: break;
15: case 7:
16: case 8:
17: case 9:
33
18: System.out.println ("Autumn leaves are abundant");
19: break;
20: case 10:
Note: The line numbers given are not part of the source code and should not be
typed so.
Save this file as season.java and compile using javac season.java at DOS prompt.
On successful compilation, execute using java season.
The output appears as given below:
The break keyword halts the execution of the current loop and forces control out of
the loop. The term break refers to the act of breaking out of a block of code. It tells
the runtime to pick up execution past the end of the named block. In order to refer to
a block by name, Java has a label construct that assigns a name to every block. The
following example demonstrates the usage of break statement.
Example 2.12
• Open a new file in the editor and type the following script:
34
class breakdemo {
public static void main (String args[ ]) {
boolean t=true;
a: {
b: {
c: {
System.out.println("Before the break");
if (t)
break b;
System.out.println ("This will not execute");
}
System.out.println ("This will not execute");
}
System.out.println ("This is after b");
}
}
}
continue is similar to break, except that instead of halting the execution of the
loop, it starts the next iteration. The following example demonstrates the usage of
continue statement.
Example 2.13
class continuedemo {
public static void main (String args[ ]) {
for(int i=0; i<10; i++) {
System.out.print(+i+ " " );
35
if (i%2 == 0)
continue;
System.out.println (" ");
}
}
}Save this file as continuedemojava and compile using javac continuedemo.java
at DOS prompt.
On successful compilation, execute using java continuedemo.
The output appears as given below:
o 1
2 3
4 5
6 7
8 9
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Properties and Task Performed.
36
Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse
.
Encapsulation is a protective wall that prevents the code and data from being
randomly accessed by other code define outside the wall.
Access to the code and data inside the wall is tightly controlled through a well-
defined interface. To relate this to the real world, consider the functionality of a
television. It encapsulates hundreds of bits of information about the internal
37
architecture such as how the signals are converted, how the volume is controlled and
about the power supply. The user has only one method of affecting this complex
encapsulation: by opening the television box.
In Java the basis of encapsulation is the class. Since the purpose of a class is to
encapsulate complexity, there are mechanisms for hiding the complexity inside the
class. Each method or variable in a class may be marked private or public. The
public method can be accessed even by the members outside the class. The private
methods and data can only be accessed by a member of that particular class.
Therefore any other code that is not a member of the class cannot access a private
method or variable. Since the private members of a class can only be accessed
externally through the public methods, the user can ensure that no improper actions
take place. The concept of encapsulation is depicted in Fig 1.1.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object. Inheritance stands for its concept of hierarchical classification. By
inheritance, information is made manageable by hierarchical (i.e. top-down)
classification
For example Labrador is part of the classification dog, which in turn is part of the
mammal class, which is under the larger class termed animal. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly.
However, by use of inheritance, objects need to define only those qualities that make
it unique within its class. It can inherit its general attributes from its parent.
38
Animal class contains its own attributes such as size, intelligence and type of
skeletal system. When going deeper into more specific class of animals (sub-
class), such as mammals, they would have more specific attributes, such as teeth
and mammary glands. Since mammals are simply more precisely specified
animals, they inherit all the attributes from animals. This inheritance is depicted in
Fig. 1.2. Thus it is the inheritance mechanism that makes it possible for one object
to be a specific instance of a more general case.
Polymorphism
Polymorphism (from the Greek, meaning "many forms").is a feature that
allows one interface to be used for a general class of actions.
A stack can explain polymorphism easily. Consider a stack (which is a last-in- first-
39
out list). Let us consider a program that requires three types of stacks, one stack for
integer values, floating-point values, one for characters .The algorithm for
manipulating the numbers is the same for all the three stacks, only the data differs.
In Java, using polymorphism the user can specify a general set of stack that shares
the same name.
More generally, the concept of polymorphism is often expressed by the phrase "one
interface, multiple methods." This means that one common interface can be used for a
group of related methods. It is the compiler's job to select the suitable method
according to the situation. The programmer does not have to make this selection
manually. Extending the dogs' analogy, a dog's sense of smell is polymorphic. If the
dog smells a cat, it will bark and run after it. If it smells its food, it will salivate and
run to its bowl. The same sense of smell is at work in both situations. The difference
is what is being smelt, that is, the type of data/being operated upon by the dog's nose.
This same general concept can be implemented in Java as it applies to methods within
a Java program.
In this unit, we have given a brief introduction to Java and its features. Java and Its
Salient Features, Fundamentals of Java Programming, Data Types, Variables,
Operators, Control Structures, Including Selection Looping and Introduction to
OOP’s
40
2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language
13. Internet.
41
UNIT 2: JAVA METHODS
Structure
2.0 Objectives
2.1 Introduction
2.2 Classes
2.3 Methods
2.4 Constructor and Finalizer
2.5 Garbage Collections
2.6 Summary/Let us Sum up
2.7 Keywords
2.8 Questions for Self Study
2.9 Suggested readings
2.0 OBJECTIVES
State Classes
Describe Methods
42
2.1 INTRODUCTION
This unit deals with classes and their creation. It demonstrates creation of methods,
instances and the usage of the keyword "new". It also describes access specifiers and the
variable scope. Constructors and finalizers and inner classes are also dealt with in detail.
2.2 CLASSES
Classes :
The basic element of object-oriented programming is a class.
A class defines the shape and behaviour of an object and is a template for multiple
objects with similar features. Any concept represented in a program is
encapsulated in a class. When an application is written, classes of objects are
defined. To create a class, a source file with the class keyword in it, followed by a
legal identifier and a pair of curly braces for the body is required.
class <classname> {
<body of the class>
}
A class called Book includes all its features serving as template for the concept. Each
property is treated as an attribute of that class. For example, the book's name, the
author's name, number of pages it contains are its attributes. The definition of the
Book class would be
class Book {
String name;
String authorName;
int nopages;
}
Apart from defining an object's structure, a class also defines its functional interface,
known as methods. For instance, the Book can have a method that displays the name
43
of the book.
class Book
String name;
String authorName;
int nopages;
String displayName() {
System.out.println("Name of the book is " + name);
}
}
Once a Book class is defined, instances of that class can be created and each
instance can have different attributes. When the program runs, instances of the
class are created and discarded as and when required.
An instance of a class can be used to access the variables and methods that form
part of the class. Each instance of the class has its own copy of instance variables
defined in the class and hence can hold different attributes. For instance, one object
of the Book class can contain the attributes of 'Gone with the wind' while another
may contain that of 'Learn Java'.
The methods in the class operate on individual instances of the class. For example,
the same display method can operate on both the instances of the Book class
described above.
Suppose we have two instances objl and obj2 of the Book class. Objl.display( )
displays the attribute of objl, while obj2 .display( ) displays that of obj2.
44
class One{
public static void main (String args[ ])) {
int a = 1;
int b = 2;
int c = 3;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The class is declared in line 1. The main method, the entry point to all Java application
programs, is defined in line 2. In lines 3 - 5, three variables that are local to the main
are declared. These variables are displayed using println in lines 6 - 8.
Attributes
Aaributes are individual properties that differentiate one object from another and determine
apperance, state and other qualities. Each attribute has a corresponding instance variable.
Instance Varibles
Data is encapsulated in a class by declaring variables inside the class declaration. Variables
declared in this scope are known as instance variables. Instance variables are declared in
same way as local variables except that they are declared outside the scope of any
particular method, such as main. For example, a class named Point can be created with
two instance variables namely a and b. Every object of this class has its own copy of
45
the instance variable.
class Point {
int a,b;
Dot Operator
The dot notation is used to obtain the value of the instance variables. It has two
parts namely the object on the left side of the dot and the variable on the right
side of the dot. Dot expressions are evaluated from left to right. The general form
for accessing instance variables using the dot operator is given below:
<ObjectReference>.<variableName>
We can store values into instance variables using the dot operator as shown below:
p.x =10;
p.y= 20;
We can refer to values of instance variables using the dot operator as given below:
The new operator creates a single instance of a named class and returns a reference
to the object. For example, an instance of the class point can be created as shown:
46
how simple types and objects are manipulated in Java. The variable p is a reference
to the object. It does not actually contain it.
Note :When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection.
When a new object is created a distinct set of instance variables are obtained. Each object
has its own copy of the instance variables of its class, so changes to the instance variables
of one object have no effect on the instance variables of another. Each object's instance
variables are separate and distinct from the others.
Example 3.2 depicts the usage of the new operator to create an instance of the class. It
also demonstrate the creation and usage of instance variables and the use of the dot
operator in variables.
Open a new file in the editor and enter the following code:
class Insvar {
int a = 10;
int b = 20;
public static void main (String args[]){
Insvar insvar1 = new Insvar();
System.out.println("The value of a is = " + insvar1.a);
System.out.println("The value of b is = " + insvar1.b);
}
}
Save the file as Insvar.java
Compile the file using javac Insvar.java
Run the file using java Insvar
Two instace variables, a and b, are defined in the class Insvar. The main ( )
method creates an instance of the class using the new operator. When the object is
47
created, the instance varibles a and b, are initialized to 10 and 20 respectively. Lines 6
and 7 display these varibles, accessing them using the dot operator.
Muliple references of the same object can be created. In the illustration, a single object of
a class named Coord is created, with two variables, referencing it.
Coord p2 = p1;
p1
Coord
p2
Object
Fig 3.1
Any changes to the object referenced by p2 will affect the same object to which p1
is referring. The assignment of p1 to p2 does not allocate memory. Subsequent
assignment to p1 will simply unhook p1 from the original object without affecting
the object itself.
Exaample 3.3
• Open a new file in the editor and enter the following code:
class Coord {
int x,y;
Coord p1,p2;
p1 = new Coord();
p1.x = 50;
p1.y = 50;
48
p2= p1;
p1.x =100;
p1.y= 75;
System.out.println("Coordinates
of p1 are" + p1.x + "," + p1.y);
System.out.println("Coordinates
of p2 are" + p2.x + ","+ p2.y);
}
Save the file as Coord •. java
Cornpile the file using javac Coord.java
Run the file using java Coord
The assignment statement in line 8 copies the reference p1 (not the object it is
referring to) to p2. The values of x and y of the object that p1is pointing to, are
modified. Lines 11 and 12 display the variables, x and y, of the objects that p1 a
nd p2 are pointing to. The output of program shows that though only p1 was
modified, changes are reflected both in p1 and p2 since they were pointing to
the same object.
Class Variables
Class variables are global to a class and to all the instances of the class. They are
useful for communicating between different objects of the same class or for
keeping track of global states. The keyword static is used to declare a class
variable. For class variables there is only one copy of the variable. Every instance
of the class has access to that variable. We have to use the dot notation to access
49
the class variable, and instead of using the object's name on the left hand side of
the dot operator, the class name can be used. Thus, class variables can be
accessed without creating an object of that class.
2.3 METHODS
Methods are functions that operate on instances of classes in which they are
defined. objects can communicate with each other using methods and can call
methods in other classes. Just as there are class and instance variables, there are
class and instance methods. Instance methods apply and operate on an instance
of the class while class methods operate on
the class.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is
a collection of instructions that performs a specific task. It provides the reusability of
code. We can also easily modify code using methods. In this section, we will
learn what is a method in Java, types of methods, method declaration, and how to
call a method in Java.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code, just
by adding or removing a chunk of code. The method is executed only when we call or
invoke it.
The most important method in Java is the main() method. If you want to read more
about the main() method, go through the link https://www.javatpoint.com/java-main-
method
Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.
50
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier
in our application.
o Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
o Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are creating
a method for subtraction of two numbers, the method name must be subtraction(). A
51
method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start
with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by adjective or noun. In the multi-word method name, the
first letter of each word must be in uppercase except the first word. For example:
Defining Methods
Method definition has four parts. They are:
A method's signature is a combination of the first three parts mentioned above. Java
permits different methods to have the same name as long as the argument list is
different. This is called method overloading. A basic method definition resembles
the one given below:
{
<set of statements>
52
The returntype is the primitive type or class of the value that this method returns.
It should be void if the method does not return a value at all.
The method's parameter list is a set of variable declarations. The list is separated by
commas within the parentheses. The parameters become local variables in the body
of the method whose values are passed when the method is called.
Inside the body of the method, statements, expressions and method calls can be
present. the method has a return type, then a value must be returned using the
keyword return.
Calling Methods
Obj.methodname(paraml,param2);
Exampe 3.4
Open a new file in the editor and enter the following code
class Area {
53
System.out.println("The area is " + ara + " sq.cms");
}
public static void main (String args[]) {
Area a = new Area();
a.calc() ;
}
}
Class Methods
Class methods, like class variables, are available to instances of the class and can be
made avialable to other classes. Class methods can be used anywhere regardless of
whether an instance of the class exists or not. Methods that operate on a particular
object should be defined as instance methods. Methods that provide some general
utility but do not directly affect an instance of the class are declared as class
methods. Class method is defined as given below:
54
Passing Argument to Methods
The objects that are passed to the body of the method are passed by reference and the
basic types are passed by value. This results in a change in original value of the object
if the value is modified in the method.
Example 3.5 depicts the passing of arguments to methods.
Example 3.5
• Open a new file in the editor and enter the following code:
class Marg {
void calc(int x) {
int square = x * x;
System.out.println ("The square of " + x + " is " + square + "sq.cms");
}
public static void main (String args[]) {
Marg a = new Marg();
a.calc(15);
}
}
55
The this keyword
A special reference value called this is included in Java. The this keyword is used
inside any insance method to refer to the current object. The value of this refers to
the object on which the current method has been called. The this keyword can be
used where a reference to an object of the current class type is required. Methods
declared with the keyword
static (class methods) cannot use this.
class point1{
int x,y;
void init (int x,int y)
{
this.x=x;
this.y=y;
}
void disp()
{
System.out.println("x=" +x);
System.out.println("y=" +y);
}
}
class point{
public static void main(String args[]) {
point1 pp =new point1 ();
pp.init (4,3);
pp.disp();
56
}
}
x=4
y=3
Overloading methods
To create an overloaded method, different method definitions each with the same
name but different parameter lists are created. Java allows method overloading as
long as the each parameter list is unique for the same method name. Java
differentiates overloaded methods with the same name, based on the number and type
of parameters to that method and not on the return type. When a method is called,
Java chooses the method definition to execute, depending on the method name and
number and type of arguments. If methods are chosen to have the same names and
parameter lists but different return types then the compiler returns an error. The
variable names in the parameter list do not matter. Only the number and the
type of the parameters matter.
Example 3.7
• Open a new file in the editor and enter the following code:
1: class Load {
2: String fname;
3: String 1name;
57
4: int age;
5: String prof;
6: Load f1oad(String fname,String 1name,int age,String prof) {
7: this.fname fname;
8: this.1name 1name;
9: this.age = age;
10: this.prof = prof;
11: return this;
12: }
13: Load f1oad(String fn,String In)
14: fname = fn;
15: lname = In;
16: return this;
17: }
18: Load fload{String fnme, String lnme, String pr) {
19: fname fnme;
20: lname lnme;
21: prof = pr;
22: }
23: return this;
24: Load fload{String fna,String lna,int ag) {
25: fname fna;
26: lname lna;
27: age = ag;
28: return this;
29: }
30: void print ( )
31: System.out.println{fname + ", " + lname + " " + age + " " + prof);
32: System.out.println (" ");
33: }
34:public static void main (String args [1) {
35:Load loads = new Load ( ) ;
36:System.out.println ("The various values supplied are as follows:");
37:System.out.println{);
58
38:loads.fload{ "Aswath", "Narayanan", 24, "Engineer");
39:loads. print ( ) ;
40:loads. fload{ "Shankar", "Athreya");
41:loads. print ( ) ;
42:loads.fload{ "Gautham", "Bhaskaran", "Doctor");
43:loads. print ( );
44:loads. fload{ "Nakul", "Mahadevan" , 28) ;
45:loads. print ( ) ;
46: }
47:}
Note: The line numbers given are not part of the source code and should not be
typed so.
The above example depicts method overloading. It has a print () method that prints the
values of the various arguments supplied to the various methods.
59
than the one preceding it.
Public
Any method or variable is visible to the class in which it is defined. If the method or variable
must be visible to all classes, then it must be declared as public. A variable or method with
public access has the widest possible visibility. Any class can use it.
Package
Package is indicated by the lack of any access modifier in a declaration, It has
an increased protection and narrowed visibility and is the default protection
when none has been specified.
Protected
This specifier is a relationship between a class and its present and future
subclasses. The subclasses are closer to the parent class than any other class.
This level gives more protection and narrows visibility.
Note : The package and protected access specifiers have been dealt with while
dealing with packages in the latter half of the book.
Private
It is narrowly visible and the highest level of protection that can possibly be
obtained. Private methods and variables cannot be seen by any class other than
the one in which they are defined. They are extremely restrictive but are most
commonly used. Any representation unique to the implementation is declared
private. An object’s primary job is to encapsulate its data and limit
manipulation. This is achieved by declaring data as private.
60
System.out.println ("The private value is "+ x)?
)
public static void main(String args[{]) {
Priv pl = new Priv()7
pl.var();
}
}
61
returns a boolean depending upon the object being an instance of the named class or
any one of its subclasses. For example, if a variable s1 is declared to be an instance of
the string class, then it can be checked if s1 is an instance of the string class as shown:
Object References
Each new class created adds another type that can be used just like simple types, when
a new variable is declared; classname can be used as a type. Such variables refer to
instance or object of that class. These variables are known as object reference. An
instance is an individual copy of the class template with its own set of data called
instance variable.
When the type of variable is declared as a class, it has a default value of null - a
reference of type Object, and is thus type-compatible with all other classes. The null
object has no value
A list of the class packages that are part of the Java class library are:
Java.lang: Classes that apply to the language itself which includes the object class, the
62
String class and the system class. It also contains the special classes for the primitive
types
(Integer, Character, Float)
java.util: Utility classes such as Date as well as simple collection classes such as
vector and Hashtable
java.io: Input and output classes for writing to, and reading from streams and for
handling files
java.applet: Classes to implement Java applets, including the Applet class itself as
well as the Audioclip interface.
The development environment may also include additional classes that provide other
utilities or functionality. Although these classes may be useful, they will not be
available to others, as they are not part of the standard Java library. This is
particularly important for applets are expected to run on any platforms. The classes
inside the Java package are guaranteed to be available in all Java environments.
Importing Class
Classes external to a program must be imported before they can be used. To import a
class, the import keyword should be used as given below:
import <classname>;
The classes in Java are arranged in hierarchical order. The Java library consists of a
number, of packages (as discussed earlier). These packages contain a set of related
classes. The whole path of the class must be specified to import a class from the Java
library, For instance, to import the Date class from the util package use the following
63
code.
import java.util.Date;
It is also possible to import all classes that belong to a package using the * symbol.
import java.awt.* ;
Note : All the classes in java.lang package are automatically imported when a
program is compiled.
Example 3.9
Open a new file in the editor and enter the following code:
import java.awt.Point;
//The following program illustrates the usage of the import keyword.
// Open a new file in the editor and enter the following code:
import java.awt.Point;
class Lib {
public static void main(String args[]) {
Point pl = new Point (2,2);
pl.x = 12;
pl.y = 12;
64
Run the file using java Lib
The point class is imported in line 1 of the program. An instance of this class is
created inside the main method, The variables in the object are initialized in lines 7
and 8 and displayed using println method.
Arguments to Java programs can be passed by appending them to the command line
when the Java program is run. These arguments can be grouped by using double
quotes that are removed before the arguments are passed to the program.
The Java program stores the command line arguments in the array of strings which is
passed To the main() method in the program. Inside the main() method, the arguments
can be handled by iterating over the array of arguments. The arguments are passed to
the main() method as an array of strings and to treat them as non-strings, they are to
be converted to the specfic type.
Example 3.10
Open a new file in the editor and enter the following code:
Class Arg {
public static void main(String args[]) {
65
System.out.println ("The first argument value is: “ + arge[0]);
}
}
Note: The example assumes that at least one argument is passed to the program. If the
program is executed without an argument, an error occurs. If more than one argument
is passed, it is ignored.
The forthcoming paragraphs deal with an important concept in Java, namely the
Constructors and Finalizers. Constructors are called whenever an instance of a given
class is created. Finalizers are used to destroy the objects created using constructors.
Basic Constructors
A constructor method is a special kind of method that determines how an object
is initialized when created. They have the same name as the class and do not have any
return type.
When the keyword new is used to create an instance of a class, Java allocates memory
for the object, initializes the instance variables and calls the constructor methods.
Every class has a default constructor that does not take any argument and the body of
it does not have any statements. Constructors can also be overloaded.
66
Example 3.11
Qpen a new file in the editor and enter the following code:
classCons {
int i;
int j;
Cons(int a,int b) {
i = a;
j = b;
}
void print() (
System,out.println ("The addition of " + i + " and " + j + " gives " + ( i + j ));
}
public static void main(String args[)) (
Cons c;
c = new Cons(10,10);
c.print ();
System.out.println (" ");
c = new Cons(50,50);
c.print ();
Sytem.out.printin (" "“);
67
The constructor passes arguments as is declared in line 4. It also indicates the print
method used to display the values of the constructor arguments.
The arguments to this are the arguments to the constructor. Example 3.12 illustrates
this concept.
Example 3.12
Open a new file in the editor and enter the following code:
class point{
int x,y;
point(int x,int y){
this.x=x;
this.y=y;
}
point(){
this(-1,-1)
}
public static void main(String args[]){
point p=new point();
System.out.println("x ="+ p.x +", y=" + p.y);
p=new point(10,10);
System.out.println("x ="+ p.x +", y=" + p.y);
}
}
68
Run the file using java Arg
In the example given above, the second constructor calls the first constructor and
initializes the instane variables.
Finalizer
Finalizer method functions in contradiction to the constructor method. Finalizers are
called Just before the object is garbage collected and its memory is reclaimed. The
finalizer method is represented by finalize(). The Object class defines a default
finalizer method, which does nothing. To create a finalizer method for the classes, the
£inalize() method can be overridden as shown below:
Overloading constructors
Constructors can also take varying numbers and types of parameters. This enables
creation of objects with the properties required.
Example 3.13
69
Open a new file in the editor and enter the following code:
Class Cload {
String pname;
int qty;
int price;
Cload(int prodgty, String prodname,int prodprice) {
pname = prodname;
qty = prodgty;
price = prodprice;
}
Cload(int q,String plname) (
pname = plname;
price = q;
qty = price/10;
}
Cload prods;
prods = new Cload(10,"Apples",10);
prods.print();
70
prods = new Cload(10,"Oranges");
prods.print();
prods = new Cload("Grapes",25);
prods.print ();
}
}
Save the file as Cloud.java
Compile the file using javac Cloud.java
Run the file using java cloud
Inner Classes
It is possible to nest a class definition within another class and treat the nested class
like any other method of the class.Such a class is called nested class, As a member of
its enclosing class, a nested class has privileges to access all class has privileges to
access all the members of the class enclosing it. A nested class can either be static or
non-static. nested classes are called as inner classes. While static nested classes are
just called as static nested classes,non-static nested classes are called as nested
classes.
NewTerm : An inner class is a nested class whose instance exists within an instance
of its enclosing class and has direct access to the instance members of its enclosing
instance.
71
class <EnclosingClass> {
class <InnerClass> {
<set of statements>
}
}
The interesting feature about the relationship between these two classes is not that the
InnerClass is inside the EnclosingClass. Apart from this feature, the instance of the
InnerClass can exist only within an instance of the EnclosingClass and it has direct
access to instance variables and methods
of its enclosing instance.
Example 3.14
Open a new file in the editor and enter the following code:
public class Parcel{
class Contents (
private int i=16;
public int value(){
return i;
}
}
Class Destination{
brivate String label;
Destination(String whereTo) {
label=whereTo;
}
String readLabel(){
return label;
}
}
public void ship(String dest) {
Contents c=new Contents();
72
Destination d=new Destination(dest) ;
System.out.println("Shipped "+c.value()+" item(s) to " + dest);
}
public static void main(String args[]){
Parcel p=new Parcel();
: p-ship("Congo");
}
}
The above example explains the usage of inner class. There are two inner class
definitions, each with its own variables/methods namely Contents and Destination.
The enclosing class has a method ship (String dest) which creates instances of the
inner classes and this called by the main() method.
More usage of inner classes can be seen while dealing with event handling.
Garbage Collection:
In Certain languages like C++, dynamically allocated objects must be manually
released by use of a delete operator. In Java deallocation happens automatically. The
technique that accomplishes this is called garbage collection.
Java has no malloc or free functions. Since every complex data structure is an object,
they are all allocated via the new operator, which allocates space for an object on the
73
heap of memory .
The memory available for objects is called a heap because the user doesn’t have to
think about
it. It is just a loosely collected heap of object instances. From new keyword, the user
actually gets a handle to an object and not the memory address.
The actual memory allocated for this object may move around, as the program runs,
but the User doesn’t have to worry about that'll that matters is that this memory will
be available for as long as the program cares for it. As soon as the user no longer have
any references of any kind to the object, the memory it is occupying will become
available for reuse by the rest of the system. The user’s doesn’t have to call free or
delete. This is known as garbage collection.
Garbage Collection only occurs sporadically during the execution of the program. It
will not occur simply because one or more objects exist that are no longer used.
Garbage Collection can also be known as litter recycling, because the user doesn’t
even have to drag the objects to the crub to have them collected. It’s just dropping and
forgetting them. The garbage collector runs whenever the system is idle, or when a
request allocation fails to find enough memory.
74
2.9 SUGGESTED READINGS AND REFERENCE
13. Internet.
75
UNIT 3: ARRAYS
Structure
3.0 Objectives
3.1 Introduction
3.2 Arrays
3,3 Summary
3.4 Keywords
3.5 Questions for Self Study
3.8 Suggested readings
3.0 OBJECTIVES
76
3.1 INTRODUCTION
3.2 ARRAYS
Arrays
An array is an object that stores a list of items. Each slot in an array holds individual
elements. An array should be of a single type, comprising of integers, strings and so
on. To create an array, a variable to hold the array is declared, and a new object is
created and assigned to it.
Declaring Array Variables
Array declaration is akin to any other variable declaration. Array variable indicates
the type of object that the array holds. It also indicates the name of the array followed
by empty brackets. The brackets may be inserted after the specification of the type
instead of succeeding the variable.
int arr[];
Creating Array Object
After declaring an array, create and assign objects to it. Two methods can be used to
create the array- initialization of the array or usage of the new keyword, The new
keyword creates an instance of the array. The number of elements that the array will
hold must be specified. The two modes of creating an array are given below:
int iarr [ ] = new int [ 10 ];
char carr[ ] = {‘a’, ‘b’,’c’,’d’};
1: class Array {
2: int I;
3: int da[] = (1,2, 3,4,5,6,7};
4: void disp() {
5 System.out.println(“Displaying Array Details”}
6: for (int i=0; I < 7; i++)
7: System.out.println(da[i] );
77
8: }
9: }
10: public static void main(Str ing args[]) {
11: Array d = new Array();
12: d.disp()
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Save the file as Array.java
¢Compile the file using javac Array.java
Run the file using java Array
78
produces an error. To avoid overrunning the end of an array, its length can be tested
using the length instance variable. This variable is available for all array objects
irrespective of the type. The usage is,
int len = arr.length
class Number1 {
int I;
int arr({] = new int [10];
vpid add() {
int j = 100;
for (i = 0; 1 < arr.length; i++) {
arr[i] = j;
j++;
}
}
void show() {
for (i=0; i < arr.length; i++) {
System.out.printin (“The “ + i + “ array element is “ +
arr(i]));
}
}
public static void main(String args[]) {
Numberl n = new Numberl();
79
n.add();
n.show();
}
}
Note: The line numbers given are not part of the source code and should not be
typed so.
Save the file as Numberl.java
Compile the file using javac Number1.java
Run the file using java Numberl
class coord {
int i=0;
int j=0;
80
int coor[][] = new int [3] [3];
yoia set() {
coor [0] [0] =1;
coor [0] [1]=0;
coor [0] [2]=0;
coor [1] [01=0;
coor [1] [1]=1;
coor [1] [2]=0;
coor [2] [0]=0;
coor [2] [1]=0;
coor [2] [2]=17
}
void show() {
for (i=0;1<3;i++) {
for (j=0;5<3;j++) {
System.out .print (coor [i] [J] + “ ”);
System.out.printin(" “);
}
}
public static void main(String args[])
Coord c = new coord();
c.set();
c.show();
81
method.
The array is displayed using the show () method.
Vector
A Vector is an array of object references. Internally, a Vector implements a strategy to
minimize reallocation and wasted space. Objects can be stored at the end of a Vector
by using the addElement method or inserted at a given index by the insertElementAt
method. An array of objects can be stored in a Vector using the copy Into method.
Example 4.4 demonstrates the usage of vector.
Example 4.4
Open a new file in the editor and enter the following code
1: import java.util.*;
2: class Cat {
3: private int catNumber;
4: Cat(int i) {
5 :catNumber = i;
6: }
7: void print() {
8 System.out.println ("Cat #" + catNumber) ;
9 :}
10:}
ll:class Dog {
12: private int dogNumber;
13: Dog(int i) {
14: dogNumber = i;
15: }
16: void print() {
17: System.out.println ("Dog 4" 4 dogNumber ) ;
18: }
19:}
20:public class CatsAndDogs {
21: public static void main(String args[]) {
22: vector cats = new Vector();
23: for(int i =0; I < 7 ;i++)
82
24: cats.addElement (new Cat(i));
25: cats.addBlement (new Dog(7)); //Not a problem to add a dog to cats:
26:for(int i = 0; i < cats.size(); i++)
27: ((Cat)cate.elementat (1)).print()1// Dog is detected only at run-time
28: }
29:}
Note: The line numbers given are not part of the source code and should not be
typed so.
The classes Cat and Dog are distinct ~ they have nothing in common except that they
are Objects (if we don’t explicitly say what class we are inheriting from, we
automatically inherit from Object).The Vector class, which comes from java.util,
holds Objects, so not only can we place Cat objects into this collection using the
Vector method addElement (), but we can also add Dog objects without complaint at
either compile-time or run-time. When we go to fetch out what we think are Cat
objects using the Vector method elementAt (), we get back a handle to an Object that
we must cast to a Cat. Then we have to Surround the entire expression with
parentheses to force the evaluation of the cast before calling the print () method for
Cat, otherwise we will get Syntax error. Then, at run, when we try to cast the Dog
83
object to a Cat, we will get an exception:
3.3 SUMMARY
An array stores a list of items. Each slot in an array holds individual elements.
An array should be of a single type.
Array declaration is similar to any other variable declaration.
To change and test the values of the array, use the array subscript expression.
To assign a value to a slot, include an assignment statement after the array
access expression.
Java does not support multidimensional arrays. However, an array of array can
be created.
3.4 KEYWORDS
1. What are arrays? How can values be stored in them? Should the datatype of each
element in the array be the same?
2. Give the three different ways of creating a string object.
3. How do we declare and create array objects?
4. How do we change the values of the elements in an array? How can we test the
values that an array holds?
5. What are multi - dimensional arrays? Does Java support them?
84
6. Sun Microsytems Java tutorial,
13. Internet.
85
UNIT4: STRINGS
Structure
1.0 Objectives
4.1 Introduction
4.2 Strings
4.3 Casting and Converting
4.4 Summary
4.5 Keywords
4.6 Questions for Self Study
4.7 Suggested readings
4.0 OBJECTIVES
Define Strings
86
4.1 INTRODUCTION
This unit provides a detailed description of strings. The manipulations that can be
done with strings is also dealt with. Casting and converting of various operators as
also methods is also elucidated in this unit.
4.2 STRINGS
Strings
A combination of characters is a string. Strings are instances of the class string. They
are real objects, and hence, enable combination, testing and modification. When as
string literal is used in the program, Java automatically creates instances of the string
class. Strings are unusual in this respect.
Example 4.5 delineates declaration and access of strings.
Open a new file in the editor and enter the following code
1: class Strings {
2: int i;
3: String names[ ] = ("Aswath", "Aswin", "Anand", "Aditya",
"Anirudh"};
4: void show() {
5: System.out.println ("My Favourite Names Are ");
6: for (i=0; i< 5; i++) {
7: System.out.println (names[i]);
8: }
9: }
10: public static void main(String args[]) {
11; Strings s = new Strings();
12: s.show();
13: }
14: }
Note: The line numbers given are not part of the source code and should not be
87
typed so.
88
String S=new String(chars,2,3);
System.out.println(s);
Hash table
Often it is necessary to store Strings and other data types in a manner that allows the
information to be found quickly. One of the ways to store information for fast lookup
is a hash table. A hash table stores information using a special calculation on the
object to be stored. A hash code is produced as a result of the calculation. The hash
code is used to choose the location in which to store the object. When the information
needs to be retrieved, the same calculation is performed, the hash code is determined
and a look up of that location in the table results in the value that was stored there
previously. Every object has the ability to be stored in a hash table. Class Object
defines method hashCode to perform the hash code calculation. Method hashCode is
overridden by String to provide a good hash code distribution based on the contents of
the String.
Example 4.6 demonstrates the hashCode method for two Strings containing “hello”
and“Hello”.
Example 4.6
Open a new file in the editor and enter the following code
1: class hash{
2:public static void main(String args[ ]){
3:String si="hello";
4:String s2="Hello";
5: System.out.println("The hash code for "+s1+ “is" + sl.hashCode(
6 System.out.println("The hash code for "+s2+ "is" + s2.hashCode( }
7:}
8 :}
Note: The line numbers given are not part of the source code and should not be
typed so.
89
The output appears as shown below:
The hash code for hello is 99162322
The hash code for Hello is 69609650
The hash code for each of the Strings is different because the Strings themselves are
lexicographically different.
String Arithmetic
The ‘+’ sign does not mean “addition” when it is used with String objects, The Java
string class has something called “operator overloading.” In other words, the “+" sign
when used with String objects, behaves differently than it does with everything else.
For Strings, it means: “concatenate these two strings.” When used with strings and
other objects, the + operator creates a single string that contains the concatenation of
all its operands.
What happens when a numerical value is added to a String? The complier calls a
method that turns
numerical value (int, float, etc.) into a String, which can then be “added” with the plus
sign. Any object or type can be converted to a string if the method toString()
implemented, To create a string, add all the parts together and output it .The +=
operator will also work for string.
Example 4.7 outlines the concatenation of two strings.
Example 4.7
Open anew file in the editor and enter the following code
class Arith {
string fname = "Aswath";
String lname = "Narayanan";void show()
{
system. out.printin ("The full name is " + fname + ” “ + lname);
}
public static void main(String args[]) {
Arith al = new Arith();
al.show();
Save the file as Arith.java
90
Compile the file using javae Arith,java
Run the file using java Arith
91
Returns a new String object with the replacemets
replace() made. Uses the old String if no match is found,
Returns a new String object with the case of all Ietters
changed. Uses the old String if no changes need to be
toLoweCase(),toUpperCase() made.
Returns a new String object with the whitespace
removed from each end. Uses a
trim() the old String if no changes need to be made.
Class equaldemo {
public static void main (String args{ ] ){
string s1="Hello”;
String g2="Hello”;
String s3="Good bye”;
String g4="HELLO”;
system.out .print1n (s1 + “equals” +s2 + “is” +s1.equals(s2));
system.out .print1n (s1 + “equals” +s3 + “is” +s1.equals(s3));
system.out .print1n (s1 + “equals” +s4 + “is” +s1.equals(s4));
92
Run the file using java equaldemo
class st{
public static void main(String args[]){String s="Now is the time for all
good men" + " to come to the aid of their country”
+” and pay their t axes”;
String s1 = "Hello world";
String s2="Hello";
String s3="HELLO";
System.out.println(s);
System.out.println (index of t = " +s.indexOf('t'));
System.out.println("last index of t= "+s.lastindexOf('t'));
System.out.println("index of(t,10) =" +s.indexOf('t',10));
System.out.println("last index of (t,60)=" + s.lastIndexOf(‘t’,60));
System. out .println (s1l.substring(6));
System. out .println(s1.substring(3,8));
System.out .println(s2.concat ("World") );
System.out.println(s2.replace('1', 'w'));
System. out .println(s3.toLowerCase ());
System.out.println(s1.trim()) ;
}
}
Save the file as st.java
Compile the file using javac st.java
Run the file using java st
93
Output appears as shown below
Now is the time for all good men to come to the aid of their country and pay their
taxes
index of t =7
last index of t =83
index of(t,10) = 11
last index of (t,60)=55
world
lo wo
HelloWorld
Hewwo
hello
Hello world
StringBuffer
StringBuffer is a peer class of String that provides much of the common use
functionality of strings. Strings represent fixed-length character sequences. String
Buffer represents varied length character sequences. StringBuffer may have characters
and substrings inserted in the middle, or appended at the end. The compiler
automatically creates a StringBuffer to evaluate certain expression, in particular when
the overloaded operators + and += are used with String object.
Example 4.10 demonstrates the usage of StringBuffer:
Open a new file in the editor and enter the following code
94
sb.append (integer .tostring (47) );
system. out.println (sb);
Save the file as buf.java
Compile the file using javac buf.java
Run the file using java buf
StringBuffer methods
Table 4.2 enlists the StringBuffer methods and their uses.
Method Use
ensureCapacity( Makes the StringBuffer hold at least the desired number of spaces
)
setLength( ) Truncates or expands the previous character string. If expanding,
pads with nulls
charAt( ) Returns the char at that location in the buffer.
95
setCharAt( ) Modifies the value at that location.
Table 4.2
The most commonly-used method is append (), which is used by the compiler when
evaluating String expressions containing the ‘+’ and ‘+=* operators. The insert ()
method has a similar form, and both methods perform significant manipulations to the
buffer rather than creating new objects.
96
precision than the smaller type, and hence no information is lost when the value is
cast. The casting of integers into floating– point values or an int to a float may cause
must be used. Converting the value result in loss of precision. Precedence of casting is
higher than that of arithmetic operations .A typical cast from an higher value to a
lower value.
(int ) (d / t);
Example 4.11 explains casting between primitive types.
Open a new file in the editor and enter the following code
Class Convert {
double x;
double y;
int z;
void prod(double a,double b) {
x= a;
y= b;
z= (int) ( a * b);
}
void print() {
System.out.println ("The value is " + z);
}
public static void main(String args[]) {
Convert con = new Convert ();
con.prod(10.94,94.30);
con.print();
}
}
Save the file as Convert.java
Compile the file using javac Convert.java
Run the file using java Convert
97
This example accepts two double values, calculates its product using the method
prod().The resulting value is printed using the print() method ,as an integer by casting
the result value at line 8.
Casting Objects
Instance of class can be cast to instance of other classes. There is only one restriction,
the class of the Object being cast and the class that it is being casted to must be related
by inheritance. Some object may not be explicitly cast .An instance of a subclass can
be used anywhere a superclass is expected because a subclass contains all the
information that a superclass contains.Casting an object to an imstance of that objects
superclass loses the information the original subclass provided and requires a specific
cast.To cast an Object to another Object .
(classname) object;
The classname is the class we want to cast the object to. Object is a reference to the
object being cast. Casting creates a reference to the old object of the type classname
and the old object continues to exist.
4.4 SUMMARY
A combination of characters is known as a string. Strings are instances of the
class String. The addition operator (+) can be used to create and concatenate
strings.
Casting is a mechanism of converting the value of an object or primitive type
into another type.
Casting between primitive types allows conversion of one primitive type to
another.This occurs most commonly between numeric types.
98
Instances of class can be cast to instances of other classes.
Conversion of primitive types to objects cannot be done explicitly. Primitive
type and objects are two different things. java.lang package includes several
special classes that correspond to each primitive type.
4.5 KEYWORDS
Strings, Casting
2. Are strings real objects? How can we combine, test and modify string?
5. What is casting? What are its uses? What are the objects on which casting can
be applied?
6. Why should we use conversion? What is the package that can be used for his
purpose?
99
6. Sun Microsytems Java tutorial,
13. Internet.
100
UNIT-5: INHERITANCE IN JAVA
Structure
5.0 Objectives
5.1 Introduction
5.2 Inheritance in Java
5.3 Super Class and Sub Class
5.4 Summary
5.5 Keywords
5.6 Questions for Self Study
5.7 Suggested readings
5.0 Objectives
At the end of this unit you will be able to
Define Inheritance in Java
Describe Super Class and Sub Class
101
5.1 Introduction
This unit introduces the concept of inheritance used frequently in Java. Subsequently
it provides a Super Class and Sub Class. The term inheritance brings to mind - huge
piles of money, large estates and farmhouses left to us by our ancestors! It also
conjures visions of the inherent genetic features and characteristics provided by our
forefathers. Let us try defining its meaning in the Object-ted context.
5.2 Inheritance In Java
102
inheriting the features of the object class has distinct features. Each of the subclasses
has been defined for a specific purpose. Thus the object class definition is found to be
abstract and further down the hierarchy, there are clear specifications to define an
object. If a class is defined without any superclass, the object class acts as its super
class. The Java class hierarchy is shown with some of its derived classes in Fig 5.2.
Java Class Hierarchy
Object
Boolean
Character
Compiler
Math
String
Number
Class
Runtime
Thread
Advantages of Inheritance
The major advantage of inheritance is reusability of code, once a class is defined and
debugged, it can be used to create new subclasses. In addition to saving a lot of time
and effort, retyping the same code becomes unnecessary. The next benefit is that data
and method of a super class are physically available to its subclasses .In case data and
methods of the super class are declared private, the derived class cannot access them
103
.To deal with this situation, protected is used.
Types of Inheritance
A very important fact to remember is that Java does not support multiple inheritance.
This means that a class cannot extend more than one class. Therefore following is
illegal −
Example
However, a class can implement one or more interfaces, which has helped Java get
rid of the impossibility of multiple inheritance.
104
Form of Inheritance
When a subclass is derived from a single super class, the inheritance is called single
inheritance and when It Is derived from more than one super class, it is called multiple
inheritances. Java supports single inheritance only.
Example 5.1 illustrates the concepts of super class and derived class. A super class
called WoodFurn and a derived class called woodTable are created.
Note:
The line numbers are provided for code reference and easy explanation. They
do not form part of the code.
The base class and the derived class are created and stored in separate files.
The filename for any class is similar to the class name with .java extension.
The files containing base class and derived class are compiled separately and
the derived class alone is run, since it contains the main() method.
To run base class separately include the main() method and initialize an object
of the base class type
Example 5.1
Class Wood {
String type = “teak";
String finish = "coarse";
void showDet() {
System.out.println ( “instance of class “+this ,getclass.getName () );
System.out.println(“===========================”);
System.out .println ("type of wood –“ + type);
System.out.printin ("finish is - " + finish);
}
}
105
Type the following code in another file
class WoodTable extends WoodFurn {
int legs=4;
void show( ) {
System.out.println("woodtype - " + type);
System.out.println("finish - " + finish);
System.out.println("legs - " + legs);
}
public static void main (String args[ ]) {
WoodTable t = new WoodTable( );
t.show( );
}
}
106
BufferedReader. These are used to accept input from the user.
Example 5.2
Open anew file in the editor and enter the following code:
import java.io.*;
class Numeral {
public int x;
void getiInt() {
try {
BufferReader br = new BufferedReader(new Input StreamReader
(System.in));
System.out.println("enter a number to find its square”);
String s=br.readLine();
x=Integer.parseInt(s);
}
catch(IOException e){ }
}
}
Save the file as Numberal.java and compile.
107
s.getInt();
s.retSquare();
}
}
Save the file as Square.java
Compile the file and run the class file using java
Class info {
protected string name = “ezhil”;
protected string add = “9 lal mohammed street”;
}
Save this file as Info.java and compile
108
Caution: Do not run this file
The derived class Info1 has a method disp( ),which displays the value of the attributes
in both base class and the derived class.
class Infol extends Info {
private int age =22;
public void disp() {
System.out.println(“name : ”” + name);
System.out.println(“name : ”” + name);
System.out.println(“name : ”” + name);
}
public static void main(string args[]) {
Infol i=new Info1;
i.displ();
}
}
Save the file as Info1.java
Compile the file and run the class file using java
109
5.3 Super Class and Sub Class
The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
Subclass A subclass is a class that derives from another class. A subclass inherits
state and behavior from all of its ancestors. The term superclass refers to a class's
direct ancestor as well as all of its ascendant classes.
Creating Subclasses
To create a subclass of another class use the extends clause in your class declaration.
As a subclass, your class inherits member variables and methods from its superclass.
Your class can choose to hide variables or override methods inherited from its
superclass.
Usage of super
Usage of the keyword super before the methods getDet () and showDet() in the
derived classes, enables accepting and displaying of details for all three classes. The
method getDet () will have an extra line before the try block in both the Books class
and Category class as follows
super .getDet ();
The showDet () method also has an extra line before displaying the details of its own
class, to display the details of its base classes, as follows
super. showDet ();
This concept is explored using another example. In Example 5.5, the name of a
country is accepted. A list of countries belonging to SAARC is provided. The name of
the country that is entered is compared with the list to ascertain if it belongs to
SAARC.
Example 5.5
Open a new file in the editor and enter the following code:
110
import java.io.*;
class Nations {
protected String name;
protected void get() {
try {
BufferedReader br = new BufferedReader (new InputStreamReader (System.
in)); System.out.println("enter name of a country ");
system.out.println("you can check if the country name you have entered is a
member of SAARC");
name=br.readLine();
} catch(IOException e) { }
}
void show() {
System.out.println(“Executing base class's show function from the derived
class ..."); System.out.println(“This is possible due to use of super");
System.out.println(“==============================");
System.out.println(“Your country name : “+name");
}
}
Save the file as Nation.java
Compile the file using javac Nations.java
111
System.out.println("Executing derived class's show
function………..”)’;
System.out .println("=========================");
System.out.println("SAARC countries are listed below ...");
for (i=0;i<7;i++)
{
System.out.println(names[i]);
}
}
public static void main(String args[]) {
Saarc s = new Saarc();
s.get();
s.show();
}
}
Save the file as Saarc.java
Compile the file using javac Saarc.java
Run the file using java Saarc
112
Bhutan
Maldives
The derived class saarc also has a method named show(). Actually the compiler must
execute this show() function, when called, because of overriding. Due to the presence
of the line number 5 in this derived class, the base class show() method is also
executed.
Inheritance is the process of inheriting all features from a class. The class from
which another class is derived is called base class or super class and the class
that is derived is called derived or sub class. Java class hierarchy has class
object. as its super class
The advantages of inheritance are reusability of code fee accessibility of
variables and of the base class by the derived classes.
Any derived class is it in the same package or in another package is ensured
the availability of the base class variables by the use of the modifier protected.
Whenever there are methods of the same name both in the base class as well
as in the derived class and if that method is called by main, the method in the
derived class is always executed. This concept is called overriding.
When an object of a class is initialized to an instance of its sub class and when
a method is called, the compiler verifies for the presence of that method
definition within the object’s class. But at runtime, since the stored reference
is an instance of the derived class, executes the derived class’s method.
5.5 Keyw0rds
113
5.7 Suggested readings
114
UNIT 6: OVERRIDING
Structure
6.0 Objectives
6.1 Introduction
6.2 Overriding
6.3 Object Classes
6.4 Polymorphism
6.5 Summary
6.6 Keywords
6.7 Questions for Self Study
6.8 Suggested Readings
6.0 Objectives
At the end of this unit you will be able to
Discuss Overriding
Explain Overriding
State Object Classes
Describe Polymorphism
115
6.1 Introduction
In the previous unit, we talked about superclasses and subclasses. If a class inherits a
method from its superclass, then there is a chance to override the method provided
that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the subclass
type, which means a subclass can implement a parent class method based on its
requirement.
6.2 Overriding
Overriding
Methods in the derived class can have a similar name as the base class. This is to
ensure that a method, when called in the program, works the same for both the base
and the derived class.
Definition
Overriding is the creation of a method in the subclass that has the same signature, i.e..
name number and type of arguments, as a method in the super class. This new method
hides the method of the super class.
When a method is called on an object, the Java compiler first searches for the method
in the class of that object. If the method is not found there, then the compiler searches
for the method in the hierarchy until it is found.
The concept is clearly elucidated in Example 5.4. Assume that a class hierarchy -
publish-----------books ----------- category exists. Each class has distinct attributes and
methods. Note that the name of methods in all three classes is identical.
Example 5.4
Open a new file in the editor and enter the following code:
import java.io.*;
class Publish {
protected String pubid;
protected String pname;
void getDet() {
116
try {
BufferedReader br = new BufferedReader (new
InputStreamReaderSystem.in));
System.out.println("enter data ");
System.out.printin("enter publisher id");
pubid=br.readLine();
System.out.println("enter publisher name");
pname=br.readLine();
} catch (IOException e) {}
}
void showDet() {
System.out.println("showing publisher details ...”};
System.out.println(“==========================”);
System.out.println("publisher id :" + pubid);
System.out.println("publisher name :" + pname);
}
}
Save the file as Publish.java.
Compile the using javac Publish.java
117
System.out println(“enter book name") ;
name=br- readLine();
} catch (roException e) {
}
void showDet() {
System.out.println( "showing book details --- ");
System.out.println(“=======================”) ;
System.out.println("author :" + aut);
System.out.println(“bookname :" + mame);
}
}
Save the file as Books.java
Compile the file using javac Books.java
Note: The line numbers given are not part of the source code and should not be
typed so.
118
system.out .print1n("showing category details ...");
system.out. println( “======================");
system.out.println("Category code :" + catcode);
}
public static void main(String args[]) {
Category c = new Category ();
¢.getDet();
c.showDet ();
}
}
Save the file as Category.java
Compile the file using javac Category.java
Run the file using java Category
If we input the category code as 100, the output appears as shown below:
showing category details...
====================
category code : 100
When the category class file is run, it is the category class’s methods that get
executed, though there are methods of the same name getDet () and showdet( ) in all
the three classes.
Overriding Constructors
Constructors are methods that have the same name as that of the class. It initializes the
values for all the class attributes. Constructors cannot be overridden. This is because
each class has its constructor with its own name.
The usage of super was illustrated along with a method that resulted in the execution
of the immediate super class’ method. Similarly to call the constructor of the base
class inside the derived class ,super(arguments) should be used. This can call the
constructor of its own base class and so on.
Dynamic Method Dispatch
Assume that an object of a class has been created. When a method is called on that
object the Java compiler ensures that a method definition exists within the class. At
runtime this object may refer to an instance of a subclass of the declared class. Java
uses the actual instance to decide the method that has to be called, in case the sub
119
class overrides the method being called.
This concept is illustrated in Example 5.6. The example consists of a base class called
Sphere. It has two methods, one to accept an integer as radius and another to calculate
the volume of the sphere. The sub class Hemisphere also has a method to calculate the
volume of the hemisphere.
Example 5.6
Open a new file in the editor and enter the following code:
import java.io.*;
class Sphere {
protected int r;
final float pi=3.14f;
sphere () {
r=0;
}
void get() {
try {
BufferedReader br = new BufferedReader (new Input StreamReader (System.
in) );
system.out.println("enter a number as radius ");
String aut=br.readLine();
r=Integer.parseiInt (aut);
} catch (IOException e) {}
}
float volume() {
float v=(4*pi*r*r*r)/3;
System.out.println("Volume of sphere is : " + v);
return v;
Save the file as Sphere.java
Compile the file using javac Sphere.java
Methods get () and volume() are defined in line numbers 8 and 16.
Open a new file in the editor and enter the following code:
120
class Hemisphere extends Sphere {
Hemisphere() {
Super();
}
float volume() {
float h=(2*pi*r*r*r) /3;
system.out.println(“Volume of hemisphere with radius "+ r +" is :”+h);
return h;
}
public static void main(String args[]) {
Sphere s = new Hemisphere () ;
s.get();
s.volume();
}
}
121
6.3 Object Class
The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't
know. Notice that parent class reference variable can refer the child class object,
know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be
of any type like Employee,Student etc, we can use Object class reference to refer that
object. For example:
Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
00:14/02:28
26.9M524
History of Java
122
6.4 Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object.
Any Java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all Java objects are polymorphic since any object will pass the
IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is through a
reference variable. A reference variable can be of only one type. Once declared, the
type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not
declared final. The type of the reference variable would determine the methods that it
can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its
declared type. A reference variable can be declared as a class or interface type.
Example
Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −
123
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −
Example
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
Virtual Methods
In this section, we will see how the behavior of overridden methods in Java
allows you to take advantage of polymorphism when designing your classes.
Example
/* File name : Employee.java */
public class Employee {
private String name;
private String address;
private int number;
124
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
125
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
Now, you study the following program carefully and try to determine its output −
126
}
}
Output
Constructing an Employee
Constructing an Employee
Here, we instantiate two Salary objects. One using a Salary reference s, and the other
using an Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at
compile time, and the JVM invokes mailCheck() in the Salary class at run time.
Here, at compile time, the compiler used mailCheck() in Employee to validate this
statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are
referred to as virtual methods. An overridden method is invoked at run time, no
matter what data type the reference is that was used in the source code at compile
time.
127
6.5 Summary
In this unit, we have learnt about the concept of overriding, object classes and
polymorphism
6.6 Keywords
Overriding, object classes , polymorphism, virtual method
6.7 Questions for Self Study
1. What is meant by overriding?
2. Discuss Object Classes.
3. Explain Virtual methods.
6.8 Suggested Readings
5. Internet
128
UNIT-7: DYNAMIC BINDING
Structure
7.0 Objectives
7.1 Introduction
7.2 Dynamic binding
7.3 Generic programming
7.4 Casting Objects
7.5 Instance of Operator
7.6 Summary
7.7 Keywords
7.8 Questions for Self Study
7.9 Reference books
7.0 Objectives
At the end of this unit you will be able to
Explain Dynamic binding
State Generic programming
Describe Casting Objects
Analyze Instance of Operator
129
7.1 Introduction
In this unit you will study about Dynamic binding , Generic programming, Casting
Objects and Instance of Operator .
Understanding Type
130
1) variables have a type
int data=30;
class Animal{}
static binding
When type of the object is determined at compiled time(by the compiler), it is known
as static binding.
If there is any private, final or static method in a class, there is static binding.
131
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
Output::dog is eating...
In the above example object type cannot be determined by the compiler, because the instance
of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
132
generic classes and interfaces as a group are known as the Java Collection
Framework. These classes represent various data structure designed to hold Objects
can be used with objects of any type. Unfortunately the result is a category of errors
that show up only at run time, rather than at compile time. If a programmer assumes
that all the items in a data structure are strings and tries to process those items as
strings, a run-time error will occur if other types of data have inadvertently been
added to the data structure. In JAVA, the error will most likely occur when the
program retrieves an Object from the data structure and tries to type-cast it to type
String. If the object is not actually of type String, the illegal type-cast will throw an
error of type ClassCastException.
JAVA 5.0 introduced parameterized types, such as ArrayList<String>. This made it
possible to create generic data structures that can be type-checked at compile time
rather than at run time. With these data structures, type-casting is not necessary, so
ClassCastExceptions are avoided. The compiler will detect any attempt to add an
object of the wrong type to the data structure; it will report a syntax error and will
refuse to compile the program. In Java 5.0, all of the classes and interfaces in the
Collection Framework, and even some classes that are not part of that framework,
have been parameterized. In this chapter, I will use the parameterized types almost
exclusively, but you should remember that their use is not mandatory. It is still legal
to use a parameterized class as a non-parameterized type, such as a plain ArrayList.
With a Java parameterized class, there is only one compiled class file. For example,
there is only one compiled class file, ArrayList.class, for the parameterized class
ArrayList. The parameterized types ArrayList<String> and ArrayList<Integer> both
use the some compiled class file, as does the plain ArrayList type. The type
parameter—String or Integer—just tells the compiler to limit the type of object that
can be stored in the data structure. The type parameter has no effect at run time and is
not even known at run time. The type information is said to be “erased” at run time.
This type erasure introduces a certain amount of weirdness. For example, you can’t
test “if (list instanceof {ArrayList<String>)” because the instanceof operator is
evaluated at run time, and at run time only the plain ArrayList exists. Even worse, you
can’t create an array that has base type ArrayList<String> using the new operator, as
in “new ArrayList<String>(N)”. This is because the new operator is evaluated at run
time, and at run time there is no such thing as “ArrayList<String>”; only the non-
133
parameterized type ArrayList exists at run time. Fortunately, most programmers don’t
have to deal with such problems, since they turn up only in fairly advanced
programming. Most people who use the Java Collection Framework will not
encounter them, and they will get the benefits of type-safe generic programming with
little difficulty.
In java object typecasting one object reference can be type cast into another object
reference. The cast can be to its own class type or to one of its subclass or superclass
types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to Typecast Objects with a dynamically loaded Class? - The casting of object
references depends on the relationship of the classes involved in the same hierarchy.
Any object reference can be assigned to a reference variable of the type Object,
because the Object class is a superclass of every Java class.
When we cast a reference along the class hierarchy in a direction from the root class
towards the children or subclasses, it is a downcast. When we cast a reference along
the class hierarchy in a direction from the sub classes towards the root, it is an upcast.
We need not use a cast operator in this case.
The compile-time rules are there to catch attempted casts in cases that are simply not
possible. This happens when we try to attempt casts on objects that are totally
unrelated (that is not subclass super class relationship or a class-interface relationship)
At runtime a ClassCastException is thrown if the object being cast is not compatible
with the new type it is being cast to.
134
A reference variable whose type is an interface that is implemented by a super
class of the class from which the object was instantiated.
Consider an interface Vehicle, a super class Car and its subclass Ford. The following
example shows the automatic conversion of object references handled by the compiler
interface Vehicle {
}
class Car implements Vehicle {
}
class Ford extends Car {
}
Let c be a variable of type Car class and f be of class Ford and v be an vehicle
interface reference. We can assign the Ford reference to the Car variable:
I.e. we can do the following
'''Example 1
c = f; //Ok Compiles fine'''
Where c = new Car();
And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are
compatible (sub class - super class relationship), i.e., the type Car can hold the type
Ford since a Ford is a Car.
'''Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation
error'''
Where c = new Car();
And v is a Vehicle interface reference (Vehicle v)
The compiler automatically handles the conversion (assignment) since the types are
compatible (class - interface relationship), i.e., the type Car can be cast to Vehicle
interface type since Car implements Vehicle Interface. (Car is a Vehicle).
Casting Object References: Explicit Casting
Sometimes we do an explicit cast in java when implicit casts don't work or are not
helpful for a particular scenario. The explicit cast is nothing but the name of the new
"type" inside a pair of matched parentheses. As before, we consider the same Car and
135
Ford Class
class Car {
void carMethod(){
}
}
class Ford extends Car {
void fordMethod () {
}
}
We also have a breakingSystem() function which takes Car reference (Superclass
reference) as an input parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford
Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the
instanceof operator to determine the type of object at run time.
public void breakingSystem (Car obj) {
obj.carMethod();
if (obj instanceof Ford)
((Ford)obj).fordMethod ();
}
To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car
object referenced by obj as if it is a Ford object. Without the cast, the compiler will
give an error message indicating that fordMethod() cannot be found in the Car
definition.
The following program shown illustrates the use of the cast operator with references.
Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes
are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class.
Any class that does not explicitly extend some other class will automatically extends
the Object by default. This code instantiates an object of the class Ford and assigns
the object's reference to a reference variable of type Car. This assignment is allowed
as Car is a superclass of Ford. In order to use a reference of a class type to invoke a
method, the method must be defined at or above that class in the class hierarchy.
Hence an object of Class Car cannot invoke a method present in Class Ford, since the
method fordMethod is not present in Class Car or any of its superclasses. Hence this
136
problem can be colved by a simple downcast by casting the Car object reference to
the Ford Class Object reference as done in the program. Also an attempt to cast an
object reference to its Sibling Object reference produces a ClassCastException at
runtime, although compilation happens without any error.
class Car extends Object {
void carMethod() { } }
class HeavyVehicle extends Object { }
class Ford extends Car {
void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }
}
class Honda extends Car {
void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); }
}
public class ObjectCastingEx {
public static void main(String[] args) { Car obj = new Ford(); // Following will result
in compilation error // obj.fordMethod(); //As the method fordMethod is undefined for
the Car Type // Following will result in compilation error //
((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in the HeavyVehicle
Type // Following will result in compilation error ((Ford) obj).fordMethod();
//Following will compile and run // Honda hondaObj = (Ford)obj; Cannot convert as
they are sibblings } }
One common casting that is performed when dealing with collections is, you can cast
an object reference into a String.
import java.util.Vector;
public class StringCastDemo {
public static void main(String args[]) { String username = "asdf"; String password =
"qwer"; Vector v = new Vector(); v.add(username); v.add(password); // String u =
v.elementAt(0); Cannot convert from object to String Object u = v.elementAt(0);
//Cast not done System.out.println("Username : " + u); String uname = (String)
v.elementAt(0); // cast allowed String pass = (String) v.elementAt(1); // cast allowed
System.out.println(); System.out.println("Username : " + uname);
System.out.println("Password : " + pass); } }
Output
Username : asdf
137
Username : asdf
Password : qwer
138
result = hV instanceof HeavyVehicle;
System.out.print("hV is an HeavyVehicle: " + result + "\n");
result = T instanceof HeavyVehicle;
System.out.print("T is an HeavyVehicle: " + result + "\n");
result = hV instanceof Truck; System.out.print("hV is a Truck: " + result + "\n");
result = hv2 instanceof HeavyVehicle;
System.out.print("hv2 is an HeavyVehicle: " + result + "\n");
hV = T; //Sucessful Cast form child to parent
T = (Truck) hV; //Sucessful Explicit Cast form parent to child
}
}
Output
hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false
Summary
7.7 Keywords
Dynamic Binding, Generic, Casting objects
139
7.9 Reference Books
4. Internet.
140
UNIT 8: ABSTRACT CLASS
Structure
8.0 Objectives
8.1 Introduction
8.2 Abstract Class
8.3 Interface in Java
8.4 Package in Java
8.5 UTIL package
8.6 Summary
8.7 Keywords
8.8 Unit-end exercises and answers
8.9 Reference books
8.0 Objectives
At the end of this unit you will be able to
Define Abstract Class
Describe Interface in Java
State Package in Java
Explain UTIL package
8.1 Introduction
In this unit is we will learn about. Abstract Class, Interface in Java, Package in Java
and UTIL package
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
141
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
2. Interface (100%)
Points to Remember
o It cannot be instantiated.
o It can have final methods which will force the subclass not to change the body
of the method.
142
Example of abstract class
A method which is declared as abstract and does not have implementation is known as
an abstract method.
In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.
143
abstract class Bike{
abstract void run( );
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
144
The usage of this modifier is discussed in Example 5.7, which accepts the radius of a
circle and calculates its circumference and area.
Example 5.7
Open a new file in the editor and enter the following code:
import java.io.*;
class Circum {
public static final float pi = 3-14f;
private int x;
public void getint() {
try {
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
System.out.println("enter a number for radius");
String s=br.readLine();
x=Integer.parseInt (s);
} catch(IOException e) { }
}
public void cir() {
float c = (2*pi*x);
System.out.println("circumference of circle :" + c);
}
public void area () {
float a = (pi*x*x);
System.out.println("area of circle : " + a);
}
public static void main(String args[]) {
Circum j = new Circum();
j.getInt();
j.cir();
area();
}
}
145
Save the file as Circum,java
Compile the file using javac Circum.java rat
Run the file using java Circum
146
Fig. 5.3
The classes Employees, Teaching and Non-Teaching are all abstract classes. This is
because an instance of these classes cannot be created. It will not contain full details.
Take the case of Professors .An instance of Professors class has attributes of Teaching
class, the Employee class and as well some of its own .Thus the instance is well
defined. We should note that the above mentioned classes are placed higher in the
hierarchy and they also act as super classes for the classes Professors, Lecturers,
Clerical and Administrative classes
Java’s class hierarchy provides a number of classes that are abstract. Some of them
are Number class, Security manager class, Class Loader class; etc. The Number
abstract class has derived classes like Integer, Long, Float and Double
Interface in Java
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
There are mainly three reasons to use interface. They are given below.
147
o By interface, we can support the functionality of multiple inheritance.
Syntax:
interface <interface_name>{
Since Java 8, interface can have default and static methods which is discussed later.
The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
148
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Output :Hello
149
8,4 PACKAGE IN JAVA
Java Package
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
150
Simple example of java package
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
Note: The line numbers given are not part of the source code and should not be
typed so.
If you are not using any IDE, you need to follow the syntax given below:
151
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
152
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
153
obj.msg();
}
}
Output: Hello
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
154
the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
155
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output: Hello subpackage
There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
156
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class fil
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
Output:Welcome to package
o Temporary
o By -classpath switch
o Permanent
o By creating the jar file, that contains all the class files, and copying the
jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by
the public class name.
157
class A{}
class B{}
public class C{}
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
java.util
The basic utility classes required by the programmer are provided by this #.
Class Description
158
the List interface. The class is declared as:
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
The class methods are extended from the
AbstractCollection<E> class.
AbstractMap.Simple The class instance is used for maintaining the value and
Entry<K,V> key. The class is declared as:
public static class AbstractMap.SimpleEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the Object class.
AbstractMap.Simple The class instance is used for maintaining the value and
ImmutableEntry<K, key which is immutable. The class is declared as:
V> public static class
AbstractMap.SimpleImmutableEntry<K,V>
extends Object
implements Map.Entry<K,V>, Serializable
The class methods are extended from the Object class.
159
The class methods are extended from the
AbstractCollection class.
160
Arrays The class contains various methods which can be used for
the performing large number of operations on arrays. The
class is declared as:
public class Array extends Object
The class methods are extended from the Objetct class.
161
The class methods are extended from the Object class.
EventListenerProxy It is the wrapper class for the Event Listener. The class is
declared as:
public abstract class EventListenerProxy extends Object
implements EventListener
The class methods are extended from the Object class.
EventObject All the objects of Event states are derived from this class.
The class is declared as:
public class EventObject extends Object
162
implements Serializable
The class methods are extended from the Object class.
163
IdentityHashMap<K, The class is an implementation of the map interface for
V> hash tables. The class is declared as:
public class IdentityHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Serializable, Cloneable
The class methods are extended from the
AbstractMap class.
164
class is declared as:
public abstract class ListResourceBundle
extends ResourceBundle
The class methods are extended from the ResourceBundle
class.
Locale.Builder Instances of the class are used to make the Locale class
objects. The class is declared as:
public static final class Locale.Builder
extends Object
The class methods are extended from the Object class.
165
The class methods are extended from the
AbstractQueue<E> class.
Properties A wide set of properties are defined by this class. The class
is declared as:
public class Properties
extends Hashtable<Object,Object>
The class methods are extended from the
Hashtable<Object,Object> class.
166
locale. The class is declared as:
public abstract class ResourceBundle
extends Object
The class methods are extended from the Object class.
SimpleTimeZone The class instances represent time zone to be used with the
Georgians Calendar. The class is declared as:
public class SimpleTimeZone
extends TimeZone
The class methods are extended from the TimeZone class.
167
extends Object
implements Enumeration<Object>
The class methods are extended from the Object class.
TimerTask The instances of the class represent various tasks which are
scheduled using the timer. The class is declared as:
public abstract class TimerTask
extends Object
implements Runnable
The class methods are extended from the Object class.
TimeZone The instances of the class represent the offset of the time
zone. The class is declared as:
public abstract class TimeZone
extends Object
implements Serializable, Cloneable
The class methods are extended from the Object class.
168
public final class UUID
extends Object
implements Serializable, Comparable
The class methods are extended from the Object class.
WeakHashMap<K,V The class implements the map interface based on the hash
> table. The class is declared as:
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>
The class methods are extended from the extends
AbstractMap<K,V> class.
8.6 SUMMARY
In this unit you studied about Abstract Class , Interface in Java , Package in Java
And UTIL package
8.7 KEYWORDS
169
3. Write short note on Packages and UTIL Package.
8.9 REFERENCE BOOKS
1. David J. Eck Introduction to Programming Using Java.
2. Elliotte Rusty Harold Java I/O published by O'Reilly
3. Ken Arnold, James Gosling . The Java Programming Language
170
UNIT 9: Event and GUI Programming
Structure
9.0 Objectives
9.1 Introduction
9.2 Event Handling in Java, Event Types , Mouse and key events, GUI Basics
9.3 Summary
9.4 Key words
9.5 Questions for Self Study
9.6 Suggested readings
9.0 OBJECTIVES
171
9.1 INTRODUCTION
In this unit we learn about Event Handling in Java, Event Types, Mouse and key
events , GUI Basics
Java Abstract Windowing Toolkit (AWT) communicates these actions to the program
using events. When the user initiates an action, the AWT generates an event and
communication it to event handlers. These event handlers can respond to the events
appropriately.
The whole of the event handling in Java 1.0 AWT is done using two method action ()
and handlevent ( ) method. The action () method has three parameters namely the
event that has occurred the x and y co-ordinates at which this event occurred. To find
the AWT component (like button, checkbox, radio button, text box discussed in the
next chapter) in which the event was generated, the instance of operator is used. The
handle event () method is called automatically for an object and an event object is
created and passed on to it. This type of event handling had various problems which is
addressed and solve in java V1.1
In the new event model, an event is propagated from a "Source" object to a "Listener
172
“object by invoking a method on the listener and passing in the instance of the event
subclass which defines the event type generated. To say it in simple terms, when an
event is fired, it is received by one or more listeners that act on that event. Each event
listener is an object of a class that implements a particular type of listener interface.
Event types are encapsulated in a class hierarchy rooted at java.util.Eventobject and
one level below this is java.awt.AWTEvent package. Given below are some of the
common terms related to event handling:
In an AWT program, the event source is typically a GUI component and the listener
id commonly an "adapter" object which implements the appropriate listener (or set of
listeners) in order for an application to control the flow/handling of events. The
listener object could also be another AWT component that implements one or more
listener interfaces.
All AWT event sources support a multicast model for listeners. This means the
multiple listeners can be added and removed from a single source. There is no
guarantee about the order in which the events are delivered to a set of registered
listeners for a given event on a given source .
HANDLING AN EVENT
The primary design goals of the new model in the AWT are;
173
To make it simple and easy to learn
To support c clean separation between application and GUI code
To facilitate the creation of robust event handling code which is less error-
prone(strong compile-time checking)
To make it flexible enough to enable varied application models for event flow
and Propagation
To support backward binary compatibility with the old model
Whenever an AWT component wants to handle its own events, the component’s
subclass created has to do two things:
The delegation method is the best-suited method to handle events. It is not possible
for a component to handle its events at all times. Hence this should be assigned to a
different object called listeners. This process is called delegation. Each component
class in the AWT has one addxxxListener () method for each event type that the
component generates.
The AWT provides two conceptual types of events: low-level and semantic. An
Eventlistener interface typically has a separate method for each distinct event type the
event class represents. It is also divided into low-level and semantic.
174
Low -level event
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener
Semantic Events
175
ItemEvent ("item state has changed")
TextEvent ("the value of the text object changed")
Mouse Events
These are generated whenever a mouse is moved, clicked, pressed, released, etc. The
MouseEvent Class represents these events as six constant values. This class has
method to get the co-ordinates at which a mouse event has occurred. The mouse move
and mouse drag are treated differently from the other four types namely mouse
pressed, mouse released, mouse entered and mouse exited. Hence there are two types
of mouse event listeners - MouseListener and MouseMotionListener.
176
}
The following illustrates the usage of mouse event listeners. Watch out for messages
on the status line of the applet as and when there is a mouse event performed by the
user. It also shows the co-ordinates at which such an event has occurred.
Example 10.2
Open a new file in the editor and type the following code:
import java.awt. *;
import java.awt. event. *;
import java. applet. *;
public Class MouseTest extends Applet implements MouseListener,
MouseMotionListener ({
Public void init () {
addMouseListener(this);
addMouseMotionListener (this);
}
public void mouseClicked (MouseEvent e) (
showStatus (“mouse clicked at “+e. getX () +","+e. getY ());
}
public void mouseEntered (MouseEvent e) (
showStatus(“mouse entered at "+e.getx()+", "+e.getY());
for(int i=0;i<1000000; ++i);
}
public void mouseExited(MouseEvent e) {
showstatus(“mouse exited at “+e.getx()+","+e.getY());
}
public void mousePressed (MouseEvent e){
177
showStatus ("mouse pressed at age ‘’+e.getx() +’’,’’+e.getY());
}
public void mouseDragged (MouseEvent e){
showStatus ("mouse dragged at ‘’+e.getx()+’’,’’+e.getY());
}
public void mouseMoved (MouseEvent e){
showStatus ("mouse moved at ‘’+e.getx()+","+e.getY());
}
}
KEYBOARD EVENT
These are generated on pressing or releasing a key. The keyEvent class contains
constants to represent the keys pressed or typed. The event listener corresponding to
these types of event is the KeyListener.This interface has the following definition;
178
The following example clarifies the usage of key event listeners. This applet contains
a label and a text field (dealt in detail in next chapter), Recently typed character in the
text field is displayed in the status line. Here the text field delegates its key events to
the applet.The add () method adds the components to the applet.
Example 10.3
Enter the following code in a new file and save the file as KeyTest.java
import java.awt. *;
import java.awt.event.*;
import java. applet. Applet;
public class KeyTest extends Applet implements KeyListener {
Public void init () {
Label l=new Label ("Enter characters");
add (1);
TextField tf = new TextField (20);
tf. addKeyListener (this);
add(tf);
)
Public void keyPressed (KeyEvent e) {}
public void keyReleased (KeyEvent e) {}
Public void keyTyped (KeyEvent e) {
showStatus ("Recently typed character in the text field is:’’+e. getKeyChar ());
}
}
On execution of this, the applet as shown in fig 10.3 is obtained.
179
User Interface Components
A place in which the various drawing needs to be done must be provided and this is
called the container the container is derived from java.awt. Container class. The
elements of the user interface are called components. These components are derived
from the java.awt. Component class.
The Component class is the abstract superclass of the nonmenu-related Abstract
Window Toolkit components. All the user interface components and container classes
and derived from this class. This class is responsible for a variety of activities like
display. Event handling and front management.
These are two major sets of classes derived from the component class:
CONTAINER classes-They are generic AWT components that can contain other
components.
USER INTERFACE COMPONENT classes-These include components like
button, lable etc.
CONTAINERS
A generic Abstract Window Toolkit (AWT) container object is a component that can
contain other AWT components. User interface components added to a container are
tracked in a list. The order of the list will contain the components’ front-to-back
stacking order within the container. It no index is specified when adding a component
180
to a container. It will be added to the end of the list. Components have to be
necessarily added to a container if they have to be displayed on the screen. Fig. 10.4
shows the class hierarchy of the classes that can act as container.
The Applet class is derived from the Panel class and, hence, can act as a container.
This property applet shall be exploited by adding user interface components and other
container directly to the applet.
NOTE: The Applet class, though derived from Panel, does not belong to the AWT
package.
181
The Component class defines a number of methods that can be used on any of the
classes that are derived from it. The methods listed below in table 10.1 can be used on
all UI components as well as containers.
Method DESCRIPTION
setSize (Dimension d) Resizes the corresponding components it
has width d. width and height d. height
setSize (int width, int height) Resizes the corresponding components so
that it has width and height
setFont (font f) Sets the font of the corresponding
setEnabled (boolean b) Enables or disables the corresponding
components, depending on the values of
the parameter b.
setVisible (Boolean b) Shows or hide the corresponding
component depending on the value
parameter b
setForeground (Color c) Sets the foreground color of the
corresponding component
setBounds (int x, int y, int width, int Moves and resizes the corresponding
Height) components.
182
SetBounds (Rectangle r) Moves and resizes the corresponding
components to conform to the new
bounding rectangle r.
setBackground (Color c) Sets the background color of the
corresponding component
getBackground () Gets the background color of the
corresponding component
getBounds () Gets the bounds of the corresponding
component in the form of a Rectangle
object
getfont () Gets the font of the corresponding
component.
getForeground () Gets the foreground color of the
corresponding component.
getsize () Returns the size of the corresponding
component in the form of a Dimension
object
Table 10.1
The various user interface components have been shown in Fig. 10.5. The following
sections will discuss each of these components in detail.
To effectively use these components, the following steps have to be carried out.
First, the user interface component has to be created using the constructor of the
corresponding class. For example, to create a Button object, the following code
fragment can be used:
183
Depending on the user interface component, it is necessary to handle the event
generated by it. There are two ways of handling events as mentioned in the last
chapter. But it is always wise to use listeners rather than letting the component
handle its events by itself.
To determine the component in which an event has occurred, it is necessary to
Use inner classes which was dealt in the fourth chapter. Each object has an inner
class defined for is that implement their respective event listeners. The object of
this inner class forms a parameter addXXXListener () function in its outer class.
The user interface component classes also have a number of method that can be used
to change the attributes of the component like, the label of a button, text of a text field
etc. The user interface components classes including their events and methods, are
discussed next
184
9.4 KEYWORDS / GLOSSARY
185
UNIT 10: PANELS
Structure
10.0 Objectives
10.1 Introduction
10.2 Panels , Frames, Layout Managers –(Flow Layout, Border Layout, Grid
Layout)
10.5 Summary
10.6 Key words
10.7 Questions for Self Study
10.8 Suggested readings
10.0 OBJECTIVES
186
10.1 INTRODUCTION
This unit illustrates the layout manager classes that are used to position the components in a
container. This chapter also discusses the classes in AWT that allow creation of pop-up
windows, menus and dialogs. It also gives an introduction to creating stand-alone Java
programs using AWT.
10.3 PANELS
The Panel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the Container class.
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
187
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
Layout Managers
The layout manager classes are a set of classes that implement the java
AWT.LayoutManager interface and help to position the components in a container. The
interface takes the task of laying out the child components in the container. This task is
achieved by resizing and moving the child components. The advantage of this type of
mechanism is that when the container is resized the layout manager automatically updates the
interface.
The basic layout managers include:
188
FlowLayout
BorderLayout
GridLayout
GridBagLayout
CardLayout
The following step have to be undertaken in order to derive the benefits of layout managers.
The first step is to instantiate a layout manager class, such as FlowLayout,
BorderLayout etc. The constructor of these classes, which comes in different flavors,
can be used to create a new layout manager object.
The next step is to associate the layout manager with the container on which it should
operate .The method setLayout () sets the layout manager of a container.
Once the layout manager for the container is set, components added to it will be arranged
depending on the layout specified.
Flow Layout
The FlowLayout class is a simple manager that works like a word processor. Components are
displayed with their preferred size in the order in which they are added to the container. The
flow layout lays out components linewise from left to right .When the line of components is
filled, flow layout creates a new line and continues laying out components on the next line.
Like a word processor a FlowLayout +
FlowLayout can be created using the constructors given in Table 11.1. 1
Constructor Description
FlowLayout( ) Constructs a new flow layout with centered alignment,
leaving a vertical and horizontal gap of 5 pixels.
FlowLayout(int align) Constructs a new flow layout with the alignment specified
leaving a vertical and horizontal gap of 5 pixels.
FlowLayout(int align , Constructs a new flow layout with the alignment specified
Int vgap, int hgap) leaving a vertical and horizontal gap as specified.
Table 11.1
The various methods that can be used in combination with the flow layout is given in Table
11.2.
189
Method Description
getAlignment( ) Gets the alignment for the layout.
setHgap(int hgap) Sets the horizontal gap for the specified layout.
setVgap(int vgap) Sets the vertical gap for the specified layout.
Table 11.2
Example 11.1 creates an applet that uses the flow layout to arrange the user interface
components.
Example 11.1
Enter the following code in a file and save it as FlowTest.java.
import java.awt.*;
public class FlowTest extends java.applet.Applet {
String str[ ]= {"One", "Two", "Three", "Four","Five","Six","Seven"};
public void init( ) {
setLayout (new FlowLayout ());
for(int i=0;i<str.length; ++i)
add(new Button(str[i]));
}
}
190
The init ( ) method instantiates an object of FlowLayout class and associates it with the
applet. Then, a few buttons are created and added to the applet. The output of the program
(Fig. 11.1) that the buttons are added to the applet from left to right. When the first line is
filled, the buttons are added to the next line, again from left to right. If a line is half filled, the
buttons are arranged centered, since, the default FlowLayout alignment is FlowLayout.
CENTER.
Grid Layout
The GridLayout class lays out components in a way very similar to a spreadsheet – in rows
and columns. Specifying the number of rows and columns in the grid creates the GridLayout.
The components in a grid are resized to fit their cell. All components in a grid layout are of
the same size. The position of a component in a grid is determined by the order in which the
components are added to the grid. Components are displayed from left to right and top to
bottom.
The grid layout can be constructed using the constructors listed in Table 11.3.
Constructor Description
GridLayout( ) Creates a grid layout with a default of one
column per component in a single row.
GridLayout(int rows, int cols) Creates a grid layout with the specified rows
and columns.
GridLayout(int rows, int cols, Creates a grid layout with the specified rows and
int hgap, int vgap) columns and specified horizontal and vertical gaps.
Table 11.3
The various methods that can be used in conjunction with the grid layout are listed in Table
11.4.
Method Description
191
getColumns( ) Gets the number of columns in corresponding layout.
getRows( ) Gets the number of rows in the corresponding layout.
getHgap( ) Gets the horizontal gap for the corresponding layout.
getVgap( ) Gets the vertical gap for the corresponding layout.
setColumns(int cols) Sets the number of columns to the specified number in
the corresponding layout
setHgap(int hgap) Sets the horizontal gap to the value specified in the corresponding
layout
setVgap(int vgap) Sets the vertical Bap to the value specified in
the corresponding layout
setRows(int rows ) Sets the number of rows in the corresponding
layout the specified value
Table 11.4
The Grindlayout object is associated with a container by using the setLayout ( ) method. The
components added to the container occupy one cell each. The first component is placed in the
first element of the grid. The subsequent components added are placed in adjoining cells,
from left to right. When the right hand side of the container is reached, the components are
added to the next row, again, from left to right.
Grid layout is often used along with Panels to divide the screen space into number of cells.
The components added to the panels are to be fitted inside the cell.
Example 11.2 demonstrates the grid layout arrangement.
Example 11.2
Enter the following code in a file and save it as GridTest.java.
import java.awt.*;
public class GridTest extends java.applet.Applet {
public void init() {
setFont (new Font ("TimesRoman", Font .BOLD+Font . ITALIC, 24));
setLayout (new GridLayout (3,4,10,10));
for(int i=1;i<=12;++i)
add(new Button(""+i));
}
}
192
The output is shown in Fig. 11.2
In line 4 of the example, the font of the applet is set using the setFont () method. This method
belongs to the component class and bears no relation to the setFont() method used with
Graphics class objects. In line 5, a GridLayout object is created with 3 rows and 4 columns
and with horizontal and vertical gaps of 10 pixels each. The layout of the applet is set using
the setLayout () method.
In lines 6 and 7, 12 buttons are added to applet. Each of these buttons occupies a cell in the
grid. These buttons are separated by a horizontal and vertical gap of 10 pixels each as
specified in the constructor of the GridLayout ().
BorderLayout
The BorderLayout class enables specification, i.e., where on the border of a container each
component should be placed. All areas need not be filled. The size of the areas will depend
on the components they contain.
With border layout, the placement of the component is specified as being, North, South, East
and West. The border layout resizes the Center component to fill the remaining center space.
The various constructors that can be used to create a border layout is given in Table 11.5.
Constructor Description
BorderLayout( ) Creates a new border layout with no gap between
the components
Table 11.5
The various methods that can be used in conjunction with the border layout is given in Table
193
11.6.
Method Description
getHgap( ) Returns the horizontal gap between components
getVgap( ) Returns the vertical gap between components
setHgap(int hgap) Sets the horizontal gap between components to
the value specified
setVgap(int vgap) Sets the vertical gap between components to the
value specified
Table 11.6
To add a component to a container with BorderLayout, an add ( ) method, that is slightly
different from the one we have been using, is used. The following code fragment adds a
component to the right border of the container.
add ( “East”, mybutton)
Similarly, North, South, West and Center can be used to place the component at the top,
bottom, left and the center of the container respectively. The components in the North and
South positions are sized to fit the container horizontally, but they are also sized to the
preferred height. The East and West components are sized to their preferred width, but they
are stretched to fill the available height. The Center component is sized to fit any remaining
area, ignoring its preferred size altogether.
The border layout is used when components are to be grouped on the borders of a container,
such as positioning of scroll bars on the bottom or right side of a container.
GridBagLayout
The GridBagLayout divides a container into a grid of equally sized cells. In this kind of
layout, a component can occupy more than one cell, if necessary. The total area occupied by
component is called its display area. We can specify the location of each component in this
layout, by specifying its x and y coordinates. The upper left corner of the GridBagLayout has
the coordinates (0,0). The x and y coordinates are specified by gridx and gridy respectively.
Similarly, gridwidth and gridheight specify the width and the height of the component,
respectively. The default value for the height and the width is one.
We can adjust the size of the component, when its size is less than the display area. The mode
of adjustment is specified by fill. If it takes the value GridBagLayout. NONE then the size of
the component remains unchanged. If the value is GridBagConstraints.HORIZONTAL then
the component is stretched horizontally. If the GridBagConstraints. VERTICAL then the
194
component is stretched vertically. If the GridBagConstraints.BOTH then the component is
stretched in both directions.
When the component is smaller than its display area, anchor determines where to place the
component. The values of the anchor are:
GridBagConstraints.CENTER
GridBagConstraints.NORTH
GridBagConstraints.NORTHEAST
GridBagConstraints.EAST
GridBagConstraints.SOUTHEAST
GridBagConstraints.SOUTH
GridBagConstraints.SOUTHWEST
GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
weightx and weighty determine how to distribute space. The GridBagLayout class contains
only one constructor, namely, GridBagLayout (). The methods of the class are listed in
Table 11.7.
Method Description
addLayoutComponent(Component c, Object a)Adds the component c to the layout using the
constraints specified by the object a
addLayoutComponent(String s, component c) Adds the component c with the name s to the
layout
getConstraints(Component c) Returns the constraints for the component c
getLayoutAlignmentX (Container c) Returns the alignment along the x-axis of the
container c
getLayoutAlignmentY (Container c) Returns the alignment along the y-axis of the
container c
getLayoutDimensions( ) Returns the Dimensions for the layout grid
GetLayoutInfo(Container c, int f) Prints the layout constraints
getLayoutOrigin( ) Returns the origin of the layout grid
getLayoutWeights( ) Returns the weights of the rows and columns
of the layout grid
195
invalidateLayout(Container c) Invalidates the layout
layoutContainer(Container c) Lays out the container c using the grid bag
layout
location(int x, int y) Returns the cell in the layout grid containing
the point specified by (x,y)
CardLayout
The CardLayout allows only one of its components to be visible at a time. The CardLayout
considers each of its components as a card. A CardLayout is controlled by a combo box.The
state of the combo box determines which panel is displayed by the CardLayout. Using the
CardLayout, the user has the option to view the following:
The first component
The last component
The previous component
The next component
Any component by specifying its name
196
Constructor Description
CardLayout( ) Creates a new card layout whose gaps are of size zero
CardLayout(int h, int v) Creates a new card layout with the horizontal gap specified
by h and the vertical gap specified by v
Table 11.8
The methods available in the CardLayout are listed in Table 11.9.
Method Description
addLayoutComponent(Component c, Object a)Adds the component c to the internal table of names
of the card layout
first(Container c) Displays the first card of the container c
getHgap( ) Returns the horizontal gap between the components
getLayoutAlignmentX(Container c) Returns the alignment along the x-axis of the
container c
getLayoutAlignmentY(Container c) Returns the alignment along the y-axis of the
container c
getVgap( ) Returns the vertical gap between the components
InvalidateLayout(Container c) Invalidates the layout
last(Container c) Displays the last card of the container c
layoutContainer(Container c) Lays out the container c using the card layout
maximumLayoutSize(Container c) Given the components of c, this method
returns the maximum dimensions for this layout
minimumLayout(Container c) Returns the minimum size for the specified panel
next(Container c) Displays the next card of the container c
preferredLayoutSize(Container c) Returns the preferred size of the container c using
the card layout
previous(Container c) Displays the previous card of the container c
removeLayoutComponent(Container c) Removes the components c from the layout
setHgap(int h) Sets the horizontal gap between the components to h
setVgap(int v) Sets the vertical gap between the components to v
show(Container c, ¸String s) Displays the component added to the container c
with the name specified by s
Table 11.9
197
Insets
Insets are used to provide spacing around the container. To cause a container (Panel) to have
its edges inset, the insets () method must be overridden to return a new instance of Insets
which represents the width of the spacing at the top, bottom, left, and right edges.
To create an inset in the container, the following method should be added to the container
class (Applet).
public Insets getInsets () {
return new Insets (10, 5, 15, 20)
}
This provides an inset of 10 and 5 pixels at the top and bottom and, 15 and 20 pixels at the
left and right edges.
Example 11.3 shows an applet that uses the border layout to position the user interface
components and adds an inset to the applet to demonstrate its usefulness.
Example 11.3
Enter the following code in a file and save it as BorderTest.java.
import java.awt.*;
public class BorderTest extends java.applet.Applet {
public void init ( ) {
setLayout (new BorderLayout(5,5,) ) ;
add("South", new Button ( "Bottom of the Applet”) );
add("North", new Button ( "Top of the Applet”) );
add(“East", new Button("Right”) );
add("West", new Button( “Left") );
add("Center", new TextArea("Appears at the centre") );
}
public Insets getInsets ( ) {
return new Insets(20,20,10,10);
}
}
Enter the following code in a file and save it as BorderTest.html.
198
In this example, the layout of the applet is set to the BorderLayout with a horizontal and
vertical gap of five pixels each. Then, four buttons are created and added to the four edges of
the applet. A Textarea is created and added to the center of the applet. Fig. 11.3 shows the
output of the program when it is run using the appletviewer.
Panel
The Panel class is a non-abstract, recursively nestable, container. The panel can contain UI
components and other containers.
A panel object can be constructed using the following code:
Panel pl=new Panel ( ) ;
The add( ) method of the Container class can be used to add a component to the
panel.pl.add(myButton);
Like all conatiners, the layout of the Panel can be set using the setLayout( ) method.
Frames and Menus
The Frame class is used to create standard application windows independent of the
browser(or the appletviewer) that contains the applet. The Frame window is a full-fledged
window by itself that can contain the following user interface elements:
Title bar - the top section of window that holds the window’s title.
Menu bar - the area just below the title bar which contains a number of menu labels.
Control Elements - these are UI components that are added to the Frame using the
add() method of the Container.
199
To create a Frame, use one of the constructors listed in Table 11.10.
Constructors Description
Frame( ) Creates a title frame, which is initially invisible.
Frame(String) Creates a frame with the String as the title
Table 11.10
Unlike Panels, a Frame object is rarely created directly from the applet. Since the frame is a
separate pop-up window, the events generated by the UI elements in the Frame are not sent to
the applet. Instead, these events are sent to the Frame object. To handle these events ,the
Frame class should be customized by deriving a sub-class from it . This sub-class can have all
event handlers specific to the problem.
public class MyFrame extends Frame {
// add your methods and event handlers here
}
In the applet, an instance of the sub-class (MyFrame) is created. The newly created frame is
initially invisible.The setVisible method is used to make the frame window appear on the
screen. The Frame class and its ancestor classes provide a number of methods that help in
positioning the frame on the screen. A selection of these methods is shown in Table 11.11.
Methods Description
setVisible(boolean) Makes the frame or window visible.
setSize(Dimension) Resizes the frame to the specified width and height.
setLocation(int,int) Moves the frame to the specified coordinates.
getLocation( ) Returns the current coordinates of the Frame as a
Point object. In case of top level windows like
frames, the location is in screen coordinate system.
Table 11.11
Note : None of the methods listed in Table 11.11 actually belong to Frame class. All these
methods belong to the Component class, an ancestor class of the Frame class. These methods
can be used on all classes derived from the Component class.
The Frame class also provides methods that allow getting and setting the title of the frame.
These methods and the dispose() method, which disposes the frame, are discussed in Table
11.12.
200
Methods Description
getTitle() Returns the title of the Frame as a String.
SetTitle(String) Changes the title of the Frame to the specified String.
dispose( ) Releases all the resources related to the window. The
window is removed from the screen.
Table 11.12
When the user attempts to close the frame an event, with id WINDOW CLOSING event type
is generated. The customized frame class should handle this event to dispose the frame.
Example 11.4 shows an applet that pops up a frame window when a button in the applet is
pressed. Use an instance variable to keep track of the number of frames that are popped up.
Example 11.4
Type the following code in a file and save it as MyFrame.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class MyFrame extends Frame {
boolean a;
MyFrame( ) {
a=false;
addWindowListener (new W( ));
}
class W extends WindowAdapter {
public void windowClosing (WindowEvent e) {
try{
setVisible(false) ;
dispose( );
System.exit (0);
}catch(Exception g) {}
}
}
201
}
public class FrameTest extends Applet {
int num=0;
public void init( ) {
Button benew Button("create window");
b.addActionListener(new B( ));
add(b);
}
class B implements ActionListener {
public void actionPerformed (ActionEvent e) {
MyFrame mf=new MyFrame( ) ;
mf.setSize(300,200);
mf.setVisible(true);
mf.setTitle("window - “+num);
++num;
}
}
}
The FrameTest.java file contains two classes, the frame, MyFrame, and the applet, The
FrameTest. The MyFrame class handles the window closing event to dispose the resource
associated with it. To accomplish this the addwindowListener method is called which has a
WindowAdapter object as its parameter. The try block within the windowclosing ( ) method
ensures that exceptions associated with such events are handled.
The init () method of the FrameTest applet creates a new button and adds it to the applet. The
action event is associated with the button which is handled using addActionListener ( )
method within which a new MyFrame object is created and displayed. There is also an
increment of the instance variable, num that keeps tracks of the number of frames popped up.
202
To create a stand-alone AWT application that constructs a Frame object in the main and pops
it up using setVisible (boolean) method, we use the following piece of code.
When the user tries to close the frame window, a window closing event is generated that
should be handled for the following to be done:
The parameter passed to the exit method represents the error value returned by the
application. An error value of 0 indicates normal exit.
Example 11.5 is a Stand-alone Java program that has a frame window as its main window
Example 11.5
Type the following code in a new file and save the file as FrameApp.java
import java.awt.*;
import java.awt.event.*;
class FrameApp extends Frame {
boolean a;
FrameApp( ) {
a=false;
setTitle("Stand-alone Application");
addWindowListener(new W( ));
}
class W extends WindowAdapter {
public void windowClosing (WindowEvent e) {
if(a)
203
dispose( );
else
System.exit (0);
}
}
public static void main(String args[]){
FrameApp fm=new FrameApp () ;
fm.setSize(300, 200);
fm.setVisible(true);
}
}
Compile FrameApp.java using javac and run it from the DOS prompt using java. The
main method creates a new FrameApp object and displays it using the setVisible
(boolean) method. A blank frame window of the application, which acts as the main
window of the application, is displayed.
When the frame is closed the window closing event handler closes the application by
the exit () method.
Menus
Java’s AWT provides a number of menu component classes to easily build and manage
menus. These menu component classes encapsulate the functionality of the three menu
elements, namely, the menu bar, the menu, and the menu item.
Fig. 11.4 indicates that the menu bar, displayed along the top of the window, has number
pull-down menus (File, Edit etc.). Each of these menus has a number of menu items. For
204
instance, the File menu has a number of menu items such as New, Open, and Save.
The classes that represent these menu elements are discussed in the following paragraphs.
The menu bar is the topmost menu element displayed along the top of the window to which it
belongs.
To create a menu bar, create an instance of the class Menubar.
The MenuBar has an add( ) method that permits addition of a number of selectable menus.
After adding menus, the Menubar should be assigned to a Frame to enable appearance of
menus on screen.
myframe.setMenubar (mb);
Creating a menu, which contains a number of menu items, involves the following steps.
First. construct a new instance of the Menu class.
Menu m= new Menu(“File”);
Then, add the menu items to the newly constructed menu using the add() method.
m.add(menuitem1) ;
m.add(menuitem2) ;
Lastly, add the Menu to a Menubar.
mb.add(m);
205
Methods Description
Add(Menultem) Adds the specified Menultem to the menu.
add(String) Adds the specified String to the menu. A new menu item with the
specified string as the label is created and is added to the menu
addSeparator( ) Adds a separator to the menu.
getItem( ) Returns the item at the specified index as a String.
Remove(int) Deletes the item at the specified index from the menu.
Table 11.13
The Menultem class encapsulates the functionality of the lower most component of the
menuing system namely, the menu item.
Menultem (String) creates new instance of Menultem with String specified as the
label.
The newly created Menultem can be added to a Menu using the add( ) method.
Since a reference to the Menultem is normally not required, the Menultem can be created and
added to the menu in a single step.
206
Methods Description
getLabel( ) Returns the label of the Menultem as a String.
setLabel(String) Changes the label of the Menultem to the specified String.
setEnabled(boolean) Makes the menu item selectable / deselectable depending
on whether the parameter is true or false.
Table 11.14
Menu Actions
When the user selects a menu item, an action event is generated. This event can be handled
by using action event listeners.
CheckboxMenultem (String) creates a checkbox menu item with the specified String
as the label. The menu item is initially unchecked.
Note : In Windows 95 environment, a tick mark appears to the left of the menu item to
indicate that it is checked.
The CheckboxMenultem class provide some additional methods to modify the state of the
menu item. These are listed in Table 11.15.
Methods Description
getState( ) Returns the state of the menu item as boolean value.
A value of true implies that the checkbox menu item is
selected.
setState(boolean) Sets the state of the menu item. If the value passed is true
the menu item is set to selected state.
207
Table 11.15
Example 11.6 adds appropriate messages to a text area as and when the respective menu
items are clicked. A label is placed on top of this text area asking the user to check out the
appearance of a pop up menu. This application introduces various features of menu:
Example 11.6
1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MenuApplication extends Frame implements
ActionListener, ItemListener {
4: boolean inAnApplet = true;
5: TextArea output;
6: PopupMenu popup;
7: String newline;
8: public MenuApplication( ) {
9: MenuBar mb;
10: Menu m1, m2, m3, m4, m4_1, m5;
11: Menultem m1_1, m1_2, m3_1, m3_2, m3_3, m3_4,m4_1_1, m5_1,
m5_2,pal,pm2, m5_1_duplicate;
12: CheckboxMenuItem m2_1;
13: addWindowListener (new WindowAdapter( ) {
208
14: public void windowClosing (WindowEvent e) {
15: if (inAnApplet) {
16: dispose();
17: }
18: else {
19: system.exit (0);
20: }
21: }
22: } );
23: newline = System.getProperty("line.separator") ;
24: setLayout (new BorderLayout ());
25: output = new TextArea(5, 30);
26: output.setEditable(false);
27: add("Center", output);
28: Label label = new Label("Try bringing up" + " a popup menu!");
29: add("North", label);
30: mb = new MenuBar();
31: setMenuBar(mb) ;
32: //makes this a tear-off menu.
33: m1 = new Menu("Menu 1", true);
34: mb.add(m1) ;
35: m1_1 = new MenuItem("Menu item 1_1");
36: m1.add(m1_1);
37: m1_2 = new MenuItem("Menu item 1_2");
38: m1.add(m1_2);
39: //Build help menu.
40: m5 = new Menu("Help Menu") ;
41: mb.setHelpMenu(m5) ;
42: m5_1 = new MenuItem("Menu item 5_1");
43: m5_1.setShortcut (new MenuShortcut (KeyEvent .VK_5));
44: m5.add(m5_1);
45: m5_2 = new MenuItem("Menu item 5_2");
46: m5.add(m5_2); //Make a popup menu.
47: popup = new PopupMenu("A Popup Menu");
209
48: add(popup) ;
49: pm1 = new Menultem("A popup menu item");
50: popup.add(pm1) ;
51: m5_1_duplicate = new MenuItem("Duplicate of menu item 5_1",new
MenuShortcut (KeyEvent.VK_5));
52: popup.add(m5_1_duplicate);
53: pm2 =new Menultem(“An item with a shortcut", new
Menushortcut (KeyEvent.VK_6));
54: popup.add(pm2); //Build second menu in the menu bar.
55: m2 = new Menu ("Menu 2");
56: mb.add (m2) ;
57: m2_1 = new CheckboxMenuItem(“Menu item 2_1”);
58: m2.add(m2_1);
59: //Build third menu in the menu bar.
60: m3 = new Menu ("Menu 3");
61: mb.add (m3) ;
62: m3_1 = new MenuItem(“Menu item 3_1”);
63: m3.add(m3_1);
64: m3_2 = new MenuItem(“Menu item 3_2”);
65: m3.add(m3_2);
66: m3.addSeparator( );
67: m3_3 = new MenuItem(“Menu item 3_3”);
68: m3.add(m3_3);
69: m3_4 = new MenuItem(“Menu item 3_4”);
70: m3_4.setenableed(false);
71: m3.add(m3_4);
72: //Build fourth menu in the menu bar.
73: m4 = new Menu ("Menu 4");
74: mb.add (m4) ;
75: m4_1 = new Menu (“Submenu 4_1”);
76: m4.add(m4_1);
77: m4_1_1 = new MenuItem(“Menu item 4_1_1”);
78: m4_1.add(m4_1_1);
79: //register as an ActionListener for all menu items.
210
80: m1.addActionListener(this);
81: m2.addActionListener(this);
82: m3.addActionListener(this);
83: m4.addActionListener(this);
84: m4_1_1.addActionListener(this);
85: //m4 can’t detect
86: //submenu actions
87: m5.addActionListener(this);
88: popup.addActionListener(this);
89: //Set action commands for a few menu items.
90: m1_1.setActionCommand(“1_1”);
91: m1_2.setActionCommand(“1_2”);
92: m5_1.setActionCommand(“5_1”);
93: m5_2.setActionCommand(“5_2”);
94: pm1.setActionCommand(“popup item #1”);
95: m5_1_duplicate.setActionCommand(“5_1”);
96: pm2.setActionCommand(“popup item #2”);
97: //Register as ItemListener on checkbox menu item.
98: m2_1.addItemListener(this);
99: //Listen for when the popup menu should be shown.
100: MouseListener listener = new PopupListener();
101: addMouseListener(listener);
102: output.addMouseListener(listener) ;
103: label .addMouseListener(listener) ;
104: }
105: class PopupListener extends MouseAdapter {
106: public void mousePressed(MouseEvent e) {
107: maybeShowPopup(e);
108: }
109: public void mouseReleased(MouseEvent e) {
110: maybeShowPopup (e) ;
111: }
112: private void maybeShowPopup(MouseEvent e) {
113: if (e.isPopupTrigger( )) {
211
114: popup. show(e.getComponent( ),e.getX( ), e.getY( ));
115: }
116: }
117: }
118: public void actionPerformed(ActionEvent e) {
119: output.append("\"" + e.getActionCommand( )+ "\" action detected
120: in menu labeled \""+ ((MenulItem) (e.getSource())).getLabel()+
"\"." + newline);
121: }
122: public void itemStateChanged(ItemEvent e) {
123: output.append("Item state change detected on item \""*+
e.getItem()+ "\" (state is "+ ((e.getStateChange( ) ==
ItemEvent .SELECTED)? "selected).": “deselected).")+ newline);
124: }
125: public static void main(String[] args) {
126: MenuApplication m = new MenuApplication();
127: m.inAnApplet = false;
128: m.setTitle("Menu Application");
129: m.setSize(450, 200);
130: m.setVisible(true);
131: }
132: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Let us go through the above code in parts. The declaration of the class Menu Application
includes implementation of ActionListener and ItemListener interfaces in order to enable
actions to be performed upon clicking a menu item.
MenuBar mb
Menu m1, m2, m3, m4_1, m5
212
CheckboxMenultem m2 with menu item m2_1
Menu Items
Menu item m3_4 is disabled when the application is started using the
setEnabled(false) method.
A sub menu is created and m4_1_1 menu item is added to this.
Action listeners are added to implement action events in the menu items.
Item listeners are added to enable item selection in the check box menu items.
Mouse listeners and action listeners are added to enable action to bring up popup
menu.
To close the frame window, the window listener is added by creating a
WindowAdapter object
A text area
A label
A string, new line, to bring in the new line property.
The setactionCommand sets the command name of the action event that is fired by this menu
item. By default, the action command is set to the label of the menu item.
The PopupListener class is created as a sub class of MouseAdapter. The mousePressed and
mouseReleased methods are added to this class, which are responsible for bringing up and
closing the pop up window. The maybePopupShow method checks if the event triggered
213
isPopupTrigger and then shows the pop up window at the point of clicking.
The actionPerformed method is responsible for displaying messages on the text are whenever
there is any action performed on the menu items.
The itemStateChanged method displays the messages whenever there is an item selection or
deselection of the CheckboxMenuItem menu.
The main method creates an object of MenuApplication that brings up the frame window of
this application . The setVisible() and set Title() methods show the window and display
window respectively. The boolean value for the object is set to false, since the application
should terminate once the close button of the window is clicked . Try commenting out this
line and observe.
To bring up pop up menu, rightclick anywhere on the frame which brings up a strip. Click on
it again to obtain a popup menu.
A simple editor that too a custom built editor sounds like a good idea isn’t it. Well that’s what
XYZ enterprises decided to do. They did not want the fancy stuff of changing fonts, their size
etc. They could not afford to buy some software that would meet their requirements. They
had the expertise in the office and hence decided that they could go head and build one for
themselves.
Their Main idea was with to use the software that was already existing with them. They had
214
Java with them and since Java was portable across any platform without much difficulty they
decided to take up the chance and built an editor.
Example 11.7
Open a new file in the editor and type the following code:
1 : import java.awt.*;
2 : import java.awt.event.*;
3 : import java.awt.datatransfer.*;
4 : import java.io.*;
5 : public clase Editor extends Frame {
6: String filename;
7: TextArea tx;
8: Clipboard clip = getToolkit( ).getSystemClipboard( );
9: Editor( ) {
215
10: setLayout (new GridLayout (1,1));
11: tx = new TextArea();
12: add (tx);
13: MenuBar mb = new MenuBar();
14: Menu F = new Menu("File");
15: MenuItem n = new MenuItem("New") ;
16: Menultem o = new MenuItem("Open") ;
17: Menultem s = new Menultem("Save") ;
18: MenuItem e = new Menultem("Exit") ;
19: n.addActionListener(new New()) ;
20: F.add(n);
21: o.addActionListener(new Open()) ;
22: F.add(o);
23: s.addActiontListener(new Save()) ;
24: F.add(s);
25: e.addActionListener(new Exit ()),
26: F.add(e);
27: mb.add(F);
28: Menu E = new Menu ("Edit*);
29: MenuItem cut = new Menultem("Cut");
30: MenuItem copy = new Menultem("Copy") ;
31: MenuItem paste = new Menultem("Paste");
32: cut.addActionListener (new Cut());
33: E.add(cut);
34: copy.addActionListener (new Copy());
35: E.add(copy);
36: paste.addActionListener (new Paste());
37: E.add(paste);
38: mb.add(E);
39: setMenuBar(mb) ;
216
Note: The line numbers given are not part of the source code and should
not be typed so.
Dialogs
Dialog box , like frame, is a pop-up window on which user interface components can be laid
out. Usually they are used to display messages and get specific information from the user.
Though a dialog resembles and behaves like a frame, there are some major differences
between the two. They are :
Unlike frames, a dialog has a parent (or a owner) window. The dialog is automatically
closed when the parent window is closed.
The dialog box usually contains a number of UI components suitably arranged (laid
out). Letting the user adjust the size of the dialog may affect the layout of the
components in the dialog.
A dialog box can be made modal. A modal dialog prevents user input to other
windows in the application until the dialog is closed.
Table 11.16
Notice that both the Dialog constructors require a Frame as a parameter. This frame window
acts as the parent of the dialog.
The dialog, like a frame, can act as a container. The layout of the dialog can be using the
setLayout() method and components can be added to it using the add() method. Methods in
the Dialog class that distinguish it from the Frame are shown in Table 11.17
217
Methods Description
setResizable(boolean) Sets the resizable flag of the dialog. If the
boolean value passed is true, the dialog is made resizable.
isModal( ) Returns true if the dialog is modal. A modal dialog prevents
the
user input to other windows in the application until the dialog
is closed.
isResizable( ) Returns true if the dialog is resizable.
Table 11.17
Example 11.8 creates a MessageBox dialog class that displays a message in a dialog window.
Example 11.8
1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MessageBox extends Dialog {
4 : MessageBox(Frame fm,String lab) {
5 : super (fm, "Message", true);
6 : setLayout (new GridLayout (2,1,0,0));
7 : Panel p1=new Panel( );
8 : Panel p2=new Panel( );
9 : Button b1,b2;
10: p1.setFont (new Font ("TimesRoman", Font .BOLD, 18) );
11: p1.setLayout (new FlowLayout (FlowLayout .CENTER, 20,15));
12: p2.setLayout (new FlowLayout (FlowLayout .CENTER, 20,20));
13: p1.add(new Label (lab) );
14: b1=new Button("ok") ;
15: b1.addActionListener (new B1());
218
16: p2.add(b1);
17: b2=new Button ("cancel");
18: b2. addActionListener (new B1());
19: p2.add(b2) ;
20: add(p1);
21: add(p2);
22: setSize(350,125),
23: setTitle("Message Box");
24: addWindowListener(new WindowaAdapter () {
25: public void windowClosing (WindowEvent e) {
26: system.exit(0); } } ) ;
27: }
28: class B1 implements ActionListener {
29: public void actionPerformed (ActionEvent e) {
30: try {
31: Button ok=(Button)e.getSource();
32: String s=ok.getLabel ();
33: if(s.equals(“ok")||s.equals("cancel") ) {
34: dispose();
35: System.exit (0);
36: }
37: }catch(Exception n) { }
38: }
39: }
40: }
Note: The line numbers given are not part of the source code and should not be
typed so.
1 : import java.awt.*;
2 : import java.awt.event.*;
3 : public class MessageApplication extends Frame {
4 : boolean a;
219
5 : MessageApplication( ) {
6 : MessageBox mb=new MessageBox(this,"Java Alert : This is a Message Box");
7 : mb.setLocation(200, 200);
8 : mb.setVisible(true);
9 : a=false;
10: }
11: public static void main(String args[ ]) {
12: MessageApplication fm=new MessageApplication( );
13: System.out.println("popping out message box");
14: fm.setVisible(true) ;
15: }
16: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Compile the two files using javac and run the MessageApplication class using the
java interpreter.
Note : The MessageBox is a generic class that can be used from any application ( which uses
frames).The MessageApplication is a stand-alone frame application that creates a
MessageBox and pops it up.
File Dialog
File dialog provides a platform-specific dialog that lets us to choose a file and to save or open
it.
220
To create a file dialog use one of the constructors shown in table 11.18
Constructors Description
FileDialog(Frame, String) Creates an Open file dialog that lets the user select a file
name from a file listing. The Frame acts as the parent
(owner) of the dialog. The string is the title of the file
dialog.
FileDialog(Frame,String, This constructor behaves exactly the same way as the
int) previous one, except that the int parameter is used to
determine whether the dialog is for loading or saving
a file. The two options are FileDialog.LOAD and
FileDialog. SAVE.
Table 11.18
Note : The file dialog does not actually load or save files. It is used only to select a file from
the file listing. The file dialog is a modal dialog.
The following code fragment creates a file dialog and displays it.
The userbutton fan select a file from the file dialog or dismiss it by clicking on the “Cancel”
button . When the setVisible method returns, the getFile() and getDirectory() methods can be
used to get the
name of the file chosen by the user. If the user dismisses the dialog without selecting a file,
the getFile() methods returns a null string.
if(if.getFile () ! = null ) {
String filename= f.getFileName ( );
String directory= f.getDirectory ( );
// perform some action (like opening the file selected)\
221
}
Methods Description
getDirectory( ) Returns the directory of the file selected as a
String
getFile( ) Returns the name of the file selected as a String. This
method returns a null string if the user dismisses the
dialog without selecting a file .
Table 11.19
Now that XYZ have built their menu, they would prefer to get their file operation done
through the FileDialog UI. Example 11.9 illustrates how to do this.
Example 11.9
222
setTitle(filename) ;
}
}
class Open implements ActionListener {
public void actionPerformed (ActionEvent e) {
FileDialog fd = new FileDialog(Editor.this, "select
File", FileDialog.LOAD);
fd.show( );
if (fd.getFile( ) ! = null) {
filename = fd.getDirectory( ) + fd.getFile( );
setTitle(filename) ;
ReadFile( );
}
tx.request Focus ( );
}
}
class Save implements ActionListener {
public void actionPerformed (ActionEvent e) {
FileDialog fd = new FileDialog(Editor.this, "Save
File", FileDialog.SAVE);
fd.show( );
if (fd.getFile( ) != null) {
filename = fd.getDirectory( ) + fd.getFile( );
setTitle(filename) ;
try {
DataOutputStream d = new DataOutputStream (new
FileOutputStream(filename) );
String lime = tx.getText( );
BufferedReader br = new BufferedReader (new StringReader (line) ) ;
while( (line = br.readLine( ) ) != null) {
d.writeBytes(line + "\r\n");
d.close();
}
} catch (Exception ex) {
223
System.out.println ("File not found");
}
tx. requestFocus( );
}
}
}
class Exit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(o) ;
}
}
void ReadFile( ) {
BufferedReader d;
StringsBuffer sb = new StringBuffer ( );
try {
d = new BufferedReader (new FileReader (filename) );
String line;
while ( (line = 4.readtine( ) ) ! = null )
sb.append (line + “\n”) ;
tx.setText (sb.toString( ) );
d.close( );
} catch (FileNotFoundException fe) {
System.out.println (“File not found”);
} catch (IOException ioe) { }
}
class Cut implements ActionListener {
public void actionPerformed (ActionEvent e) {
String sel = tx.getSelectedText ( ) ;
StringSelection ss = new StringSelection(sel) ;
clip.setContents(ss,ss) ;
tx.replaceRange(“ ”, tx.getSelectionStart ( ) , tx.getSelectionEnd ( ) );
}
}
class Copy implements ActionListener {
224
public void actionPerformed (ActionEvent e) {
String sel = tx.getSelectedText ( ) ;
StringSelection clipString = new stringSelection (sel) ;
clip. setContents (clipstring, clipstring);
}
}
class Paste implements ActionListener {
public void actionPerformed (ActionEvent e) {
Transferable cliptran = clip.getContents (Editor.this);
try {
String sel = (String) cliptran.getTransferData
(DataFlavor.stringFlavor);
tx.replaceRange(sel , tx.getSelectionStart ( ), tx.getSelectionEnd ( ) );
} catch (Exception exc) {
System.out.printin ("not string flavor");
}
}
}
public static void main (String args[ ] ) {
Frame f = new Editor( );
f.setSize (500,400);
f.setVisible(true);
f.show ( );
}
}
225
10.2 SUMMARY / TO SUM / LET’S SUM UP
The Layout manager classes are a set of classes that help in arranging the user
interface components in a container .
The FlowLayout lays out component linewise from left to right while the Gridlayout
position components in the cells of the grid.
The BorderLayout helps in laying out components relative to the edges of the
container.
The GridbagLayout divides a container into a grid of equally sized cells.
The CardLayout allows only one of its components to be visible at a time. The
CardLayout considers each of its components as a card.
Insets a provide space around the panel .
The frame is a pop-up window that is independent of the browser window containing
the applet.
The frame window can have a title bar and a menu bar . It can contain user interface
elements.
Java’s AWT provides three classes MenuBar ,Menu and MenuItem to build and
manage menus.
The Menu class implements the functionalities of pull-down menu. The MenuItem
class
represents individual items in a menu.
The CheckboxMenuItem creates a dual state menu item.
Dialog is a pop-up window on which UI components can be laid out.
A modal dialog prevents user input to other windows in the application until the
dialog is closed.
226
The file dialog provides a platform-specific dialog that allows the user choose a file to
save or open.
227
UNIT 11: GUI PROGRAMMING
Structure
11.0 Objectives
11.1 Introduction
11.2 GUI Components Like Buttons, Check Boxes, Radio Buttons, Labels,Text
Fields, Text Areas
11.3 Summary
11.4 Key words
11.5 Questions for Self Study
11.6 Suggested readings
11.0 OBJECTIVES
11.1 INTRODUCTION
In this unit we will learn about Java's GUI components include labels, text fields, text
areas, buttons, etc. The Abstract Windowing Toolkit (AWT) also includes containers
which can include these components. Containers include frames (windows), canvases
(which are used to draw on), and panels (which are used to group components).03-
Oct-199811.2
Button
Buttons are components that can contain a label. It has an outline, the button is similar
to a push button in any other GUI. Pushing a button causes the run time system to
generate an event. This event is sent to the program. The program in turn can detect
the event and respond to the event. Clicking a button generates an ActionEvent.
228
However, before a button can be used it has to be created. It can be created using the
new keyword in association with the constructors that are defined for it, buttons must
be added to the containers before they can be used. This is done using the keyworld
add. Once the buttons have been created and added they can be used.
When a button is clicked the AWT sends an instance of the ActionEvent to button by,
calling the processEvent on the button. The processEvent method of the button
receives all the events of the button. This then passes an action event along by calling
its processActionEvent. The processActionEvent then passes the action event to any
action listeners that have registered an interest in action events generated by the
button in question.Any application that has to perform an action based on the button
has implement the ActionListener and register the listener to receive the events from
the button, by calling is addActionListener method.
A button is basically a control component with a label that generates an event when
pushed. The Button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the button is
pushed.When we press a button and release it, AWT sends an instance
of ActionEvent to that button by calling processEvent on the button.
The processEvent method of the button receives the all the events, then it passes an
action event by calling its own method processActionEvent. This method passes the
action event on to action listeners that are interested in the action events generated by
the button.To perform an action on a button being pressed and released,
the ActionListener interface needs to be implemented. The registered new listener
can receive events from the button by calling addActionListener method of the
button. The Java application can use the button's action command as a messaging
protocol.
229
Table 10.2 lists the constructors that can be used with the Button component.
Constructor Description
Button( ) Constructs a button with no label
Button( String label) Constructs a button with the label
specified
Table 10.2
Table 10.3 lists some of the methods that can be used in relation to a button
component
Method Description
addActionListener (ActionListener 1) Adds the specified action listener to
receive action events from corresponding
button.
getActionCommand () Returns the command name of the action
event fired by the corresponding button.
getlabel () Return the label of the Corresponding
button
paramString () Returns the parameter string representing
the state of the corresponding button.
setLabel (String label) Sets the label of the button to the value
specified.
Table 10.3
Example 10.4 contains two labels, and two buttons, “OK” and “Cancel”. Two labels
are used to display the text of the buttons namely — Button! and Button2, The status
bar indicates which button was clicked.
Example 10.4
230
import java.awt. *;
import java. applet. *;
import java.awt. event. *;
public class ButtonTest extends Applet {
Label lb1=new Label("Button1");
Button b1=new Button("ok");
Label 1b2=new Label ("Button2");
Button b2=new Button("cancel");
public void init () {
setLayout (new FlowLayout ());
b1. addActionListener (new B1());
b2.addActionListener (new B2());
add(lb1);
add(b1);
add ( lb2);
add(b2);
}
class B1 implements ActionListener{
public void actionPerformed( ActionEvent e){
getAppletcontext () . showstatus (“button1: ok clicked”);
}
}
Class B2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
getAppletContext (). showStatus ("Button2; cancel clicked”);
}
}
}
Two buttons and two labels are added to the applet in the init () method in line 13 to
231
16. Two action listeners are created in the inner classes B1 and B2 and are added to
the applet using the addActionListener () method. Note that these inner classes
implement the ActionListener interface. The getappletContext () method determines
this applets context and uses the showStatus () method to display appropriate message
on the status line when the buttons are clicked. The setLayout () method is dealt in the
latter half of this chapter.
CheckBox
Checkboxes are user interface components that have dual state: checked and
unchecked
Clicking on it can change the state of the checkbox.
The various methods that are supported by checkboxes are listed in Table 10.5.
232
METHOD Description
getCheckboxGroup () Determines the group of the
corresponding check box
getLabel () Gets the name of the corresponding
check box
getSelectedObjects () Returns an array (length 1) containing the
checkbox label or null if the checkbox is
not selected.
getState() Determines if the checkbox is in the ‘on’
or ‘off’ state
setCheckboxGroup (CheckboxGroup g) Sets the corresponding checkbox’s group
to the specified one.
setLabel(String label) Sets the label of the corresponding
checkbox to the value specified.
setState(boolean state) Sets the state of the corresponding
checkbox to the value specified.
Table 10.5
The Choice class implements a pop-up menu that allows the user to select an item
from that menu. This UI component displays the currently selected item with an arrow
to its right. On clicking the arrow, the menu opens and displays options for a user to
select.
The create a choice menu, a Choice object is instantiated. Then, various items are
added to the choice by Using the addItem() method. The various constructors that can
be used to create a Choice object are given in Table 10.6.
Constructor Description
Choice() Creates a new choice menu
Table 10.6.
The various Methods that can be used along with a choice object are listed in Table
10.7.
233
METHOD Description
add (string item) Adds an item to the corresponding choice
menu
additem (string item) Adds an item to the corresponding choice
getitem (int index) Gets the string at the specified index of
the corresponding choice menu
getItemCount () Returns the number of items in the
corresponding choice menu
getSelectedindex() Returns the index of the currently select
item
getSelectedltem() Gets a representation of the current
choice as a string
getSelectedObjects( ) Returns an array (length 1) containing
the currently selected item.
insert(String item, int index) Inserts the item into the corresponding
the specified position.
remove(int position) Removes an item from the corresponding
choice menu at the specified position.
Remove the first occurrence of item from
remove(String item) the corresponding Choice menu.
removeAll() Removes all items from the
corresponding choice menu.
Example 10.5
234
Type the following code in a new file and save it as RadioTest.java
1: import java.awt. *;
2: import java.awt.event,*;
3: import java.applet.+*;
4: public class RadioText extends applet {
5: Public void init () (
6: CheckboxGroup c = new CheckboxGroup ();
7: Checkbox c1=new Checkbox (“Black and White”, c. true);
8: Checkbox c2=new Checkbox (‘Color’,c, false);
9: c1, addMouseListener (new Check1());
10: c2, addMouseListener (new Check2());
11: add(c1);
12: add(c2);
13: Choice abc = new Choice ();
14: abc. add("Onida");
15: abc.add("BPL");
16:abc.2dd("Samsung’’);
17:abc.2dd("Philips");
18: abc.add("Videocon”);
19:abc. addItemListener (new Ch());
20: add (abc);
21: }
22:class Check1 extends MouseAdapter {
23: public void mouseClicked (MouseEvent e) {
24: showStatus ("You have selected: Black and White TV");
25:}
26:}
27: class Check2 extends MouseAdapter{
28: public void mouseClicked (MouseEvent e) {
29: showStatus ("You have selected: Color TV");
30:}
31:}
32: class Ch implements ItemListener{
235
33: public void itemStateChanged(ItemEvent e) {
34: String s=(String)e.getItem();
35: showStatus ("You have selected "+s +" brand") ;
36: }
37: }
38: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Canvas
236
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the
user.An application must subclass the Canvas class in order to get useful functionality
such as creating a custom component. The paint method must be overridden in order
to perform custom graphics on the canvas. The canvas does not have a Size that is
useful to the end user and hence the setSize method has to be used to, render a
meaningful canvas on the screen.
Canvas component can also be created using the constructor listed in table 10.8
Constructor Description
Canvas( ) Constructs anew canvas
Table 10.8
The canvas component has some useful method that can be used and are listed in table
10.9
Method Description
addnotify () Creates a peer of the canvas
paint(graphics g) This method is called to repaint the
corresponding canvas.
Table 10.9
FileDialog
The FileDialog class displays a dialog window from which the user can select a file.
Being a modal dialog, it blocks the rest of the application until the user has chosen a
file. The constructors that can be used to create a FileDialog are listed in Table 10.10.
Constructors Description
FileDialog(Frame parent) Creates a file dialog for loading a file
FileDialog(Frame parent, string title) Creates a file dialog window with the
specified title for loading a file
FileDialog(Frame parent, String title, int Creates a file dialog window with the
mode) specified title for loading or saving a file.
Table 10.10
The various methods that can be used in conjunction with the FileDialog component
237
are
listed in Table 10.11.
Method Description
getdirecory () Gets the directory of the corresponding
File dialog
getFile( ) Gets the file of the corresponding file
dialog
get FilenameFilter( ) Determines the file dialog’s filename
filter
getmode( ) Indicates whether the file dialog is in the
save mode or open mode
setDirectory(String str) Sets the directory of the file dialog
window to the one specified
setFile(string file) Sets the selected file for the
corresponding file dialog window to the
one specified
setFilenameFilter(filename filter) Sets the filename filter for the specified
file dialog window to the specified
value.
setModel(int mode) Sets the mode of the file dialog.
Table 10.11
Label
The component can be used for displaying a single line of text in a container. The text
can be changed by an application but the user cannot edit the text. Labels do not
generate any event.
A lable is similar to a button can be created using its construction in combination with
the keyworld new. The various construction for labels is listed in table 10.12
Constructor Explanation
Lable() constructs as empty label
238
Label (string text) constructs a string with the corresponding
text
Label (string text, int Alignment) Constructs a string with the text, with the
specified alignment. The alignment could
be
CENTER, LEFT, RIGHT.
Table 10.12
The various methods that can operate on a lable object are listed in table 10.13
Method Explanation
gettext () Gets the text of the corresponding label
paramString () Return the parameter string representing
the state ff the corresponding label
setText (string text) Set the text for the corresponding label to
the specified text.
Table 10.13
List
The List component presents the user with a scrolling list of text items. The list can be
used so that the user can choose either one item or multiple items. The difference
between a line and a choice menu are given below.
Unlike Choice, which displays only the single-selected item, the list can be made
to show any number of choices in the visible window.
The list can be constructed to allow multiple selections.
The various constructors that can be used to create a list object are given in table
10.14
Constructors Description
List () Create a new scrolling list of items
List (int rows) Create a new scrolling list of items with
239
the Specified number of variable lines
List (int rows, boolean multiple code) Create a new scrolling list of items to
display the specified number of rows.
Table 10.14
The various methods that can be used in conjunction with the list component are
given in table 10.15
METHOD DESCRIPTION
add (string items) Adds the specified items at the end of the
scrolling list
add (string item, int index) Add the specified items at the position
specified
deselect (int Index) Deselects the item at the specified index
getitem count () Gets the number of items in the list
getitems () Gets the items in the list
getMinimumSize () Determines the minimum size of the
scrolling list
getMinimumSize (int rows) Gets the minimum dimensions for a list
with the specified number of rows
getPreferredSize () Gets the preferred size of the
corresponding scrolling list
getPreferredSize (int rows) Gets the minimum dimension of the list
with the specified number of rows
getrows () Gets the number of visible lines in the
corresponding list
getSelectedindex () Gets the index of the selected items in the
list
getselecteditem () Gets the selected items in the
corresponding list
select (int index) Select the item at the specified index in
the corresponding list
setMultipleMode (boolean b) Sets the flag that allows multiple
selection in the corresponding list
240
Table 10.15
SCROLLPANE
ScrollPane is a container class which implements automatic horizontal and /or vertical
scrolling for a single child component the display policy for the scrollbars can be set
as needed
always
never
The various methods that can be used with the scrollpane component are listed in
table
10.17.
METHOD DESCRIPTION
getScrollbarDisplayPolicy () Returns the display policy for the
corresponding scroll bars
setScrollPosition (int x, int y) Scroll to the specified position within the
child component
Table 10.17
Scrollbar
Scrollbars are used to select a value between a specified minimum and maximum. It
has the following components:
241
The arrows at either end allow incrementing or decrementing the value
represented by the scrollbar.
The thumb’s (or handle’s) position represents the value of the scrollbar
The various constructors that can be used to create a Scrollbar are giver in table 10.18
Constructor Description
Scrollbar() Constructs a vertical scroll bar
Scrollbar (int orientation) Constructs a new scroll bar with the
specified orientation.
scrollbar (int orientation, int maxvalue, Constructs a new scroll bar with the
int visible, int minimum, int maximum) specified orientation, initial value, page
size
minimum and maximum values.
Table 10.18
The various methods can be used in conjunction with Scrollbar are given in table
10.19
Methods Description
getBlockIncrement () Gets the block increment of the
corresponding scroll bar
getMaximum () Gets the maximum value of the
corresponding scroll bar
getMinimum () Gets the minimum value of the
corresponding scroll bar
getOrientation () Determines the orientation of the
corresponding scroll bar
getValue () Gets the current value of the
corresponding scroll bar
setBlockIncrement (int v) Sets the block increment for the
corresponding scroll bar
setMaximum (int newMaximum) Sets the maximum value for the
corresponding scroll bar
242
setMinimum (int newminimum) Sets the minimum value for the
corresponding scroll bar
setValue (int newvalue) Sets the value pf the corresponding scroll
bar to the specified value
Table10.19
TEXTFIELD
Textfields are UI component that accept text input from the user. They are often
accompanied by a label control the provides guidance to he user on the content to be
entered in the Textfield.
Textfields only have single line text and are ideal in situation where a relatively small
piece of information such as name age etc, is to be got from the user. For more than
one line of text, TextArea is a better choice.
Table 10.20 below lists some of the construction that can be used to create TextFields
Constructors Description
TextField () Constructs a new text area
TextField (int columns) Constructs a text area with the specified
number of columns
TextField (String text) Constructs a new text field initialized
with the specified text
TextField (String text, int columns) Constructs a new text field initialized
with the specified text with the and
specified number of columns
Table 10.20
Some of the methods that may be used in association with a Textfield are given in
table 10.21
METHOD DESCRIPTION
getColumns () Gets the number of columns in the
Corresponding text field
getEchoChar () Gets the character that is to be used for
Echoing
243
setColumns (int column) Sets the number of columns in the text
field
setEchoChar (char c) Sets the echo character for the text field
setText (String t) Sets the text that is presented by the
corresponding text component to be
specified text.
TEXTAREA
Textareas behave like TextFields except that they have more functionality to handle
amounts the text these functionalities include.
Text areas can contain multiple rows of text
Text areas have scrollbars that permit handling of
large amount of data
The constructors that can be used to create a text area are listed in table 10.22
CONSTRUCTORS DESCRIPTION
TextArea (int rows, int columns) Constructs a text area with the
specified number of Rows and
columns
244
The various methods that can be used in conjunction with the TextArea are given in
table 10.23.
Methods Description
append (String str) Appends the given text to the text areas
contents
getColumns () Gets the number of columns of the text
area
getMinimumSize( ) Determines the minimum area of the text
area
getRows() Gets the number of rows in the text area
insert (String str, int pos) Inserts the specified string at the
specified position
setColumns (int columns) Sets the number of columns for the text
area
setRows(int rows Sets the number of rows for the text area
Table 10.23
Example 10.6 opens an applet that has the following UI components.
Example 10.6
Import java.awt. *;
import java. applet. *;
import java.awt. event. *;
public class ListTest extends Applet {
245
List acts=new List ();
TextField tx=new TextField (10);
Button add=new Button("add");
String stringlist [] = {"one", "two", "three"};
public void start () {
add (new Label ("text"));
add(tx);
for (int i=0; i<stringlist. Length; ++i)
acts. addiItem(stringlist[i]);
add(acts);
add. addActionListener (new Add());
add(add);
}
class Add implements ActionListener {
public void actionPerformed (ActionEvent e) {
acts. addItem (tx. getText ());
}
}
}
246
The init () method of the applet, creates the user interface component specified in the
problem and adds them to the applet. The addItem () method is used to add three
items to the List. The text entered in the text field is added to the list on clicking the
add button the addActionListener () method enables the program to listen to button
click events items are added to the list inside the actionPerformed() method within the
inner class add.
Changing the state of an object is known as an event. For example, click on button, dragging mouse e
provides many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
247
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
o Button
o MenuItem
o TextField
o TextArea
248
o public void addTextListener(TextListener a){}
o Checkbox
o Choice
o List
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
249
b.addActionListener(this);//passing current instance
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield
etc.
250
2) Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
251
}
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
We have learnt GUI Components Like Buttons, Check Boxes, Radio Buttons, Labels,
Text Fields, Text Areas, Combo
252
11.4 KEYWORDS / GLOSSARY
253
UNIT 12: APPLET AND ITS LIFE CYCLE
Structure
12.0 Objectives
12.1 Introduction
12.2 Applet and its Life Cycle
12.3 Introduction to Swing
12.4 Summary
12.5 Key words
12.6 Questions for Self Study
12.7 Suggested readings
12.0 OBJECTIVES
12.1 INTRODUCTION
Introduction
The Abstract Windowing Toolkit (AWT) is an API that is responsible for building the
Graphical User Interface (GUI).It is part of the Java Foundation Classes (JFC). AWT
includes a rich set of user interface components, a powerful event handling model,
graphics and image tools, layout managers and support for data transfer using cut and
paste through clipboards. AWT also Supports JavaBeans architecture. Every AWT
component is a simple bean. The java.awt Package contains all classes for creating
user interfaces and for painting graphics and images.
The AWT has several subsystems that support the development of Graphical User
Interface (GUI) program. The Subsystems include:
Graphics Primitives that allow the drawing and rendering of lines and images.
Components such as Labels, Buttons and TextFields.
Containers that include Frames, Panels and Dialogs.
254
Layout Managers that control the display in a portable manner.
Event system, which allows the user to respond to interactions between the
components and containers in the application
The Original AWT version 1.0 of the Java Development Kit (JDK) did its work by
instantiating peer objects from the native operating system, Starting with JDK 1.1,
Sun has made substantial changes 'o the user interface components. The AWT in
1.1.The interface in Java 1.1 still does its work through peer objects and these are now
known as heavyweight components. There are also lightweight components that do
not tie the user to the native operating system. These instead support the pluggable
look and feel. Java makes many details of the graphical user interface (GUI)
programming invisible but they are still present. This is possible because of the
platform independence of Java.
Swing is a set of classes that provide more powerful flexible components than
possible with AWT
In addition to familiar components, like button, checkbox, labels, swings
supplies several exciting additions including tabbded panes, scroll panes, tress
and tables.
Even familiar components like button may have both an image and a text
string associated with it. The image can be changed as the state of the button
changes.
Unlike AWT components, swing components are not implemented by
platform-specifiec code. Instead, they are written entirely in java therefore it is
platform-independent.
255
Definition
An applet is a dynamic and interactive program that can run inside a Web page
displayed by a Java-capable browser such as HotJava or Netscape. Hot Java Browser
is a World Wide Web Browser used to view Web pages, follow links and submit
forms. It can also download and play applets on our system.
Example 9.1
Open a new file in the editor and type the following code.
import java.awt
public class MyFirstApplet extends java.applet.Applet {
public void paint (Graphics g) {
g.drawString ("My first Java applet", 70,30) ;
}
256
}
Save this file, as MyFirstApplet.java and compile it using javac. This will
result in the creation of a .class file for the same
Now create an HTML file and within its body, type
Save this file as MyFirstApplet.html in the same directory as that of the java
file.
Execute the applet using appletviewer MyFirstApplet.html
The result is as shown in Fig. 9.1
In the program, line number 1 is used to import all the features of the awt
package. All import statements should be included in the beginning of the file.
In the number 2, the class MyFirstApplet that is sub class of the Applet class,
has been declared. All Applets are sub class of the Applet class of Java library.
Line number 3 has a method called paint ().It is responsible for printing the
required string using the drawstring() method .The two numbers entered along
with the string are the x and y co-ordinates to position the display of the string.
HTML Tags
Some of the HTML tags used in the.html file are discussed below.
257
Applet Tags
The <applet> tag is used to start the applet from inside the HTML document as well
as from the appletviewer. Each <applet> tag is executed in separate windows by the
appletviewer while the Java capable browser is capable of executing numerous
applets inside a Single web page. This code instructs the browser or the appletviewer
to load the compiled Java apply, namely the .class file. The size of display of the
applet is initialized using the WIDTH and HEIGHT tags. To indicate the end of the
applet, </applet> tag is used. It is essential to end the applet using this tag, otherwise
it will not be executed. Comment lines can be inserted below, above or at the side of
the applet within the HTML file. This is done by including those lines within the
<applet> and </applet> tags.
258
Example9.2 helps in understanding the usage of passing parameters to an applet.
Example 9.2
Open a new file in the editor and the following code:
import java.awt.*;
public class ParamTestApplet extends java.applet.Applet{
Font f = new Font (“TimesRoman”,Font. BOLD, 40);
String name;
public void init () {
name = gerParameter (“name”);
if (name = null)
name = “friend";
name = "Have a nice day “ + name ;
}
public void Paint (Graphics g ) {
g.setFont (f);
g.setColor (Color.darkGray) ;
g.drawString(name, 50,50);
}
}
In the Line number 3 an instance of the Float class f is declared. This object has been
initialized to contain “TimesRoman” as font name, font size as 40 and font style as
BOLD. The init() method declared in line number 5,contains the getParameter()
method, which accepts the name (a string ) as its parameter. If no value is given to the
variable “name”, then a default value is given line number 8. The paint () method of
the Applet class is overridden to execute the paint () method in our class. This method
contains the drawSting () method apart from, two methods namely setFont () and
setColor (). These two methods are used to set the desired font and color respectively.
259
<PARAM NAME = name VALUE=’Abi’>
</APPLET>
The ParamTestApplet.html file code given above contains its. Class file in another
directory called “test”. Therefore the usage of the tag CODEBASES. Note the usage
of the tag <PARM> .Suppose the value of the parameter is to be changed, The
VALUE attribute of the <PARM> tag is substituted accordingly. Thus parameter
passing in an applet is done by changing the values in the .html file. When this applet
is run ,a screen as shown in figure 9.2 appears
If <param> tag is not given in the .html file, the resulting figure contains “friend”
instead of
“Abi” and it is exactly the same as the above figure.
Note: From now on, it is assumed that appropriate .html files will be created and there
will be no code given for it in the following examples.
Major Applet Activities
So far simple applets were created which did not require an explicit initialization,
clean-up activities at the end or a method to stop the applet which is running. There
are methods available to perform all these activities. Some of them are discussed
below. These are methods exist in the Applet class and are overridden to execute the
methods in a given class (except the repaint () method).
260
The start () Method
This method is executed after the init () method. In case a Java enabled browser is
used to run the applets ,any time it is reloaded, the execution begins from the start ()
method
repaint () takes four arguments to update only a part of the screen. The first two
261
arguments are the x and y coordinates, the next two arguments are the width and the
height of the image. This helps in faster updation of the screen.
One reason for the limited nature of the AWT is that it translates its various
visual components into their corresponding, platform-specific equivalents, or peers.
This means that the look and feel of a component is defined by the platform, not by
Java. Because the AWT components use native code resources, they are referred to as
heavyweight.
The use of native peers led to several problems. First, because of variations
between operating systems, a component might look, or even act, differently on
different platforms.
262
Two Key Swing Features
Swing was created to address the limitations present in the AWT. It does this through
two key features: lightweight components and a pluggable look and feel. Together
they provide an elegant, yet easy-to-use solution to the problems of the AWT. More
than anything else, it is these two features that define the essence of Swing.
Separating out the look and feel provides a significant advantage: it becomes possible
to change the way that a component is rendered without affecting any of its other
aspects. In other words, it is possible to “plug in” a new look and feel for any given
component without creating any side effects in the code that uses that component.
For example, if you know that an application will be running only in a Windows
environment, it is possible to specify the Windows look and feel. It is also possible to
design a custom look and feel. Finally, the look and feel can be changed dynamically
at run time.
263
Components and Containers;
The difference between the two is found in their intended purpose: As the term is
commonly used, a omponent is an independent visual control, such as a push button or
slider. A container holds a group of components. Thus, a container is a special type of
component that is designed to hold other components. Thus, all Swing GUIs will have
at least one container. Because containers are components, a container can also hold
other containers. This enables Swing to define what is called a containment hierarchy,
at the top of which must be a top-level container.
Components
In general, Swing components are derived from the JComponent class. JComponent
provides the functionality that is common to all components. For example,
JComponent supports the pluggable look and feel. JComponent inherits the AWT
classes Container and Component. Thus, a Swing component is built on and
compatible with an AWT component.
All of Swing’s components are represented by classes defined within the package
javax.swing. The following table shows the class names for Swing components
264
Containers
Swing defines two types of containers. The first are top-level containers: JFrame,
JApplet, JWindow, and JDialog. These containers do not inherit JComponent.
They do, however, inherit the AWT classes Component and Container. Unlike
Swing’s other components, which are lightweight, the top-level containers are
heavyweight. This makes the top-level containers a special case in the Swing
component library.
The glass pane is the top-level pane. It sits above and completely covers all other
panes. By default, it is a transparent instance of JPanel. The glass pane enables you to
manage mouse events that affect the entire container (rather than an individual
control) or to paint over any other component, for example. In most cases, you won’t
need to use the glass pane directly, but it is there if you need it.
265
The layered pane is an instance of JLayeredPane. The layered pane allows
components to be given a depth value. This value determines which component
overlays another. The layered pane holds the content pane and the (optional) menu
bar.
The glass pane and the layered panes are integral to the operation of a top-level
container and serve important purposes, much of what they provide occurs behind the
scene. The pane with which your application will interact the most is the content pane,
because this is the pane to which you will add visual components. In other words,
when you add a component, such as a button, to a top-level container, you will add it
to the content pane. By default, the content pane is an opaque instance of JPanel.
Swing is a very large subsystem and makes use of many packages. These are the
packages used by Swing that are defined by Java SE 6.
The main package is javax.swing. This package must be imported into any program
that uses Swing. It contains the classes that implement the basic Swing components,
such as push buttons, labels, and check boxes.
Swing programs differ from both the console-based programs and the AWT-based
programs. For example, they use a different set of components and a different
container hierarchy than does the AWT. Swing programs also have special
requirements that relate to threading. There are two types of Java programs in which
Swing is typically used. The first is a desktop application. The second is the applet.
266
The program uses a JFrame container to hold an instance of a JLabel. The label
displays a short text message.
267
Create a Swing Applet;
The second type of program that commonly uses Swing is the applet. Swing-based
applets are similar to AWT-based applets, but with an important difference: A Swing
applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus,
JApplet includes all of the functionality found in Applet and adds support for Swing.
JApplet is a top-level Swing container, which means that it is not derived from
JComponent. Because JApplet is a top-level container, it includes the various panes
described earlier. This means that all components are added to JApplet’s content
pane in the same way that components are added to JFrame’s content pane.
Swing applets use the same four lifecycle: init( ), start( ), stop( ), and destroy( ). Of
course, you need override only those methods that are needed by your applet. Painting
is accomplished differently in Swing than it is in the AWT, and a Swing applet will
not normally override the paint( ) method.
One other point: All interaction with components in a Swing applet must take place
on the event dispatching thread, as described in the previous section. This threading
issue applies to all Swing programs.
Here is an example of a Swing applet. It provides the same functionality as the
previous\ application, but does so in applet form.
// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet {
268
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
// Initialize the applet.
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}
269
// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
}
}
OUTPUT :
270
use the ImageIcon class. ImageIcon implements Icon and encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor.
ImageIcon(String filename)
It obtains the image in the file named filename.
The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
The following applet illustrates how to create and display a label containing both an
icon and a string. It begins by creating an ImageIcon object for the file france.gif,
which depicts the flag for France.
// Demonstrate JLabel and ImageIcon.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
271
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}
JTextField;
JTextField is the simplest Swing text component. It is also probably its most widely
used text component. JTextField allows you to edit one line of text. It is derived from
JTextComponent, which provides the basic functionality common to Swing text
components. JTextField uses the Document interface for its model.
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
272
Here, str is the string to be initially presented, and cols is the number of columns in
the text field. If no string is specified, the text field is initially empty. If the number of
columns is not specified, the text field is sized to fit the specified string.
JTextField generates events in response to user interaction. For example, an
ActionEvent is fired when the user presses ENTER. A CaretEvent is fired each time
the caret (i.e., the cursor) changes position.
To obtain the text currently in the text field, call getText( ). The following example
illustrates JTextField. It creates a JTextField and adds it to the content pane. When the
user presses ENTER, an action event is generated. This is handled by displaying the
text in the status window.
// Demonstrate JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
273
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}
JButton
The JButton class provides the functionality of a push button. You have already seen
a simple form of it in the preceding chapter. JButton allows an icon, a string, or both
to be associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
274
Here, str and icon are the string and icon used for the button. When the button is
pressed, an ActionEvent is generated. Using the ActionEvent object passed to the
actionPerformed( ) method of the registered ActionListener, you can obtain the
action command string associated with the button. By default, this is the string
displayed inside the button. However, you can set the action command by calling
setActionCommand( ) on the button.
You can obtain the action command by calling getActionCommand( ) on the event
object. It is declared like this:
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons
within the same application, the action command gives you an easy way to determine
which button was pressed.
// Demonstrate an icon-based JButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=450>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
275
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(germany);
jb.setActionCommand("Germany");
jb.addActionListener(this);
add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Flag");
add(jlab);
}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}}
276
JToggleButton
Auseful variation on the push button is called a toggle button. A toggle button looks
just like a push button, but it acts differently because it has two states: pushed and
released. That is, when you press a toggle button, it stays pressed rather than popping
back up as a regular push button does. When you press the toggle button a second
time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles
between its two states.
Toggle buttons are objects of the JToggleButton class. JToggleButton implements
AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a
superclass for two other Swing components that also represent two-state controls.
277
These are JCheckBox and JRadioButton, which are described later in this chapter.
Thus, JToggleButton defines the basic functionality of all two-state components.
JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the button
is in the off position. Other constructors enable you to create toggle buttons that
contain images, or images and text.
JToggleButton uses a model defined by a nested class called JToggleButton
.ToggleButtonModel. Normally, you won’t need to interact directly with the model
to use a standard toggle button.
// Demonstrate JToggleButton.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}}
278
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);
}
}
The output from the toggle button example is shown here:
279
Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as just
described. JCheckBox defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors
let you specify the initial selection state of the button and specify an icon.
When the user selects or deselects a check box, an ItemEvent is generated. You can
obtain a reference to the JCheckBox that generated the event by calling getItem( ) on
the ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
The easiest way to determine the selected state of a check box is to call isSelected( )
on the JCheckBox instance.
The following example illustrates check boxes. It displays four check boxes and a
label. When the user clicks a check box, an ItemEvent is generated. Inside the
itemStateChanged( ) method, getItem( ) is called to obtain a reference to the
JCheckBox object that generated the event. Next, a call to isSelected( ) determines if
the box was selected or cleared. The getText( ) method gets the text for that check
box and uses it to set the text inside the label.
// Demonstrate JCheckbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
280
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);
// Create the label and add it to the content pane.
jlab = new JLabel("Select languages");
add(jlab); }
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
281
}}
Develop an applet to create a label, a text field and 4 check boxes with the caption
“red”, “green”,”blue” and “yellow” (jun-2012)
import java.awt.*;
import java.awt.event*;
import java.applet;
public class checkdemo extends applet implements item Listener {
checkbox rd,gn,be,yw;
public void init()
{rd=new checkbox(“rd”nulltrue);
gn=new checkbox(“green”);
be=new checkbox(“blue”);
yw=new checkbox(“yellow”);
add(rd); add(gn);
add(be); add(yw);
Lable np=new Label (“Name:”,Label. RIGHT);
nm = new TextField(12);
add(np);
add(nm);
nm.add Action Listener(this);
}
Publiv void Itemstate changed (ItemEvent ie)
{ repaint();}
Public void paint(Graphics g)
{
g.drawstring(“Name:”+nam.getText(),6,60);
msg=”color is”;
g.drawstring(msg,6,60);
msg=”red”+rd.getstate();
282
g.drawstring(msg,6,100);
msg=”green”+rd.getstate();
g.drawstring(msg,6,120);
msg=”blue”+rd.getstate();
g.drawstring(msg,6,140);
msg=”yellow”+rd.getstate();
g.drawstring(msg,6,160);
}}
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time. They are supported by the JRadioButton class, which
extends JToggleButton. JRadioButton provides several constructors. The one used
in the example is shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.
In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group. Only one of the buttons in the 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. Abutton group is created by the
ButtonGroup class. Its default constructor is invoked for this purpose. Elements are
then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
// Demonstrate JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
283
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");
284
add(jlab);
}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}
Output from the radio button example is shown here:
JTabbedpane;
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking
them with tabs. Selecting a tab causes the component associated with that tab to come
to the forefront. Tabbed panes are very common in the modern GUI, and you have no
doubt used them many times. Given the complex nature of a tabbed pane, they are
surprisingly easy to create and use.
JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane. The other
two constructors let you specify the location of the tabs, which can be along any of
the four sides. JTabbedPane uses the SingleSelectionModel model.
Tabs are added by calling addTab( ). Here is one of its forms:
void addTab(String name, Component comp)
Here, name is the name for the tab, and comp is the component that should be added
to the tab. Often, the component added to a tab is a JPanel that contains a group of
related components. This technique allows a tab to hold a set of components.
The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
285
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}
// Make the panels that will be added to the tabbed pane.
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);
286
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Output from the tabbed pane example is shown in the following three illustrations:
287
JScrollPane;
JScrollPane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can either be an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel.
If the object being scrolled is larger than the viewable area, horizontal and/or vertical
scroll bars are automatically provided, and the component can be scrolled through the
pane. Because JScrollPane automates scrolling, it usually eliminates the need to
manage individual scroll bars.
JScrollPane defines several constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically
displayed when the content of the pane exceeds the dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
288
3. Add the scroll pane to the content pane.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
289
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
Output from the scroll pane example is shown here:
JList;
In Swing, the basic list class is called JList. It supports the selection of one or more
items from a list. Although the list often consists of strings, it is possible to create a
list of just about any object that can be displayed. JList is so widely used in Java that
it is highly unlikely that you have not seen one before.
JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines how
access to the list data is achieved. The second model is the ListSelectionModel
interface, which defines methods that determine what list item or items are selected.
290
AJList generates a ListSelectionEvent when the user makes or changes a selection.
This event is also generated when the user deselects an item. It is handled by
implementing ListSelectionListener. This listener specifies only one method, called
valueChanged( ), which is shown here:
void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event.
ListSelectionEvent does provide some methods of its own, normally you will
interrogate the JList object itself to determine what has occurred. Both
ListSelectionEvent and ListSelectionListener are packaged in javax.swing.event.
By default, a JList allows the user to select multiple ranges of items within the list,
but you can change this behavior by calling setSelectionMode( ), which is defined by
JList. It is shown here:
void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
// Demonstrate JList.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JListDemo" width=200 height=120>
</applet>
*/
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle",
291
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
setLayout(new FlowLayout());
// Create a JList.
jlst = new JList(Cities);
// Set the list selection mode to single selection.
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Add the list to a scroll pane.
jscrlp = new JScrollPane(jlst);
// Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120, 90));
// Make a label that displays the selection.
jlab = new JLabel("Choose a City");
// Add selection listener for the list.
jlst.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent le) {
// Get the index of the changed item.
int idx = jlst.getSelectedIndex();
// Display selection, if item was selected.
if(idx != -1)
292
jlab.setText("Current selection: " + Cities[idx]);
else // Otherwise, reprompt.
jlab.setText("Choose a City");
}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}
Output from the list example is shown here:
JComboBox;
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it will
also display a drop-down list that allows a user to select a different entry. You can
also create a combo box that lets the user enter a selection into the text field. The
JComboBox constructor used by the example is shown here:
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box. Other constructors are available.
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries
can be changed) use the MutableComboBoxModel.
In addition to passing an array of items to be displayed in the drop-down list, items
can be dynamically added to the list of choices via the addItem( ) method, shown
here:
293
void addItem(Object obj)
Here, obj is the object to be added to the combo box. This method must be used only
with mutable combo boxes.
// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Instantiate a combo box and add it to the content pane.
jcb = new JComboBox(flags);
294
add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.
jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
Output from the combo box example is shown here:
JTable.
JTable is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a new
position. Depending on its configuration, it is also possible to select a row, column, or
cell within the table, and to change the data within a cell. JTable is a sophisticated
component that offers many more options and features than can be discussed here. (It
is perhaps Swing’s most complicated component.) However, in its default
configuration, JTable still offers substantial functionality that is easy to use—
especially if you simply want to use the table to present data in a tabular format.
JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a JTable inside a JScrollPane.
295
JTable supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
JTable relies on three models. The first is the table model, which is defined by the
TableModel interface. This model defines those things related to displaying data in a
two-dimensional format.
The second is the table column model, which is represented by TableColumnModel.
JTable is defined in terms of columns, and it is TableColumnModel that specifies
the characteristics of a column. These two models are packaged in javax.swing.table.
The third model determines how items are selected, and it is specified by the
ListSelectionModel, which was described when JList was discussed.
Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
// Demonstrate JTable.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
296
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
}
}
Output from this example is shown here:
297
Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
import java.awt.*;
import java.swing.*;
public class JTable Demo extends JApplet{
public vod init(){
container content pane=get content pane();
content pane.set Layout(new Border Layout());
final string[ ] collteads={“Name”,”USN”,”Age”,”Address”};
final object [ ] [ ] data = {
{“Swamy”,”12cs403”,”26”,”Sargur”},
{“Sunil”,”11cs047”,”21”,”Nanjanagude”,},
{“gagana”,12cs401”,”21”,”Mysore”}
};
JTable table = new JTable(data,collteads);
int v=Scroll pane constants.VErTICAL-SCrOLLBAr-AS-NEEDED;
int h=scroll pane constants.HOrIZONTAL-scrollbar-as-needed;
JScroll pane jsp=new JScroll pane(table, v, h);
Content pane.add(jsp,Border Layout.cednter);
}}
298
AWT SWINGS
We can build user interfaces with AWT Swings is a set of classes that provides
classes more powerful and flexible components
AWT supports all the types of controls Familiar components like buttons, check
like labels, push buttons, check boxes, bixes etc.. have more capabilities in
choice list scroll bars Text editing. These swing
controls are subclasses of component Ex: button may have both image and
container is also sub class of component string associated with it. Also, image can
panel and window is a concrete subclass be changed as the button state changes.
of container
Frame is a subclass of window Swings are nit subclass of windows
AWT is implemented by platform- Swing components are not implement by
specific code platform-specific code Instead, they are
written entirely in Java, and therefore are
platform independent
AWT examines standard controls and
layout managers defined by Java
Controls are components that allow user The term light weight is used to describe
interaction such elements
Layout manager automatically positions The number of class and interfaces in the
components within a container swing packages is substantial
In addition to component, a frame- Swing related classes ave contained in
window is included as standard style JavaX. Swing and its subpackages javaX
menu bar Swing tree
299
12.4 SUMMARY / TO SUM / LET’S SUM UP
At the end of this unit we have learnt the Applets and its life cycle and swings.
Applets, Swings
300
5. What is Swing? List the main Swing features. Explain the different types of panes
of swing containers
6. How AWT is different from Swings? What are the two key features of it ?
Explain
301
UNIT-13 TEXT AND BINARY I/O CLASSES, OBJECT I/O, RANDOM
ACCESS FILES ( I/O STREAMS)
STRUCTURE
13.0 Objectives
13.1 Introduction
13.2 I/O Streams
13.3 Summary
13.4 Keywords
13.5 Questions for Self Study
13.6 Questions for Self Study
13.7 References
13.0 OBJECTIVES
In this unit you will able to learn as follows.
Define virus
Elucidate the different types of computer viruses
Understand the importance of antivirus
State Functions of computer security
302
13.1 INTRODUCTION VIRUS
Types of I /O Streams
There are various types of streams found in the java.io package as shown in fig.8.1. In
the following paragraphs we will discuss about some of them.
303
The various input stream, their functions and the methods supported by them are
given by them in Table 8.1
304
The streams under FilterInputStream are dealt with under the section FilterStream.The
various output streams, their functions and the supported methods are given in Table
8.2
305
are
applicable to this class also. The FileOutputStream class creates a file, if it does not
already
exist, before opening it for output. In case of writing into a read-only file, an
IOException is thrown. Example 8.1 is an illustration of FileOutputStream.
Example 8.1
Open a new file in the editor and enter the following code:
import java.io.*;
Class ReadWriteFile {
public static byte getInput( )[] throws Exception {
byte inp[] = new byte[50];
System.out.println("enter text.");
System.out.println(“only 50 bytes i.e about 2 lines……”);
System.out.println(“press enter after each line to get input into the program”);
for (int i=0;1<50;i++) {
inp[i] = (byte) system. in. read( );
}
return inp;
}
public static void main (String args[]) throwsException {
byte input[] = getInput();
OutputStream f = new Fileoutputstream
for (int i=0;i<50;i++){
f.write(input[i]);
f.close();
int size;
InputStream f1 = new FileInputStream("c:/java/write.txt”);
size=fl.available();
System.out .println("reading contents of file write.txt.. “);
for (int i=0;i<xsize;i++) {
System.out.print ( (char) f1l.read( ));
}
306
f.close();
}
}
ByteArrayStream
This stream contains ByteArrayInputStream and ByteArrayOutputStream .
ByteArrayinputStream
This class uses a byte array as its input source. It has two types of constructors, The
first one takes a byte array as Its parameter.
ByteArrayinput Stream b = new ByteArrayInputStream (buf []);
The next constructor helps to create a ByteArrayInputStream from the specified array
of bytes.
307
ByteArrayInputStream b = new ByteArrayInputStream(buf[],int off,int len);
Off is the offset of the first byte to be read and len is the number of bytes to be read
into the array.
ByteArrayOutputStream
import java.io.*;
class ByteArray {
public static void main(String args[]) throws Exception {
ByteArrayOutputStream f = new ByteArrayOutput Stream(12);
System.out.println("enter 10 characters and press the Enter key");
System.out.println("These will be converted to uppercase and displayed") ;
while (f.size( ) != 10) {
f.write(System.in.read( ));
}
System.out.println("Accepted characters into an array");
byte b[] = f.toByteArray( );
System.out.println("displaying characters in the array");
for(int 1=0;l<b.length;l++) {
System.out.println((char) b[1]);
}
308
ByteArrayInputStream inp = new ByteArrayInputStream(b);
int c;
System.out .println("Converted to upper case characters");
for (int i=0;i<1;i++) {
while ((c = inp.read( )) != -1) {
System. out .print (Character.toUpperCase((char)c));
} Sysetem.out.println( );
inp.reset( );
}
}
}
Save the file as ByteArray.java
Compile the file using javac ByteArray.java
Run the file using java ByteArray al
309
while loop. The next part of the program dumps the input into an array b, initialized at
the line number 11.For better understanding, line numbers 13 to 15 display the
accepted characters from the array. The subsequent part of the program deals with the
conversion of the input into upper case characters and then displays them. At line
number 16, an instance of the ByteArraytnputStream is created. The characters inside
the array b are converted to uppercase characters using the touppercase( ) method
found in the characte class.
FilterStream
FilterStream is dealt under FilterInputStream and FilterOutputStream.The following
classes under the FilterInputStream – BuffereInputStream ,DataInputstream and
PushbackInputStream and the following classes under FilterOurputStream –
BufferedOutStream , DataInputstream ,PrintStream
The classes under FilterInputStream and their functions are discussed in the Table 8.3
310
The various classes under the FilterOutputStream are discussed in Table 8.4.
Table 8.4
BufferedinputStream
The BufferedInputStream class accepts input by using a buffered array of bytes that
acts as cache and it utilizes the mark( ) and reset( ) method. Chunks of bytes from the
buffered array can be chosen and read. To create a Filernputstream that can handle
marking and resetting properly, the nested stream to read a specified portion of a file
called temp is given below.
InputStream s = new BufferedInputStream (new FileInputstream (“temp”));
The above line of code BufferedInputStream for the file Temp.
BufferedOutputStream
The output is stored in a buffered array by bytes, which acts as a cache for writing. As
311
above, a specific number of bytes can be buffered using the nesting facility offered by
the FileStream.
import java.io.*;
class DataStream {
public Static void main(String args(]) throws IOException {
BufferedReader d = new BufferedReader (new InputStream(new
FileInputStream("c:/java/temp”);
DataOutputStream o = new DataOutputStream(new FileOutputStream("c:
/java/temp1") ;
String line;
while ((line = d.readLine( )) != null) {
String a = (line.toUpperCase( ));
312
System.out.printin(a);
o.writeBytes(a + "\r\n");
}
d.close( );
o.close( );
}
}
Save the file as DataStream.java
Compile the file using javac DataStream.java aed
Ensure that there exists a file temp, in the directory ¢:\java. os
Run the file using java DataStream
Suppose the file contains the line "This is an example of DataStreams" as its content.
The output appears as shown below:
313
RandomAcessFile object takes two arguments. The first argument specifies the file
either as a string containing the file name or as a file object. The second arguments is
a string that takes the value “r” if the files is to be read but not written ,or the value
“rw” if the file is to be both read and written. If the specified file does not exist, it is
automatically created.
The following Statement opens the file Test.txt for reading and writing:
RandomAccessFile thefile = new RandomAccessFile (“Test -txt”, "rw");
Unlike InputStream and OutputStream, which access their data sequentially. It is
possible direct to direct a random access file to read or write at any position within a
file by using the seek() method .The seek() method specifies the byte offset from the
beginning of the file ,at which the input and output is to commence.
Stream Tokenizer
Stream Tokenizer class helps in identifying the patterns in the input stream. It is
responsible for breaking up the InputStream into tokens, which are delimited by a set
of characters .The best use of this class is to identify the number of words or lines
within a file .A stream is tokenized by creating a Stream Tokenizer with a Reader
Object as its source and then setting parameters for the screen. A scanner loop
invokes nextToken,which returns the token type of the next token in the screen.
When NextToken recognizes a token, it returns the token type as its value and also
sets the type field to the same value. There are four token types:
TT_WorD : A word is scanned. The String field sval contains the word that is
scanned.
TT_NUMBER. A number is scanned. The double field nval contains the value of the
Number. Only decimal floating numbers are recognized.
TT_EOL : An end-of-line is found.
314
FileReader fr = new FileReader(”“C:\\temp.txt”);
StreamTokenizer input = new StreamTokenizer (fr) ;
int tok;
int count = 0;
while ((tok = input.nextToken( )) != StreamTokenizer.TT _EOF)
if (tok == StreamTokenizer.TT WORD) {
System.out.println("Word found :" + input.sval);
count++;
}
System.out.println("Found "+ count+" words in temp.txt");
}
o Save the file as WordCounter.java
o Compile the file using javac WordCounter.java
o Ensure that a file temp exists in the directory c:\
Run the file using java WordCounter
315
The FileReader class enables reading character files. It uses default character
encoding. FileReader class usage is similar to FileInputStream class and its
constructors are identical to those of FilelnputStream class. The constructor is given
below:
public FileReader(File f)
This constructor can throw a FileNotFound Exception.
CharArrayReader
The Char ArrayReader allows the usage of a character array as an InputStream. The
usage of CharArrayReader class is similar to ByteArrayInputStream. The constructor
is given below:
Public CharArrayReader(char ch[]);
String Reader.
The StringReader class reads character from the string. The constructor is given
below.
316
and buffer size. The usage of FileWriter class is similar to that of FileOutputStream
class. The constructor is given below and it can throw an IOException.
public FileWriter(File f)
CharArrayWriter
CharArrayWriter allows to use a character buffer as an output stream, It is used in
situations where ByteArrayOutputStream is used. The constructor is:
public CharArrayWriter( )
Printer Writer
The PrintWriter class contains methods that makes the generation of formatted output
simple. It can be used instead of PrintStream.The constructor is
public PrintWriter(OutputStream ostream)
The stream is not flushed each time print () method is called.
FilterWriter
The FilterWriter class is used to Write filtered Character streams. It has one instance
variable out, which is a protected reference to the Writer that is being filtered.
protected FilterWriter(Writer w)
BufferedWriter
The BufferedWriter Class buffers data to the character output stream.BufferWriter
class functionality is the same as BufferedOutputStream class .The constructor is
public BufferWriter(Writer w)
Example 8.5
@ Open a new file in the editor and enter the following code:
import java.io.*;
public class WordCounter{
public static void main(String args[]) throws IOException {
BufferReader in =new BufferedReader (new FileReader(args[0}));
String s,
s1=new string();
BufferedReader Stdin=new BufferedReader (new Input StreamReader (System.in));
in.close();
System.out.println(“usage of BufferedReader and Input StreamReader………”);
317
System.out.println(“enter a line”);
System.out.println(stdin.readLine());
Str ingReader in2=new StringReader(s1);
int c;
System.out.println(“printing individual characters of the file ”+args[0]);
while ((c=in2.read()!=-1)
System.out.print1in( (char)c);
BufferedReader in4 =new BufferedReader(new StringReader(s1));
PrintWriter p=new PrintWriter(new BufferedWriter (new Filewriter( “demo.out”)));
while((s=in4.readLine( )) !=nul1)
p.println("output " + s);
p-close( );
}catch(IOException e) { }
}
}
Save the file as ReaderWriter.java
Compile the file using javac ReaderWriter.java
Ensure that a file named temp exists in ¢:\java directory
Run the file using java ReaderWriter c:\java\temp Ze
Let the contents of the temp file be the line "You are Welcome". The output appears
as shown:
Y
o
u
318
a
r
e
W
e
l
c
o
m
e
Between lines 5 and 9, input is accepted from the keyboard and the same is printed on
the screen. The next part of the program uses the file name provided at the command
line. Individual characters in the file are printed on the screen, using the StringReader
object.The Printwriter class object writes the content of the accepted file onto
demo.out.
13.10 SUMMARY
In this Unit we have leant that , There are different subclasses of the Input
Stream and the outputstream. The FileInputstream and Fileoutput stream help
in reading / writing data from actual
disk files.
319
PushbackInputStream takes input from the InputStream and places it back
without disturbing it. The Printstream has two methods syetem.out .print( )
and System.out. printin( ) which are widely used. The streamTokenizer helps
to break the InputStream into tokens.
The Reader and writer classes are used to read / write characters respectively
instead of bytes.
13.11 KEYWORDS
13.14 REFERENCES
320
10. Jose M. Garrido Object-Oriented Programming: From Problem Solving to
Java
11. Bill Venners Object-Oriented Design with Java
12. E. Balaguruswamy Programming with java
13. Internet
321
UNIT-14 MULTITHREADING IN JAVA
STRUCTURE
14.0 Objectives
14.1 Introduction
14.2 Multithreading in Java
14.3 Thread life cycle and methods
14.4 Runnable Interface
14.5 Summary
14.6 Keywords
14.7 Questions for Self Study
14.8 Keys Questions for Self Study
14.9 References
14.0 OBJECTIVES
Upon completion of this unit you will be able to:
322
called multithreading.
For example, to calculate (b*b)-(4*a*c) in quadratic equation, b*b can be calculated
independently of 4*a*c.One thread can execute the first and another next. Thus
completion of this process is faster. Generally, the main thread executing a program is
terminated after all its other threads have been destroyed.
When a program requires user input, multithreading enables creation of a separate
thread for this task alone. The main thread can continue with the execution of the rest
of the program. Programs not using multithreading will have wait the user has input a
value for the continuation of the execution of the program.
The advantages of using threads over processes are as follows.
Can be created faster
Requires less overheads
Interprocess communication is faster
Context switching is faster
Maximum use of CPU time
323
Blocked - The thread could be run but there is something that prevents it. While a
thread is in the blocked state the scheduler will simply skip over it and not give it any
CPU time. Until a thread re-enters the runnable state it will not perform any
operations.
Common Thread Methods
Let us discuss some of the common thread methods:
Start ( ) - The start method starts execution of the invoking object. It can throw an
Illegal exception if the thread was already started
stop () - This method terminates the invoking object.
suspend ( ) - This method suspends the invoking object. The Thread will become
runnable again if it gets the resume () method
sleep ( ) – This method suspends execution of the executing thread for the specified
number of mill second s. It can throw an Interrupted Exception.
public Static void sleep (long ms)
The following statement can suspend execution of the executing thread for the
specified number of milliseconds plus nanoseconds.
public Static void sleep (long ms,int ns)
resume () - The resume ( ) method restarts the suspended thread at the point at which
it was halted. The resume ( ) method is called by some thread outside the suspended
one, there is a separate class called Resumer which does just that. Each of the classes
demonstrating suspend/resume has an associated resume.
324
thread.
Fig. 15.1 - States of a thread
Creation of a Thread
A thread in Java is created as an object of class Thread. It has an interface which is
used along with it concurrently - Runnable interface. Creation of new threads can be
done as follows.
Creating objects of class Thread
Using Runnable interface
325
getName() Gets and returns this Thread’s name
getPriority() Gets and returns the Thread’s priority
setName(String) Sets the Thread’s name
setPriority(int) Sets the Thread’s priority
join() Waits forever for this Thread to die
toString() Returns a String representation of the
Thread ,including the thread’s name,
priority and thread group.
Example 15.5 portrays the usage of some of the methods discussed earlier
Example 15.5
Open a new file in the editor and enter the following code
class ThreadMethodl {
public static void main(String args[]) {
Thread t=Thread.current Thread ();
System.out.printIn("current thread : " + t);
System.out.printin("Name of the current thread : " +t.getName());
System.out.println("Priority : " + t.getPriority());
t.setName(“mythread") ;
System.out.println("after name change : "+t);
t.setPriority(2);
System.out.println("after priority change : " +t);
System.out.printin("number of active threads : "; +t.activeCount () );
}}
Save the file as ThreadMethod1.java
Compile the file using javac ThreadMethod1. java
Run the file using java ThreadMethod1
326
after name change : Thread [main, 5, main]
after priority change : Thread [main, 5, main]
number of active threads : 1
This program gets a reference to the current thread by calling currentThread ()
method, makes use of the methods using this reference and prints relevant details
about it.
Example 15.6 illustrates usage of some more Thread class methods.
Example 15.6
Open a new file in the editor and enter the following code
327
System.out.println("Thread m2 is alive : " +m2.t.isAlive());
try{
System.out.printin("Waiting for threads to finish……..” );
m1.t.join();
m2.t.join();
} catch (InterruptedException e) {}
System.out.println ("Thread m1 is alive: " +m1.t.isAlive ());
System.out.println("Thread m2 is alive : " +m2.t.isAlive());
System.out.println("Main thread exiting “);
}
328
Thread m2 is alive : false
Thread m2 is alive : true
Main thread exiting……
329
} catch (InterruptedException e) {}
System. Out .println ("Exiting child thread ...");
}
public static void main (String args[]){
IntThread i=new IntThread();
try{
for (int j=5;j>0;j--){
System.out.println("Main thread : "+j);
Thread.sleep(1000);
}
}catch(InterruptedException e) {}
System.out.println("Main thread exiting ….”);
}
}
Save the file as IntThread.java
Compile the file using javac IntThread.java
Run the file using java IntThread
A new object of IntThread class is created as the first step, which calls its constructor.
Inside the constructor ,a new thread is created using one of Thread class constructor,
which takes as parameters- the object itself and a string .This helps in creating new
child threads apart from the main thread .The start() method starts each of the newly
created threads.
Automatically, control passes to the run () method. Within it, the sleep () method of
the Thread class suspends the thread for 500 milliseconds. Since this method
generates an exception .it is enclosed within the try block.
Simultaneously, the main thread continues with execution of the main program. The
main thread enters the try block inside main () method and exists at the end of the for
loop. It is ensured that the child thread created is destroyed before main thread
terminates. Note that the output obtained may vary from one system to another.
The output of the above program is :
Child thread: Thread [Test thread, 5, main]
Main thread : 5
Child thread : 5
330
Child thread : 6
Main thread : 4
Child thread : 3
Child thread : 2
Main thread : 3
Child thread : 1
Existing child thread……
Main thread: 2
Main thread: 1
Main thread exiting……
The first line of the output contains Child thread: Thread [Test thread, 5, main].Here
Test thread is the allocated name of the thread.5 is the default thread priority and the
third argument main represents the main represents the default thread group. Thread
priority is discussed in the latter part of this session. Thread group is a data structure
that controls the state of a collection of threads as a whole.
Creating Thread Class Objects
A thread object can be created from Thread class. The run () method should
necessarily exist in classes created as subclass of Thread .The first constructor of
Thread class can be given as follows.
Thread (Runnable, String)
A new thread is created with specified name. It applies the run () method on the
specified target.
The next constructor creates a new thread in the specified Thread group with the
specified name and it applies the run () method on the specified target.
Thread (ThreadGroup, Runnable, string)
The following program illustrates the creation of a thread object using Thread class
and the output produced is the same as example 11.3.
Example 15.4
Open a new file in the editor and enter the following code:
class MyThread extends Thread {
MyThread () {
super ("Using Thread class");
system. out .println ("Child thread : " +this);
start ();
331
}
public void run(){
try{
for (int i=5;i>0;i--) {
System.out .print1n("Child thread "+i);
Thread.sleep(500);
}
}catch(InterruptedException e) {}
System.out .printin("exiting child thread...");
}
}
class TestMyThread {
public static void main(String args[]) {
new MyThread();
try{
for(int k=5;k>0;k--) {
System.out.println("Running main thread :"+k);
Thread.sleep(1000);
}
}catch(InterruptedException e) {}
System.out.println("Exiting main thread ...");
}
}
Save the file as TestMyThread.java
Compile the file using javac TestMyThread.java
Run the file using java TestMyThread
332
Child thread : 2
Running main thread : 3
Child thread : 1
Existing child thread……
Running main thread : 2
Running main thread : 1
Existing main thread……
In the main method, a new object of MyThread a subclass of Thread is created. The
constructor of MyThread class calls the base class constructor using super and starts
the thread .The run() method of the call starts after this .It can be observed that both
the main thread and created child thread are executed concurrently.
14.5 SUMMARY
In this Unit we have learnt Multithreading in Java, Thread life cycle and methods
And also Runnable Interface
14.6 KEYWORDS
333
14.8 REFERENCES
334
UNIT-15 THREAD SYNCHRONIZATION
STRUCTURE
15.0 Objectives
15.1 Introduction
15.2 Thread Synchronization
15.3 Exception Handling with try-catch-finally
15.4 Summary
15.5 Keywords
15.6 Questions for Self Study
15.7 Keys Questions for Self Study
15.8 References
15.0 OBJECTIVES
335
15.1 INTRODUCTION
This unit intends to introduce concept like synchronization of threads to enable data
integrity, inter thread communication using wait (), notify () and thread priorities.
Synchronization
Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. For example, when two people access a saving account, it is possible that
one person may overdraw and the cheque may bounce. The important of updation of
the passbook can be well understand in this case.
Example 15.7
Open a new file in the editor and enter the following code
Class Inventory {
static int qoh = 500;
static int req = 0;
static public synchronized void request(int order){
if(order<=qoh){
336
System.out.printIn ("Quantity Ordered: " + order);
qoh-=order;
req+=order;
System.out.printIn("Quantity on hand : " + qoh);
System.out.printIn("Total quantity taken away by way of order : " + req);
}
else {
System.out.printIn ("Ordered quantity more than quantity on hand”);
}
}
public static void main(String args[]) {
new OurThread();
new OurThread();
try{
for (int p=3;p>0;p--){
System.out.printIn ("================================”);
System.out.printIn ("main thread : ” +p);
System.out.printIn ("================================”);
Thread. Sleep (10000);
}
}catch (Interrupted Exception e){}
System.out.printIn (“exiting main thread”);
}
}
class OurThread extends Thread {
OurThread () {
super (“test thread”);
System.out.printIn( “child thread : ”+ this);
start ();
}
public void main run(){
for (int i=5;i>0;i++){
try{
sleep(100);
337
}
public void run() {
for (int i=5;i>0;i--){
try{
sleep(100);
} catch (Interrupted Exception e){}
Inventory.request((int )(Math.random()*100))
}
}
}
Save the file as Inventory.java
Compile the file using javac Inventory. java
Run the file using java Inventory
Two objects of class OurThread are created, which call their constructor .Since the
class OurThread is a subclass of Thread, the base class constructor is called using
super. The child Thread is also started within this.
The run method of OurThread class calls the request () method of Inventory class.
Note the usage of random () method of the Math class .Since it returns a double value
and the request () method takes an integer parameter, there arises a necessity for
typecasting at line number 41.The random () method is used to generate values for
orders. In case, generated number exceeds the qoh, an error message is printed.
The important methods of this program is request ().Both the threads that are created
are trying to access request () at the same time, hence it is declared as synchronized,
static, public and void .Inside this method, a check is made if quantity on hand is
greater than or equal to the quantity on hand is greater than or equal to the quantity
ordered. If so, then qoh is updated.
Interthread Communication
There may be cases where one of the created threads requires data from another. It
becomes essential to check every few seconds, whether the second thread has
338
produced the required information or not .Till such time, the first thread waits,
wasting CPU time.
Java offers interprocess communication through the usage of wait (), notify (),
notifyAll () methods of object class and all are synchronized methods.
Wait () – This method waits indefinitely on another thread of execution until it
receives a notify () or notifyAll () message.
notify () – This method wakes up a single thread waiting on the Object’s monitor.
notifyAll () – this method wakes up all threads waiting on the Object monitor.
Example 15.8
Open a new file in the editor and enter the following code
class Consumer implements Runnable {
Stock c,
Thread t;
Consumer (Stock c){
this .c=c;
t=new Thread (this,”producer thread”);
t.start();
}
public void run(){
339
while (true)
try {
t.sleep(500);
} catch(Interrupted Exception e){}
c.getStock((int)(Math.random()*100));
}
}
void stop(){
t.stop();
}
}
Save the file as Consumer.java
Open another new file and enter the following code:
340
}
Both the Producer class and the Consumer class create a thread, using goods are
added are consumed respectively. The run () method of both the classes use the
random () method of Math class to generate random numbers.
Open a new file in the editor and enter the following code
Class Stock {
int goods=0;
public synchronized void addStock (int i){
goods=goods+i;
System.out.printIn ( “Stock added: ”+ i);
System.out.printIn ( “Present Stock: ”+ goods);
notify();
}
public synchronized void getStock (int j){
goods=goods-j;
System.out.printIn ( “Stock taken away: ”+ j);
System.out.printIn ( “Present Stock: ”+ goods);
break;
}
else{
System.out.printIn ( “Stock not enough……….:”);
System.out.printIn ( “Waiting for stocks to come ………..”);
try{
wait();
} catch(Interrupted Exception e){}
}
}
return goods;
}
341
public static void main(String args[]) {
Stock j = new Stock();
Producer p= new Producer(j);
consumer c = new Consumer(j);
try{
Thread.sleep(100000);
p.stop();
c.stop();
p.t.join();
c.t.join();
System.out.printIn ( “Thread stopped”);
} catch(Interrupted Exception e){}
System .exit(0);
}
}
Save the file as Stock.java
Compile the file using javac Stock. java
Run the file using java Stock
The output depends on the random number generated in the Consumer and Producer
classes.
The main method creates a Producer and Consumer object, which call their respective
constructors. Within the constructors of these classes, threads are created and started.
The run () method of both these classes are executed concurrently. Within the run
methods, addstock () and getStock () methods of the stock class are called. If the
requested goods for consumptions is greater than the stock at hand (goods produced +
buffer stock), the wait () method of the object class is called which waits until it gets
information from notify () method within the addstock () method. As soon as goods
and added buffer stock, the notify () method is called. This process continues, while
the main thread resumes, both the child threads are terminated using join ().
Thread Priorities
Each thread created has a priority attached to it .The scheduler allocates time in
accordance to these priorities. A thread with higher priority can preempt lower
priority thread, thus taking CPU’s time. The yield () method enables provision of
342
CPU’s time to thread with equal priority and prevents monopolization of a single
thread.
The usage of setPriority and getPriority method is already explained. These are used
to set and get the priorities respectively .Threads have maximum and minimum
priorities set by default .The Thread class has final variables declared like –
NORM_PRIORITY,MINIMUM_ PRIORITY and MAXIUM _ PRIORITY to set
default priorities. A thread can have a maximum priority of 1.Normal priority is set at
5.
343
generates error that occurs during the execution of a program. For example, trying to
access an invalid array index, division by zero, etc. cannot be known at compilation
time. They are generated at runtime .It is good programming practice to anticipate
such error and handle them. RuntimeException is defined, by default all program .Fig
6.1 illustrate the Exception class hierarchy.
Object
Throwable
Error Exception
IOException RuntimeException
Example 6.1 tries to set a value to the tenth element of the integer array, which
generated ArrayIndexOutOfBoundsException.
Example 6.1
Open a new file in the editor and enter the following code:
344
}
Save the file as DefException.java
Compile the program using javac DefException.java
Run the program using java DefException
345
}
}
Save the file as NegTest.java
Compile the file using javac NegTest.java wand
Run the file using java NegTest
Example 6.3
Open a new file in the editor and enter the following code:
346
while (line = d.readLine()) !null){
if (line.equals(“end”))
break;
else {
try {
x=Integer.parseInt(line);
system.out.println(“valid element and it is :”+arr[x] );
}catch(ArrayIndexOfBoundException e){
system.out.println(“invalid ekement”);
system.out.println(“exception generated :”+e);
}catch(NumberFormatException n){
system.out.println(“sorry no characters”);
system.out.println(“generated exception :””+n);
}
}
}
}catch(IOException i) {}
}
}
Save the file as MultiCatchException java
Compile the Program Using javac MultiCatchException,java
Run the program Using java MultiCatchException
The program executes different catch statements depending on our input. The
program initially displays the following lines:
enter a number as array index and find out its value
enter end to come out of the program
If we input a character or a string or a string then the output appears as:
sorry no characters
generated exception :‘java. lang –NumberFormatExcept : e
if we input number greater than 4 Or less than 0 then the output appears as:
invalid element
exception generated : java.lang.ArrayIndexOutOfBoundsException
If we input a number between 0 and 4, say 3, then the output appears as:
347
valid element and it is:400
The above program accepts an array index from the user. To exit the program, the
user should type “end”. If the accepted input is a valid index, the corresponding value
is displayed. If the array index is invalid, an ArrayIndexOutOfBoundsException is
generated, On entering characters as input, a NumberFormatException is generated.
The parsetnt() method of the integer class generates a NumberFormatException, when
the string passed does not represent a number. Note that, in case of generation of both
the exceptions the program does not terminate abruptly. Each catch clause is searched
in order by the exception to identify its matching one. The 10Exception takes care of
identifying exceptions generated while accepting input.
Care should be taken to ensure that the subclass exception precedes the base class
exception. For example, in order to catch FileNotFoundException and 10Exception
within a try block. it is essential to catch FileNotFoundException earlier than
IoException. Example 6.4 illustrates sub class exception precedence over the base
class.
Example 6.4
Open a new file in the editor and enter the following code:
// To illustrate sub class exception precedence over base class
import java.io.*;
class BaseSubException {
public static void main(String args[]) {
if(args.length=<0) {
System.out.println("invalid usage");
System.out.println("Usage : java <filename> filel file2 -file3 ...”);
return;
}
for (int i=0;i<arge.length;i++) {
File f= new File(argse[i]);
try {
String line;
DataInput d = new DataInputStream(new FileInputstream(args[i})),
if (f.exists() && f.isFile()) {
System.out.println("file exists");
System.out.println(f + " is ordinary file");
348
System.out .println("printing the contents of file named : " + args[i]);
System.out .println(“===========================”);
while ((line = d.readLine())!=null) {
System.out.println(line);
} //end while
} // end if
} catch (FileNotFoundException e) {
if (f.exists() && £.isDirectory()){
System.out -printin( “===============") ;
System.out.printin("Name : " + f + " is a directory");
System.out.printlin("inside catch of FileNotFoundException") ;
System. out .print1n(“=======================");
}else{
System. out .print1n (“===================");
System.out.println("Name : " + args[i] + " does not exist");
System.out.print1n("generated exception :"+e);
System.out. println( “============================" ) ;
}
} catch(IOException p) {
System.out.println("super class is higher up in the program");
}// end of for
}
}
}
349
Select File>Exit from the menu
Type mkdir testdir in the command line and click Enter
Run the BaseSubException program using java BaseSubException testdir
test.txt
try.txt (where try.txt does not exist in the current directory)
Let us suppose that we have a file named test.txt and a directory named testdir inside
the current directory. Let us also assume that the file test.txt does not exist
Run the file using java BaseSubException
The above program accepts file names as commandline arguments. It displays the
contents of the file, if the file exists and if it is an ordinary file. Otherwise, an
exception is generated which is caught by the FileNotFroundexception. Inside this
catch, a check is made to ascertain if the file is a directory or if it does exist at all.
Accordingly the statements within the if Or else are executed. Try inserting the catch
clause of IOException first and then the catch of the FilenotFoundException,
Compilation error results saying that catch of the FileNotFoundException is not
350
reached. Since FileNotFoundexception is a subclass of the IOException, it is essential
that it should precede the base class.
try, catch and finally
When an exception is generated in a program, sometimes it may be necessary to
perform certain activities before termination. The activities may be closing of a file,
deleting a graphics object created, etc. In such cases, the try block, apart from the
catch clause, also has finally block within which the activities mentioned above can
be performed. This block is executed after the execution of statements within the
try/catch block. Thus it bypass all the other methods existing in the program, In case
an exception is thrown, the finally block will be executed even if no catch matches it.
The try block requires either a finally clause or a catch clause.
Example 6.5 illustrates the usage of the try / catch with finally clause.
Example 6.5
¢ Open a new file in the editor and enter the following code:
Output
351
System.out.println("inside finally ");
System.out.println("ha! I always have the final say");
System. out -println(“========================");
}
}
}
Save the file as FinallyException.java
Compile the file using javac FinallyException.java
Run the file using java FinallyException
class ThrowsException {
352
public static void main(String args[])throws ArithmeticExceptiont {
System.out.println("inside main");
int i=0;
int j=40/i;
Syetem.out.printlin("this statement is not printed");
}
}
Save the file as ThrowsException.java
Compile the file using javac ThrowsException.java '
Run the file using java ThrowsException
Usage of throw
The throw statement is used to explicitly throw an exception. First, a handle on an
instance of Throwable must be got (via a parameter) into a catch clause or by creating
one using the new operator. The general form of a throw statement is given below:
throw <Throwableinstance>
where <Throwableinstance> is the instance when the throw has to be executed.
The flow of execution stops immediately after the throw statement and the next
statement is not reached. The closest enclosing try block is inspected to see if it has a
catch clause which matches the type of the Throwable instance. If it finds a match,
then control is transferred to that statement. If no match is found, the next enclosing
try statement is inspected and the cycle continues till the outermost exception handler
stops the program.
Example 6.7 demonstrates throwing a new instance of an exception, then rethrowing
353
the same Exception to the outer handler.
Open a new file in the editor and enter the following code:
Class Throwdemo{
static void demoproc() {
try{
throw new Null PointerException ("demo") ;
}catch(Null PointerException e) {
system.out.print(“Caught inside demoproc");
throw e;
}
}
public static void main(String args[]){
try{
demoproc
}catch (NullPointerException e) {
System.out.println("Recaught:" +e);
}
}
}
Save the file as Throwdemo.java
Compile the file using javac Throwdemo.java a.
Run the file using java Throwdemo
354
When we override a method, we can throw only the exception that has been specified
in the base-class version of the method. This is a very useful restrictions since it
means that the code which works with the base class will automatically work with any
object derived from the base class(a fundamental OOP concept),including exception.
It is useful to realize that, although exception specifications are enforced by the
compiler during inheritance, the exception specifications are not part of the type of a
method. The method is comprised of only the method name and argument types.
Therefore, we cannot overload methods based methods on exception specification. In
addition, because an exception specification exists in a base-class version of a method
does not mean it must exist in the derived-class version of the method, and this is
quite different from inheriting the methods themselves.
15.4 SUMMARY
In this Unit we have learnt Thread Synchronization and Exception Handling with try-
catch-finally
15.5 KEYWORDS
1. What is Synchronization?
2. What is an Exception ? Explain different types of Excepion handlers.
355
15.7 REFERENCES
356
UNIT-16 INTRODUCTION TO JAVA BEANS AND NETWORK
PROGRAMMING
STRUCTURE
16.0 Objectives
16.1 Introduction
16.2 Collections in Java
16.3 Introduction to Java Beans
16.4 Network Programming
16.5 Summary
16.6 Keywords
16.7 Questions for Self Study
16.8 Keys Questions for Self Study
16.9 References
16.0 OBJECTIVES
After going through this unit you will able to learn:
357
16.1 INTRODUCTION
In this unit we will learn Collections in Java , Introduction to Java Beans and
Network Programming.
Collections in Java
1. Java Collection Framework
3. Collection interface
4. Iterator interface
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList
, Vector, LinkedList
, PriorityQueue
, HashSet, LinkedHashSet, TreeSet).
o It is optional.
358
What is Collection framework
2. Algorithm
JavaBean
o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as
getter and setter methods.
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
359
}
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object. One way is by constructor
and second is by setter method.
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.
Nested Structure in C
Keep Watching
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
Advantages of JavaBean
360
o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
o Creating the setter and getter method for each property separately may lead to
the boilerplate code.
16.4 NETWORKING
Java networking
Introduction to Networking
A network is a set of computers and peripherals, which are physically connected
together. Networking enables sharing of resources and communication. Internet is a
network of networks. Java applets can be downloaded from a Web site. This is one of
the main attractions of Java. Networking in Java is possible through the use of
java.net package. The classes within this package encapsulate the socket model
developed by Berkeley Software Division.
The following sections introduce various terms used generally while discussing
networking.
Protocols
Communication between computers in a network or a different network requires
361
certain set of rules called protocals.java networking is done using TCP/IP protocol.
Some of the different kinds of protocols available are HTTP (Hyper Text Transfer
Protocol – enables Interaction with the internet), FTP (File Transfer Protocol - enables
transfer of files between Computers), SMTP (simple Mail Transfer Protocol —
provides e-mail facility) and NNTP (network news transfer Protocol — acts as a
bulletin board for sharing news).
Socket
Sockets can be understood as a place used to plug in just like electric sockets.in case
of electric sockets, if a toasters plug is plugged into a socket, communication start at
the time. It is essential that they should follow a set of rules to communicate called
protocals.Assuming that the toaster has been plugged in the socket at the kitchen, the
power grid of the house should know the point of communication or the address of the
socket. A network socket can be similarly understood. Here TCP/IP as protocol for
communication and IP addresses are the addresses of the sockets.
Specific ports are assigned to some protocols by TCP/IP A few examples are port
number 21 is assigned for FTP, 23 is assigned for Telnet, 25 is assigned for e-mail, 80
for HTTP and so on. Each protocol establishes specific set of rules to communicate.
For example, to transfer hypertext pages and images, Web browsers and servers use
the HTTP protocol.
Client / Server
A computer, which requests for some service from another computer, is called a client
.The one that processes the request is called as Server. A server waits till one of its
clients makes a request. It can accept multiple connections at a time to the same port
number. Multithreading is used to serve multiple users at the same time.
Internet Address
Every computer connected to a network has a unique IP address. It is similar to every
student of a batch having a unique id. An IP address is a 32-bit number which has four
number separated by periods.It is possible to connect to the Internet either directly or
by using internet service provider.by connecting directly to the Internet, the computer
is assigned with a permanent IP address. In case connection is made using ISP,it
assigns a temporary IP address for each session. A sample IP address is given below.
362
Domain Naming Service
It is very difficult to remember a set of numbers (IP address) to connect to the
Internet. The Domain Naming Service (DNS) is used to overcome this problem. It
maps one particular IP address to a string of characters. For example,
"www.mascom.com" implies com is the domain name reserved for US commercial
sites, mascom is the name of the company and www is the name of the specific
computer, which is mascom’s server.
InetAddress
There are classes provided in Java to enable networking. They are found In the
java.net package. InetAddrese is one such class, which is used to encapsulate the IP
address and the DNS. To create an instance of inetaddress class, factory methods are
used as there are no visible constructors available for this class. Factory methods are
conventions where static methods return an instance of that class.
Methods
Static InetAddress getlocalHost() Return InetAddress object representing
local host.
Static inetaddress getbyname(string Return InetAddress for the host passed to
hostname) it.
Table 16.1
Both the methods throw UnknownHostNamEexception, if they are unable to local the
host.
The following program illustrates the creation of an inetaddress object.
Example 16.1
Open a new file in the editor and enter the following code:
import java.net,*;
class InetAddresstest{
public static void main(string args[]) {
try {
InetAddress add=InetAddress.getlocalhost();
363
System.out.printin(‘’address of local host is : “” + add);
} catch (unknownhostexception u) {}
}
}
Save the file as inetaddresstest.java
Compile the file using javac inetaddresstest.java
Run the file using java inetaddresstest
Datagram
Datagram is a type of packet that represents an entire communication. There is no
necessity to have connection or disconnection stages when communicating using
datagram. This is less reliable than communication using TCP/IP.
There are two classes in Java, which enable communication using datagrams,
DatagramSocket is the class, which acts as the data container, and DatagramSocket is
a mechanism used to send or receive DatagramPackets.
DatagramPacket
A DatagramPacket object can be created as follows.
Constructors
DatagramPacket (byte data [], int size)
The above constructor takes a byte array and its size as its parameter.
DatagramPacket (byte data[], int size, InetAddress I, int port)
In addition to the byte array and its size, the above constructor takes the InetAddress
and the port as its parameters.
DatagramSocket
The class DatagramPacket does not provide methods to send or receive data. This job
is taken up by the Datagram socket class. Listed below are its constructors and some
of its methods.
Constructors
364
The creation of a DatagramSocket object throws a SocketException, which must be
handle.
There are two constructors of DatagramSockets class, the first constructor does not
take any parameters and is created as given below:
Datagramsockets s= new datagramsockets ();
The next constructor is given as follows.
DatagramSocket s=new DatagramSocket (int port);
Methods
send (DatagramPacket d) Dispatches the given DatagramPacket
object
receive(DatagramPacket p) Receives the given DatagramPacket
object
Close() Close the socket connection
Table 16.2
Note: The send and receive methods of the DataFramSockets class throw an
IOException which must be caught.
Example 16.2 contains a program code for client and server using Datagram. Any
string entered as input in the window running the server program is displayed in the
client’s window. The user has to enter “end’’ to exit the server program and press
Ctrl+C to exit the client program. Note the client and the server program should run
on the same machine. Open two instances of the MS-DOS prompt and simultaneously
run both the programs.
Example 16.2
Open a new file in the editor and enter the following code:
Input/
Output
1: import java.net.*;
2: import java.io.*;
3: class datagramclient {
4: public static datagramsocket ds;
5: public static byte buffer[]=new byte[1024];
6: public static int clientport =789,serverport=790;
7: public static void main(string args[]) throws Exception {
365
8: ds=new datagramsocket(clientport);
9 System. out .printin( "Client je waiting for server to send data’’);
10: system. out .printin("pres® ctrl4c to come to dos prompt");
11: while(true) {
12: DatagramPacket p= new patagramPacket (buffer, buffer.length);
13: de. receive (p);
14 String pex=new string (p.getData(),0,p.getLength());
15: system. out .print1n (psx);
16: }
17: }
18: }
Note: The line numbers given are not part of the source code and should not be
typed so.
Save the file as DatagramClient.java
Compile the file using javac DatagramClient.java
Run the file using java DatagramClient
366
8: ds=new DatagramSocket (serverport) ;
9: BufferedReader dis=new buffereader(new Inputstreamreadersystem.in));
10: system.out.printin(‘’server waiting for input’’);
11: inetaddress ia=inetaddress.getbyname(‘’localhost’’);
12: while(true) {
13: string str- dis.readline();
14: if((str==null // str.equals(‘’end’’)) }
15: break;
16: buffer=str.getbytes();
17: ds.send(new Datagrampacket(buffer,str,length(),ia,clientport));
18: }
19: }
20: }
Note: The line numbers given are not part of the source code and should not be
typed so.
367
TCP/IP
TCP/IP sockets are the most reliable, bi-directional, stream protocols. It is possible to
send arbitrary amounts of data using TCP/IP. Sockets are used for data
communication using this protocal. There are two kinds of sockets in Java - a server
and a client. The ServerSocket class is used by the server to wait for the client and the
client connects to the server using Socket class.
Socket Class
A socket object establishes connection between the client and the server. Given below
are its constructors and some of the methods associated with it.
Constructors
The first constructor takes the hostname and port as its parameters to create a socket
object. Creation of a Socket object throws an UnknownHost Exception or an
IOException which must be caught.
Socket s= new Socket (String hostName, int port);
The next constructor takes the Inetaddress and port number as its parameters s to
Socket Object. The constructor throws an IOException or an UnknownHost
Exception which must be caught and handled.
Socket s=new Socket (InetAddress a, int port);
Methods
InetAddress getInetAddress() Returns Inetaddress associated with
socket
object
368
OutputStream getOutputStream() Returns the output Stream associated
with this socket
void close() Closes both Input stream and Output
Stream
Table 16.2
ServerSocket Class
The ServerSocket object waits for the client to make a connection. An object of this
class registers itself as having an interest in client connections. Apart from using the
methods listed above, this class has accept () method which is used to wait for a client
to initiate communications. The normal Socket object is used for further transfer of
data.
Constructors
There are two types of constructors available. The first constructor accepts a port
number as parameter to create a ServerSocket object on that port. Creation of this
object throws an IOException, which must be caught and handled.
ServerSocket ss=new ServerSocket (int port);
The next constructor accepts a port and maximum queue length as parameters. The
queue length indicates the maximum number of client connections that the system can
have before refusing further connections.
ServerSocket ss=new ServerSocket (int port, int maxqu);
The following example has code for a server and client program. Use two instances of
MS-DOS prompt, run the client program on one window and the server program on
the other. Note that the client and the server program should run on the same machine.
Run the FileSarver before running the FileClient program. This program displays the
contents of thefile specified in the server on to the client. Ensure that the specified file
exists in the same directory as the server program.
Example 16.3
Open a new file in the editor and enter the following code:
1. import java.net.*;
2. import java.io.*;
3. public class FClient {
4. public static void main(string[] args) throws IOException (
5. Socket echoSocket = null;
369
6. BufferedReader in = null;
7. try {
8. echoSocket = new socket (Inetaddress.getLocalHost (),95);
9. in = new BufferedReader (new Input StreamReader (echoSocket .get Input
Stream() )) ;
10. } catch (UnknownHostException e) {
11. system.err.print1n("Don't know about host");
12. System. exit (1) ;
13. } catch (IOException e) {
14. system.err.printin("Couldn't get I/O for the connection");
15. System.exit (1);
16: }
17: String userInput;
18: while ((userInput = in.readLine() ) != null) {
19: System.out.println(userInput) ;
20: }
21: in.close();
22: echoSocket .close();
23: }
24: }
Note: The line numbers given are not part of the source code and should not be
typed so.
A new socket object is created using the local host name and the port number. To read
the Input sent from the server, a Buffered Reader object is created, The get Input
stream of the socket class is used to obtain the input stream from the server .
370
Open another new file and type the following code:
1: import java.net.*;
2: import java.io.*;
3: public class Fserver {
4: public static void main(String[] args) throws IOException {
5: serversocket serverSocket = null;
6. try {
7: serversocket = new ServerSocket (95);
8: } catch (IoException e) {
9: system.err.println("Could not listen on port:95.");
10. System.exit (1);
11. }
12. Socket clientSocket = null;
13. try {
14. clientSocket = serverSocket .accept ();
15. system.out.printIn("Connected to:" + clientSocket) ;
16. } catch (IOException e) {
17. System.err.println("“Accept failed.");
18. System.exit (1);
19. }
20: PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
21: String inputLine, outputLine;
22: bufferedReader stdin=new BufferedReader (new
inPutStreamReader (System. in) );
23: system.out Print In ("enter data in server");
24: string s=stdin.readline();
25: file f=new file(s);
26: if(f.exists()) {
27: bufferedreader d=new bufferedreader(new Filereader(s));
28: string line;
29: while((line=d.readline()) !=null) {
30: out.write(line);
371
31: out.flush();
32. }
33. d.close();
34. }
35. out.close();
36. elientsocket .close();
37. serverSocket ,close();
38. }
39. }
Note: The line numbers given are not part of the source code and should not be
typed so.
The ServerSocket object waits for a client to make a connection at some port number
95.Once a client makes a connection, the accept method is called to accept the
connection, after which a message is displayed giving details about the local port
number. Client address and the port number of the client.
The server program requests for a file name. This file must be present in the current
working directory. A check is made at the server end and if the file exists, the data is
read by the socket object using the getInputstream method. The transfer of data
between the client program and the server program takes place using the socket
object. The client end displays the file contents. Both the programs terminate after the
request is serviced.
The output from both ends is shown below.
C:\>java FServer
Connected to ‘Socket [addr=GAYA/130.2.0.164, port=1100, localport-=95]
enter data in server
Let us give the input as soc.txt
C:\>java FClient
372
Welcome to socket Programming, Hope you enjoyed this
In the ouput shown above, GAYA is the name of the machine and 130.2.0.164 is its
IP address.
URL
URL stands for Uniform Resource Locator and it points to resource files on the
internet. The term Web is often used when there is a discussion about the Internet.
The web is a collection of higher level protocols and file formats. An important aspect
of a web is its ability to locate on the internet. The URL helps in locating such files
using their addresses on the net. Java provides URL class that provides an API to
access information across the internet.
Components of URL
The URL has four components-the protocal. IP address or the hostname, port number
and actual file path. The protocols may be http, smtp, nntp, ftp or gopher. The most
commonly used protocal of the web is the hypertext transfer protocal (HTTP). The IP
address is delimited on the left by double slashes (//) and on right by a slash (/) or a
colon. The component, port, is optional and is delimited on the left by a colon and on
the right by a slash. The last component specifies the actual file path.
Given below is an example of an url.
http://www.freeway.com:80/root/htmlfiles/index.html
http is the protocal.www.freeway.com is the host name,80 is the port number and the
file index.html is stored under root/htmlfiles directory.
Constructors
There are four constructors and creation of URL, object throws a
MalefromedURLExceptions.
The first constructor takes the urlname as parameter and creates an object. This is the
most commonly used constructor to create the URL object.
URL u = new URL (String urlname) ;
The next constructor takes the name of the protocol, host name, port number and the
file path as parameters.
URL u=new URL (String protocolname, String hostname, int port, String path);
373
The third constructor accepts three parameters as given below.
URL u=new URL(String protocolname, String hostname, String path);
The last constructor accepts the URL object and a string.
URL u=new URL(URL urlobj, String urlspecifier);
Methods
Returns specified port number in URL /
get Port () returns —1 if port is not explicitly set .
Getcontenttype()
returns content type & returns null if not
known .
Table 16.4
16.9 SUMMARY
In this unit the Network one of the main attractions in java, is possible
through the use of java.net package.
374
Communication between computers is a network or a different network
requires certain set of rules called protocals.
A computer, which requests for some service from another computer, is
called a client and the one, which processes the request, is called as server.
Domine naming service9DNS) is used to map one particular IP address to
a string of characters.
TCPAP sockets are the most reliable, bi-directional, stream protocols. The
server to wait for the client uses the serverSocket class and the client to
connect to the server uses the socket class.
The URL class helps in locating files on the Net using their addresses class is
a general . URLConnection class is a general -purpose class that provides
methods to know more about the remote resource.
16.10 KEYWORDS
375
6. Write an applet to display the home page of any html file using URL class.
(Hint : use getAppletContext() and showDocument() methods).
7. Write a code snippet where a ServerSocket waits for a connection from
clients. It should send a string “welcome to java networking” to all its
connected clients.
8. Write a code snippet where a Socket object prints the string on to the client.
9. Explain Protocols
10. What is a Datagram?
11. Give the Components of URL
16.13 REFERENCES
376