You are on page 1of 162

1

[Long Question 8-10]


Chapter 1
BASICS
2. Explain the Features of Java ? [ Nov / Dec 2008] , [Oct / Nov 2009]
Following are the features of JAVA.
1. Simple and powerful
Java was designed to be easy to learn and use. Since it exposes the
inner working of a machine.
the programmer can perform his desired actions without fear.
Unlike other programming systems that the provide dozens of
complicated ways to perform a simple task
Java provides a small number of clear ways to achieve a given task.
Anyone can master Java with a little bit of programming experience.
If the user already understands the basic concepts of object-oriented
programming, learning Java with be much easier.
2. Secure
Today everyone is worried about safety and security.
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 be violated.
3. Portable
The quality of being architecture neutral allows for a great deal of
portability.
However, another aspect of portability is how the hardware interprets
arithmetic operations. In C and C++, source code may run slightly
differently on different hardware platforms because of different
methods of implementing these arithmetic operations.
In Java, this has been simplified. An integer type in Java, int, is a
signed, twos complement 32-bit integer.
A real number, float, is also a 32-bit floating-point number.
These consistencies make it possible to have the assurance that any
result on one computer with Java can be replicated on another.
4. Object-oriented

Java gave a clean, usable, realistic approach to objects.


The object model in Java is simple and easy to extend, while simple
types, such as integers.
float etc, are kept as high-performance non-objects.

5. 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 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.

Java virtually rectifies the problem of memory management by


managing memory allocation and automatic memory deallocation by
providing garbage collection for unused objects.

Java also handles exceptional conditions by providing object-oriented


exceptional handling. In a well-written Java program, all run-time
errors can and should be managed by the program itself.

6. Multithreaded
Java was designed to meet the real-world requirements of creating
interactive, networked programs to achieve this,
java supports multithreaded programming, which allows the user to
write programs that perform many functions simultaneously
The Java run-time system enables the user to construct smoothly
running interactive systems.
Javas easy-to-use approach to mutithreading allows the user to think
about the specific behavior of his-her own program, not the
multitasking subsystem.
7. Architecture-neutral
The Java designers worked hard in achieving 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 problem 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.

8. Interpreted and High performance


Java enables the creation of cross-platform programs by compiling the
code into an intermediate representation called Java bytecode.
This code can be interpreted on any system that has a Java Virtual
Machine.
Most of the earlier cross-platform solutions are run at the expense of
performance.
Java was designed to perform well on very low-power CPUs.
Java bytecode was carefully designed so that it can be easily translated
into native machine code for very high performance.
9. Distributed
Java is designed for the distributed environment of the Internet,
because it handles TCP/IP protocols.
In fact, accessing a resource using a URL (Uniform Resource Locator)
is not different from accessing a file.
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).
10. Dynamic
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 are small fragments of bytecode may be dynamically updated on
a running system.
/* A program displaying the usage of variable and data types */
class second
{
public static void main (String args[])
{
int x = 90;
short y = 4;
float z = 10.87f;
String name = "Ram";
System.out.println("\n\nThe integer value is " + x);
System.out.println("\n\nThe integer value is " + y);
System.out.println("\n\nThe integer value is " + z);
System.out.println("\n\nThe integer value is " + name);
}
}

/* Write a program to add, substract, multiply and divide two numbers */


class three
{
public static void main (String args[])
{
int x = 10;
int y = 20;
float z = 25.98f;
System.out.println("\n\nThe value of x + y is " + (x+y));
System.out.println("\n\nThe value of x - y is " + (z-y));
System.out.println("\n\nThe value of x * y is " + (x*y));
System.out.println("\n\nThe value of x / y is " + (z/y));
System.out.println("\n\nThe value of x % y is " + (z%y));
}
}

3. Types of Flow Controls in java ? [March/April -2009]


Following statements are used to control the flow of execution in a program.
1. Conditional Statements
If else statement
Switch case statement
2. Looping statements
For loop
While loop
Do while loop
3. Other statements
Break
Continue
3.1 Conditional Statements
3.1.1 If-else statement
a.
if (expression)
Statement;

When the expression is true the Statement within the if is executed.


After that execution continues with the next statement after the if statement.

If the expression is false then the statement within the if is not executed and
the execution continues with the statement after the if statement.

/* This progam finds the largest of three numbers */


class larger1
{
public static void main(String args[])
{
int x1 = 15;
int x2 = 20;
int x3 = 10;
int large;
large = x1;
if (x2 > large)
large = x2;
if (x3 > large)
large = x3;
System.out.println("\n\n\tLargest number = " + large);
}
}
b.

if (expression)
{
Statement 1;
Statement 2;
}

c.

Same as in case a, except that here multiple statements are executed if the
expression Is true.
Note that when multiple statements are to be executed when the expression is
true, they are enclosed within parentheses.
if (expression)
Statement 1;
Else
Statement 2;

If the expression is true, execute statement 1, otherwise execute statement 2.


After that proceed with the next statement after the if-else statement.

/* This program checks whether the student has passed or not */


class result
{
public static void main(String args[])
{
int marks = 45;

if (marks<40)
System.out.println("\nThe student has failed .. ");
else
System.out.println("\nThe student has Passed .. ");
}
}
d.

if (expression)
{
Statement 1;
Statement 2;
}
else
{
Statement 3;
Statement 4;
}

Same as in case c, except that here Statement 1 and Statement 2 are executed
when the expression is true and Statement 3,
Statement 4, are executed when the expression is false.

/* Program to display the use of if..else..if */


class if1
{
public static void main(String args[])
{
int month = 12;
String season;
if (month == 12 || month == 1 || month ==2)
{
season = "Winter";
}
else if (month == 3 || month == 4 || month ==5)
{
season = "Spring";
}
else if (month == 6 || month == 7 || month ==8)
{
season = "Summer";
}
else if (month == 9 || month == 10 || month ==11)
{
season = "Autumn";
}
else
{

season = "Invalid month ";


}
System.out.println("Arpil is in " + season + ".");
}
}
3.1.2 Switch statement
When a variable value has to be compared with multiple values, we require
nested if statements.
The readability of the nested if statement is poor and hence understanding of
the logic becomes difficult. In such cases, switch statement can be used.
switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
case value 3 :
statement 3 ; break;
default
:
statement 4 ; break;
}

The test variable or expression to be tested can be any of the primitive types
byte, char, short, or int.
This value is compared with each case values. If a match is found, the
corresponding statement or statements are executed.
If no match is found, statement or statements in the default case are executed.
Default statement is optional.
If default statement is absent, then if no matches are found, then the switch
statement completes without doing anything.

/* An example that shows the usage of switch..case */


class switchuse
{
public static void main(String args[])
{
int weekday=3;
switch(weekday)
{
case 1: System.out.println("Sunday") ;
break;
case 2: System.out.println("Monday") ;
break;

case 3: System.out.println("Tuesday") ;
break;
case 4: System.out.println("Wednesday") ;
break;
case 5: System.out.println("Thursday") ;
break;
case 6: System.out.println("Friday") ;
break;
case 7: System.out.println("Saturday") ;
break;
default: System.out.println("Not a valid day ");
break;
}
}
}
3.2 Looping statements
For loop
While loop
Do- while loop
3.2.1 For loop
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
below.
Syntax
for (initialization; test; expression)
{
Set of statements;
}

In the first part a variable is initialized to a value.


The second part consists of a test condition that returns only a Boolean value.
The last part is an expression, evaluated every time the loop is executed.
The following example depicts the usage of the for loop.

/* An example of for loop */


class for1
{
public static void main(String args[])
{
int i;
9

for (i=0;i<10;i++)
{
System.out.println("\nExample of for loop ");
}
}
}
3.2.2 The while loop
The while loop executes a set of code repeatedly until the condition returns
false.
The syntax for the while loop is given below:
Syntax
while (<condition>)
{
<body of the loop>
}

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 executed.

/* An example of while loop */


class while1
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println("\n" + i);
i++;
}
}
}
3.2.3 The dowhile loop

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:

Syntax
do{
<body of the loop>
} while (<condition>);
/* This is an example of do ... while loop */
class dowhile1

10

{
public static void main(String args[])
{
int i = 1;
int sum = 0;
do
{
sum = sum + i;
i++;
}while (i<=100);
System.out.println("\n\n\tThe sum of 1 to 100 is .. " + sum);
}
}
3.3 Other statements
Break
Continue
3.3.1 The break statement
This statement is used to jump out of a loop.
Break statement was previously used in switch case statements.
On encountering a break statement within a loop, the execution continues with
the next statement outside the loop.
The remaining statements which are after the break and within the loop are
skipped.
Break statement can also be used with the label of a statement.
A statement can be labeled as follows.
statementName : SomeJavaStatement

When we use break statement along with label as


break statementName;

The execution continues with the statement having the label. This is equivalent
to a goto statement.

/* An example of break statement */


class break1
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{

11

System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}
/* An example of break to a label */
class break3
{
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");
}
}
}
3.3.2 Continue statement
This statement is used only within looping statements.
When the continue statement is encountered, the next iteration starts.
The remaining statements in the loop are skipped. The execution starts from
the top of loop again.
The program below shows the use of continue statement.
/* This is an example of continue */
class continue1
{
public static void main(String args[])
{
for (int i=0; i<10; i++)
{
if (i%2 == 0)
continue;

12

System.out.println("\n" + i);
System.out.println(" ");
}
}
}

4. Explain Data Types of Java ? [March/April -2009]

Java provides several data types that are commonly supported on all platforms.
For example,
the int (integer) data type in Java is represented as 4-bytes in the memory on
all machines, irrespective of where the Java programs run.
Hence, Java programs need not to be modified to run on different platforms.

In Java, data types fall under two categories:


Primitive data types
Reference data types
4.1 Primitive Data Types
Java provides eight primitive data types.
Data
Type

Range

Explanation

Byte

Size
in
bits
8

-128 to 127

Char

16

All characters

Boolean

True or false

Short

16

-32768 to 32767

Int

32

-2,147,483,648 to
+2,2,147,483,647

Long

64

-9,223,372,036,854,775,808 to
+9,223,372,036,856,775,807

Float

32

Double

64

-3.40292347E+38 to
+3.40292347E+38
-1.79769313486231570
E+308
+1.79769313486231570
E+308

The byte data type is typically used to


store small amount of data in bytes. It
is mostly used while handling text
files.
The char data type is used to store
names or character data.
The Boolean dats type is used to store
a true or a false value.
The short data type is used to store
smaller numbers upto 32767.
The int data type is used to store the
large number upto 2,147,483,648.
The long data type is used to store
very
large
numbers
upto
9,223,372,036,854,775,808
The float data type is used to store
decimal upto 3.40292347E+38.
The double data type is used to store
the large number values with decimal
upto 1.79769313486231570E+308.

4.2 Composite Data Types


Java has three reference data types

13

Data Type
Array
Class
Interface

Description
A collection of several items of the same data type. For example names
of student.
A collection of variables and methods.
An abstract class created to implement multiple inheritance in JAVA.

Arrays can be declared in three ways:


Way
Only
Declaration
Declaration
creation

Declaration,
creation
initialization

Description
Syntax
Just declares the Datatype
array.
identifier[]
and Declares
and
allocates memory
for
the
array
elements using the
reserved
word
new.
Declares the array,
and allocates memory
for it and assigns
initial values to its
elements.

Example
Char ch[ ]; declares
a character array
named ch.
Datatype
Char ch[] = new
identifier[] =new char[10]; declares
datatype[size];
an array ch to store
10 characters.

Datatype
identifier[]
=
{value1,
value2,
.ValueN};

/* An example of array outside main function */


class array3
{
int i;
int da[]={1,2,3,4,5,6,7};
void disp()
{
System.out.println("\n\nDisplaying Array Details .. ");
for(i=0;i<7;i++)
{
System.out.println("\n " + da[i]);
}
}
public static void main(String args[])
{
array3 d = new array3();
d.disp();
}
}

14

Char
ch[]
={A,B,C,D};
declares an array ch
to store 4 pre-as
signed
character
values.

Explain Types of Operators Available in Java ?


Operators are special symbols used in expressions.
They include arithmetic operators, assignment operators, increment and
decrement operators, logical operators, bitwise operators and comparison
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:
Operator
+
*
/
%

Meaning
Addition
Subtraction
Multiplication
Division
Modulus

Example
8 + 10
10 8
20 * 84
10 / 5
10 % 6

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 any one 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.

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=xy
X *= y
X=x*y
X /= y
X=x/y
X=y
X=y
Incrementing and Decrementing
To increment or decrement a value by one, the ++ operator and -- operator are
used respectively. The increment and the decrement operators can be prefixed
or postfixed. The different increment and decrement operators can be used as
given below:
++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.

15

b--(Post decrement operator): Use the current value of b in the expression in


which b resides and then increment b by 1.

Comparison Operators
There are several expressions for testing equality and magnitude.
All these expressions return a boolean value.
Table lists the comparison operators.
Operator
==
!=
<
>
<=
>=

Meaning
Equal
Not equal
Less than
Greater than
Less than or equal to
Greater than or equal to

Example
U == 45
U != 75
U < 85
U > 68
U<= 53
U >= 64

Logical Operators
Logical operators available are AND, OR and NOT.

The AND operator (& or &&) returns true only if both sides in an expression
are true. If any one side fails, the operator returns false.

For example, consider the following statement

marks >= 40 && age >=65

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 the all the conditions are false, the expression is false. Consider the
following statement
semesterAverage >= 90 | | finalExam >= 90

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 ! operator is used for NOT.


The value of NOT is negation of the expression.

16

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
Operator
&
|
^
<<
>>
>>>>
~
<<=
>>=
>>>=
X &=y
X |= y
X ^= y

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
AND assignment
OR assignment
XOR assignment

Conditional Operator (ternary operator)


The conditional operator is also known as the ternary operator and is
considered to be an alternative to the ifelse construct.
It returns a value and the syntax is:
Syntax
<condition> ? <true statement> : <false statement>

where, <condition> is the condition to be tested. If the condition returns true


then the statement given in <true> will be executed.
Otherwise, the statement given in <false> will be executed.

17

CHAPTER 2
CLASS FUNDAS
WHAT CLASS / STATIC VARIABLE ?
Class variables apply to a class as a whole.
It is necessary to store the same information for every object.
They are useful for keeping track of classwide information among a
group of objects.
All instances of the class have access to the same copy.
The static keyword is used to declare a class static variable.
Class MyPoint {
int x;
int y;
Static int quadrant=1;
// method 1
// method 2
}
In the above example x and y are instance variable whereas quadrant is a class /
static variable.
public class MyPoint
{
int x = 0;
int y = 0;
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}
public static void main(String args[])
{
MyPoint obj; // declaration
obj = new MyPoint(); // allocation of memory to an object
obj.displayPoint(); // calling a member function
}
}

18

// Example of static variable .


class Static1
{
int a;
int b;
static int c;
Static1()
{
a = 1;
b = 2;
}
void display()
{
c++;
System.out.println("\n\n a " + a + "\tb " + b + "\tc " + c);
}
public static void main(String args[])
{
Static1 obj1 = new Static1();
Static1 obj2 = new Static1();
Static1 obj3 = new Static1();
obj1.display();
obj2.display();
obj3.display();
}
}

HOW TO DEFINE METHOD ?


Methods are defined as follows
Return type
Name of the method
A list of parameters
Body of the method.
void displayPoint()
{
// body of the method
}
In the above example return type is void.
It means the method does not return any value.
Name of the method is displayPoint.

19

The parameters for this method are nil.


If the return type is not void then the return keyword has to be used
within the body of the method to return the value.
The name of the method and the list of parameters are called as the
signature of the method.
Return type of the method is not part of the methods signature.
A variable declared can be used only within the block it has been
declared.
It has a limited scope within which it can be used.

If the variable is not a local variable, that is if it is not defined within


the current method then java checks for the definition of that variable as
an instance or class variable in the current class.

If the definition is not found still then it is checked in each superclass in


turn.
Consider the case when same variable name is used for both local
variable and instance variable/class variable.
When the values are printed, the values of local variables are printed.
The declaration of local variable hides the value of instance or class
variables.
However the values of instance or class variables can be accessed by
using the keyword this along with the variable name.
The example below shows the use of this keyword
// An example of this.
class This1
{
int x = 10;
int y = 20;
void display()
{
int x = 5;
int y = 6;
System.out.println("\n\n\n\t--Printing Local variables -- ");
System.out.println("\n\t\t" + x + "\t" + y);

20

System.out.println("\n\n\n\t--Printing Instance variables -- ");


System.out.println("\n\t\t" + this.x + "\t" + this.y);
}
public static void main(String args[])
{
This1 obj = new This1();
obj.display();
}
}
Parameter-list: It is a sequence of type & identifiers pairs separated by
commas.
Parameters are variables that receive the value of the argument passed to
the method when it is called.
If the method has no parameters, then the parameter list will be empty.
Method that has a return type other than void, returns a value to the
calling routine using the following form of the return statement;
return value;

3. what is constructors ? explain with an example ? [ Nov / Dec 2008] ,


[March/April -2009]

Every time when we create an object, we have to initialize all the


variables of a class.
Java allows objects to initialize themselves when they are created.
This automatic initialization is performed with the use of constructor.
A constructor allows objects to initialize themselves as soon as they are
created.
A constructor is automatically called when an object is created. It has
the same name as the class in which it resides and is syntactically similar
to a method.

Constructors do not have return type not even void. The general form of
declaring a constructor is:

Constructor_name([arguments])
{
// body
}
Constructors are generally of two types.
21

1. Non-Parameterized
2. Parameterized
Non-Parameterized Constructor
// Non - parameterised constructor
class Point1
{
int x;
int y;
Point1()
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
public static void main(String args[])
{
Point1 p1 = new Point1();
p1.display();
}
}
Parameterized Constructor
// parameterised constructor
class Point2
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}

22

public static void main(String args[])


{
Point2 p1 = new Point2(10,20);
p1.display();
}
}

4. explain Method Overloading ? with Example ? [ Nov / Dec 2008] ,


[March/April -2009] , [Oct / Nov 2009]

A class can contain any number of methods. Methods can be with


parameter and without parameter.
The parameter in a method are called type signature.
It is possible in java to define two or more methods within the same
class that share the same name,
but with different parameter declarations (type signatures).
When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
Overloading methods demonstrate the concept of polymorphism.
When an overloaded method is invoked, java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to call.
Thus, overloaded methods must differ in the type and/or number of their
parameters.
Overloaded methods may have different return types.
When java encounters a call to an overloaded method, it simply executes
the version of the method whose parameters match the arguments used
in the call.
// An example of Method Overloading
class MethodOver
{
int n1;
int n2;
MethodOver()
{
n1 = 10;
n2 = 20;
}

23

void square()
{
System.out.println("\n\n\tThe Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("\n\n\tThe Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;
n2 = p2;
System.out.println("\n\n\tThe Square is " + n1 * n2);
}
public static void main(String args[])
{
MethodOver obj1 = new MethodOver();
obj1.square();
obj1.square(4);
obj1.square(7,8);
}
}

5. Exaplin Constructor Overloading ? With Example ?


[ Nov / Dec 2008]

Along with method overloading,


we can also overload constructors. Constructors having the same name
with different parameter list is called constructor overloading.
// constructor with object as parameter
class Point
{
int x;
int y;
Point(int a, int b)
{
x = a;
y = b;
}
}
class Circle
{
int originX;
int originY;

24

int radius;
//Default Constructor
Circle()
{
originX = 5;
originY = 5;
radius = 3;
}
// Constructor initializing the coordinates of origin and the radius.
Circle(int x1, int y1, int r)
{
originX = x1;
originY = y1;
radius = r;
}

Circle(Point p, int r)
{
originX = p.x;
originY = p.y;
radius = r;
}
void display()
{
System.out.println("\n\t--Center at " + originX + " and " + originY);
System.out.println("Radius = " + radius);
}
public static void main(String args[])
{
Circle c1 = new Circle();
Circle c2 = new Circle(10,20,5);
Circle c3 = new Circle(new Point(15,25),10);
c1.display();
c2.display();
c3.display();

25

}
}

6. How to Pass Objects as a Parameter to Method ?

We have seen that methods can take parameters as input and process
them.
It is also common to pass objects as a parameter to methods.

// An example of Passing Object as parameter to method


class PassObj
{
int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}
PassObj(int p1, int p2)
{
n1 = p1;
n2 = p2;
}
void multiply(PassObj p1)
{
int temp;
temp = p1.n1 * p1.n2;
System.out.println("\n\n\tMultiplication is " + temp);
}
public static void main(String args[])
{
PassObj obj1 = new PassObj(5,6);
PassObj obj2 = new PassObj();
obj2.multiply(obj1);
}
}

7. Explain Method overloading with object as a parameter ?


// An example of Method overloading with object as a parameter
class MetObjOv
{
int n1;
int n2;

26

// constructor
MetObjOv()
{
n1 = 0;
n2 = 0;
}
MetObjOv(int x, int y)
{
n1 = x;
n2 = y;
}
void multiply(MetObjOv p1)
{
n1 = p1.n1;
n2 = p1.n2;
System.out.println("\n\n\tThere is nothing to multiply ");
System.out.println("\tn1 = "+n1+"\tn2 = " +n2);
}
void multiply(MetObjOv p1, MetObjOv p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;
System.out.println("\n\n\tMultiplication of two objects ");
System.out.println("\tn1 = " + n1 + "\tn2 = " + n2 );
}
public static void main(String args[])
{
MetObjOv obj1 = new MetObjOv(5,6);
MetObjOv obj2 = new MetObjOv(6,5);
MetObjOv obj3 = new MetObjOv();
obj3.multiply(obj1);
obj3.multiply(obj1, obj2);
}
}

8. How to Return an Object ? Explain with an Example ?

A method can return any type of data, including class type (object) that
you create.

// An example of returning an object


class RetObj
{
int n1;

27

int n2;
// constructor
RetObj()
{
n1 = 0;
n2 = 0;
}
RetObj(int x, int y)
{
n1 = x;
n2 = y;
}
RetObj multiply(RetObj p1, RetObj p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;
return (this);
}
void display()
{
System.out.println("\n\n\tAn Example of returning an Object ");
System.out.println("\tn1 = "+n1+"\tn2 = " +n2);
}
public static void main(String args[])
{
RetObj obj1 = new RetObj(5,6);
RetObj obj2 = new RetObj(6,5);
RetObj obj3 = new RetObj();
obj3 = obj3.multiply(obj1, obj2);
obj3.display();
}
}

11. How to Pass Arguments in Java ? Call by value and Reference ?

Computer language can pass an argument to a subroutine in following


two ways:
[1] call-by-value [2] call-by-reference

[1] Call-by-Value

This method copies the value of an argument into the formal parameter
of the subroutine.

28

Therefore, changes made to the parameter of the subroutine have no


effect on the argument.
In java, when we pass a primitive type to a method, it is passed by value.
Thus, what occurs to the parameter that receives the argument has no
effect outside the method.
/* An example of call by value */
class CallVal
{
int a, b;
CallVal()
{
a = b = 0;
}
CallVal(int x, int y)
{
a = x;
b = y;
}
void Interchange(int Temp)
{
Temp = 100;
System.out.println("\n\n\tCall by Value ");
System.out.println("\n\n\tTemp = " + Temp);
}
void display()
{
System.out.println("\n\n\ta = " + a + "\tb = " + b);
}
public static void main(String args[])
{
CallVal obj1 = new CallVal(10,20);
int var = 11;
System.out.println("\n\n\tThe value of var is " + var);
obj1.Interchange(var);
System.out.println("\n\n\tThe value of var is " + var);
}
}

[2] Call-by-Reference

A reference to an argument (not value of argument) is passed to the


parameter.
Inside the subroutine, this reference is used to access the actual
argument specified in the call.

29

This means that changes made to the parameters will affect the argument
used to call the subroutine.
When we pass an object to a method, the situation changes, because
objects are passed by call-by-reference.
When we create a variable of a class type, we are only creating a
reference to an object. Thus,
when you pass this reference to a method, the parameter that receives it
will refer to the same object as that referred to by the argument.
This effectively means that objects are passed to method do affect the
object used as an argument.
/* An example of call by Reference*/
class CallRef
{
int a, b;
CallRef()
{
a = b = 0;
}
CallRef(int x, int y)
{
a = x;
b = y;
}
void Interchange(CallRef Temp)
{
Temp.a = 100;
Temp.b = 200;
System.out.println("\n\n\tCall by Reference ");
System.out.println("\n\n\tTemp.a = " + Temp.a);
System.out.println("\n\n\tTemp.b = " + Temp.b);
}
void display()
{
System.out.println("\n\n\ta = " + a);
System.out.println("\n\n\tb = " + b);
}
public static void main(String args[])
{
CallRef obj1 = new CallRef(10,20);
obj1.display();
obj1.Interchange(obj1);
obj1.display();
}
}

30

14. Exaplin Access Control ? [ Nov / Dec 2008] , [March/April -2009] ,


[Oct / Nov 2009]

One can control what parts of a program can access the member of a
class. By controlling access, one can prevent misuse.
For Example, allowing access to data only through a well-defined set of
methods, one can prevent misuse of that data. Thus,
when correctly implemented, a class creates black box.
How a member can be accessed is determined by the access specifier
that modifies its declaration.
Java provides a set to access specifiers. Some aspects of access control
are related to inheritance or packages.
Javas access specifiers are:
public:
o When a member of a class is specified by the public specifier, then
that member can be accessed by any other code.
o The public modifier makes a method or variable completely
available to all classes.
o Also when the class is defined as public, it can be accessed by any
other class.
private:
o To hide a method or variable from other classes, private modifier is
used.
o A private variable can be used by methods in its own class but not
by objects of any other class.
o Neither private variables nor private methods are inherited by
subclass.
o The only place these variables and methods can be seen is from
within their own class.
protected:
o protected applies only when inheritance is involved.
o If you want to allow an element to be seen outside your current
package, but only to classes that are inherited from your class
directly, then declare that element as protected.
default:
o We have seen that when no access control modifier is specified, it is
called as default access.
o Classes written like this are not accessible in other package.

31

o Any variable declared without a modifier can be read or changed by


any other class in the same package.
o Any method declared the same way can be called by any other class
in the same package.
o When a member does not have an explicit access specification,
o it is visible to subclasses as well as to other classes in the same
package.
The following table summarizes the levels of access control.
Access
From
the
same class
From
any
class in the
same package
From
any
class outside
the package
From a sub class in the
same package
From a sub class outside
the
same
package

Public
Yes

Protected
Yes

Default
Yes

Private
Yes

Yes

Yes

Yes

No

Yes

No

No

No

Yes

Yes

Yes

No

Yes

Yes

Yes

No

Exaplin static keyword ? [ Nov / Dec 2008]

A class member must be accessed with the use of an object of its class but
sometimes we want to define a class member that will be used
independently without creating any object of that class.
It is possible in java to create a member that can be used by itself, without
reference to a specific instance.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
one can declare both methods and variables to be static.
The most common example of a static member is main().
Main() is declared as static because it must be called before any object
exist.
Instance variables declared as static are actually, global variables.
When objects of its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static variable.
Method declared as static have several restrictions:

32

1.
2.
3.

Can call only other static methods.


Only access static data.
Can not refer to this or super in any way.

One can also declare a static block which gets executed exactly once,
when the class is first loaded.
/* An example of Static Variable */
class StaticDemo
{
static int x = 3;
static int y;
static void display(int z)
{
System.out.println("\n\n\tz = " + z);
System.out.println("\n\n\tx = " + x);
System.out.println("\n\n\ty = " + y);
}
static
{
System.out.println("\n\n\tStatic block initialized");
y = x*4;
}
public static void main(String args[])
{
display(42);
}
}

18. What is Nested / Inner Classes ?


It is possible to define a class within another class; such classes are
known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing
class.
That means, if class B is defined within class A, then B is known to A,
but not outside A.
If A is nesting class B, then A has access to all the members of B,
including private members. But the B does not have access to the
members of nested class.
There are two types of nested classes:
1. Static

33

2. Non Static
Static nested class
A static nested class is one which has the static modifier, as it is static it
must access the member of its enclosing class through an object.
That means it cannot refer to member of its enclosing class directly.
Non Static nested class
Non Static nested class is known as inner class.
It has access to all of its variables and methods of its outer class and can
refer to them directly.
An inner class is fully within the scope of its enclosing class.
/* An example of Inner class */
class Inner1
{
class Contents
{
private int i = 16;
public int value()
{
return i;
}
}
class Destination
{
private String label;
Destination(String whereTo)
{
label = whereTo;
}
}
public void ship(String dest)
{
Contents c = new Contents();
Destination d = new Destination(dest);
System.out.println("\n\n\tShipped " + c.value() + " item(s) to " +
dest);
}
public static void main(String args[])
{
Inner1 p = new Inner1();
p.ship("Congo");
}

34

CHAPTER 3
PACKAGES
1. Explain VECTOR CLASS with example ? [March/April -2009], [Oct / Nov
2009]

The Vector class is one of the most important in all of the Java class
libraries. We cannot expand the size of a static array.
We may think of a vector as a dynamic array that automatically
expands as more elements are added to it.
All vectors are created with some initial capacity.
When space is needed to accommodate more elements, the capacity is
automatically increased.
That is why vectors are commonly used in java programming.

This class provides the following constructors:


Vector()
Vector(int n)
Vector(int n, int delta)

The first form creates a vector with an initial capacity of ten elements.
The second form creates a vector with an initial capacity of n elements.
The third form creates a vector with an initial capacity of n elements
that increases by delta elements each time it needs to expand.

Example 1
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
int i;
Vector v = new Vector();
v.addElement(new Integer(10));
v.addElement(new Float(5.5f));
v.addElement(new String("Hi"));
v.addElement(new Long(2500));
v.addElement(new Double(23.25));
35

System.out.println(v);
String s = new String("Bhagirath");
v.insertElementAt(s,1);
System.out.println(v);
v.removeElementAt(2);
System.out.println(v);
for(i=0;i<5;i++)
{
System.out.println(v.elementAt(i));
}
}

}
2. Explain Random class with an example ? [March/April -2009]
The Random class allows you to generate random double, float, int, or
long numbers.
This can be very helpful if you are building a simulation of a realworld system.
This class provides the following constructors.
Random()
Random(long start)
Here, start is a value to initialize the random number generator.
Method
Double nextDouble()
Float nextFloat()
Double nextGaussian()

Int nextInt()
Long nextLong()

Description
Returns a random double value.
Returns a random float value.
Returns a random double value.
Numbers obtained from repeated
calls to this method have a Gaussian
distribution with a mean of 0 and a
standard deviation of 1.
Returns a random int value.
Returns a random long value.

Example 2
import java.util.*;
class RandomDemo
{
public static void main(String args[])
{
Random ran = new Random();
for(int i = 0; i<5;i++)
{
System.out.println(ran.nextInt());

36

}
}
}
3. Explain Date class an example ? [March/April -2009]
The Date classes encapsulate information about a specific date
and time.
It provides the following constructors.
Date()
Date(long msec)

Here, the first form returns an object that represent the current date
and time.
The second form returns an object that represents the date and time
msec in milliseconds after the time.
The time is defined as midnight on January 1,1970 GMT (Greenwich
Mean Time).

Method
Boolean after(Date d)
Boolean before(Date d)
Boolean equals(Date d)

Long getTime()
Void setTime
(long msec)
String toString()

Description
Returns true if d is after the current
date. Otherwise, returns false.
Returns true if d is before the current
date. Otherwise, returns false.
Returns true if d has the same value
as the current date. Otherwise,
returns false.
Returns the number of milliseconds
since the epoch.
Sets the date and time of the current
object to represent msec milliseconds
since the epoch.
Returns the string equivalent of the
date.

Example
import java.util.*;
class DateDemo
{
public static void main(String args[])
{
Date dt = new Date();
System.out.println(dt);
Date epoch = new Date(0);
System.out.println(epoch);
}

37

Example
import java.util.Date;
public class date2
{
public static void main(String[] args)
{
Date d1 = new Date();
try
{
Thread.sleep(1000);
}
catch(Exception e){}
Date d2 = new Date();

System.out.println("First Date : " + d1);


System.out.println("Second Date : " + d2);
System.out.println("Is second date after first ? : " + d2.after(d1));
}
}
Example
import java.util.*;
public class date3{
public static void main(String args[]){
Date date = new Date();
System.out.println("Date is : " + date);
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " +
date.getTime());
Date epoch = new Date(0);
date.setTime(10000);
System.out.println("Time after 10 second " + epoch);
System.out.println("Time after 10 second " + date);

38

String st = date.toString();
System.out.println(st);
}
}
4. Explain Calendar and Gregorian class with an example ? [March/April 2009]
The Calendar class allows you to interpret date and time information.
This class defines several integer constants that are used when you get
or set components of the calendar. These are listed here:
AM
AUGUST
DAY_OF_WEEK
DECEMBER
FEBRUARY
HOUR
JULY
MAY
MONDAY
OCTOBER
SECOND
THURSDAY
WEDNESDAY
YEAR

AM_PM
DATE
DAY_OF_WEEK_IN_MONTH
DST_OFFSET
FIELD_COUNT
HOUR_OF_DAY
JUNE
MILLISECOND
MONTH
PM
SEPTEMBER
TUESDAY
WEEK_OF_MONTH
ZONE_OFFSET

APRIL
DAY_OF_MONTH
DAY_OF_YEAR
ERA
FRIDAY
JANUARY
MARCH
MINUTE
NOVEMBER
SATURADAY
SUNDAY
UNDERIMBER
WEEK_OF_YEAR

The Calendar class does not have public constructors. Instead, you may
use the static getInstance() method to obtain a calendar initialized to
the current date and time.

One of its forms is shown here:


Calendar getInstance()
Example
import java.util.Calendar;
public class Cal1 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println("DATE is : " + cal.get(cal.DATE));
System.out.println("YEAR is : " + cal.get(cal.YEAR));
System.out.println("MONTH is : " + cal.get(cal.MONTH));

39

System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK));


System.out.println("WEEK
OF
MONTH
is
:
"
+
cal.get(cal.WEEK_OF_MONTH));
System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR));
System.out.println("DAY
OF
MONTH
is
:
"
+
cal.get(cal.DAY_OF_MONTH));
System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR));
System.out.println("HOUR is : " + cal.get(cal.HOUR));
System.out.println("MINUTE is : " + cal.get(cal.MINUTE));
System.out.println("SECOND is : " + cal.get(cal.SECOND));
System.out.println("DAY OF WEEK IN MONTH is : " +
cal.get(cal.DAY_OF_WEEK_IN_MONTH));
System.out.println("Era is : " + cal.get(cal.ERA));
System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY));
System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND));
System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM
and 1 if PM
}
}

The GregorianCalendar class is a subclass of Calendar.


It provides the logic to manage date and time information according to
the rules of the Gregorian calendar.
This class provides following constructors:
GregorianCalendar()
GregorianCalendar(int year, int month, int date)
GregorianCalendar(int year, int month, int date, int hour, int minute,
int sec)
GregorianCalendar(int year, int month, int date, int hour, int minute)

The first form creates an object initialized with the current date and
time.
The other forms allow you to specify how various date and time
components are initialized.
The class provides all of the method defined by Calendar and also adds
the isLeapYear() method shown here:
Boolean isLeapYear()

This method returns true if the current year is a leap year. Otherwise, it
returns false.

Example
import java.util.*;

40

public class gcal1 {


public static void main(String[] args) {
GregorianCalendar c1 = new GregorianCalendar() ;
System.out.println("DATE is : " + c1.get(c1.DATE));
System.out.println("YEAR is : " + c1.get(c1.YEAR));
System.out.println("MONTH is : " + c1.get(c1.MONTH));
System.out.println("DAY OF WEEK is : " + c1.get(c1.DAY_OF_WEEK));
System.out.println("WEEK
OF
MONTH
is
:
"
+
c1.get(c1.WEEK_OF_MONTH));
System.out.println("DAY OF YEAR is : " + c1.get(c1.DAY_OF_YEAR));
System.out.println("DAY
OF
MONTH
is
:
"
+
c1.get(c1.DAY_OF_MONTH));
System.out.println("WEEK OF YEAR is : " + c1.get(c1.WEEK_OF_YEAR));
System.out.println("HOUR is : " + c1.get(c1.HOUR));
System.out.println("MINUTE is : " + c1.get(c1.MINUTE));
System.out.println("SECOND is : " + c1.get(c1.SECOND));
System.out.println("DAY OF WEEK IN MONTH is : " +
c1.get(c1.DAY_OF_WEEK_IN_MONTH));
System.out.println("Era is : " + c1.get(c1.ERA));
System.out.println("HOUR OF DAY is : " + c1.get(c1.HOUR_OF_DAY));
System.out.println("MILLISECOND : " + c1.get(c1.MILLISECOND));
System.out.println("AM_PM : " + c1.get(c1.AM_PM));// Returns 0 if AM
and 1 if PM */
}
}
5. Explain Math Class with an example ? [March/April -2009] , [Oct / Nov
2009]

For scientific and engineering calculations, a variety of mathematical


functions are required.
Java provides these functions in the Math class available in java.lang
package.
The methods defined in Math class are given following:

Method
Double sin(double x)
Double cos(double x)
Double tan(double x)
Double asin(double x)

Description
Returns the sine value of angle x in
radians.
Returns the cosine value of the angle
x in radians
Returns the tangent value of the
angle x in radians
Returns angle value in radians for

41

Double acos(double x)
Double atan(double x)
Double exp(double x)
Double log(double x)
Double pow(double x, double y)
Double sqrt(double x)
Int abs(double n)
Double ceil(double x)
Double floor(double x)
Int max(itn n, int m)
Int min(int n, int m)
Double rint(double x)
Int round(float x)
Long round(double x)
Double random()
Double toRandians(double angle)
Double toDegrees(double angle)

arcsin of x
Returns angle value in radians for
arcos of x
Returns angle value in radians for
arctangent of x
Returns exponential value of x
Returns the natural logarithm of x
Returns x to the power of y
Returns the square root of x
Returns absolute value of n
Returns the smallest wholoe number
greater than or equal to x
Returns the largest whole number
less than or equal to x
Returns the maximum of n and m
Returns the minimum of n and m
Returns the rounded whole number
of x
Returns the rounded int value of x
Returns the rounded int value of x
Returns a random value between 0
and 1.0
Converts the angle in degrees to
radians
Converts the angle in radians to
degrees

6. Explain Wrapper Class with an example ?


[March/April -2009] , [Oct / Nov 2009]

[ Nov / Dec 2008] ,

Java uses primitive types, such as int, char, double to hold the basic
data types supported by the language.
Sometimes it is required to create an object representation of these
primitive types.
These are collection classes that deal only with such objects. One needs
to wrap the primitive type in a class.
To satisfy this need, java provides classes that correspond to each of the
primitive types. Basically, these classes encapsulate, or wrap, the
primitive types within a class.
Thus, they are commonly referred to as type wrapper. Type wrapper
are classes that encapsulate a primitive type within an object.
The wrapper types are Byte, Short, Integer, Long, Character, Boolean,
Double, Float.

42

These classes offer a wide array of methods that allow to fully integrate
the primitive types into Javas object hierarchy.

Byte
The Byte class encapsulates a byte value. It defines the constants
MAX_VALUE and MIN_VALUE and provides these constructors:
Byte(byte b)
Byte(String str)
Here, b is a byte value and str is the string equivalent of a byte value.

Example
import java.util.*;
class Byte1
{
public static void main(String args[])
{
Byte b1 = new Byte((byte)120);
for(int i = 125; i<=135; i++)
{
Byte b2 = new Byte((byte)i);
System.out.println("b2 = " + b2);
}
System.out.println("b1 Object = " + b1);
System.out.println("Minimum Value of Byte = " + Byte.MIN_VALUE);
System.out.println("Maximum Value of Byte = " + Byte.MAX_VALUE);
System.out.println("b1* 2 = " + b1*2);
System.out.println("b1* 2 = " + b1.byteValue()*2);
Byte b3 = new Byte("120");
System.out.println("b3 Object = " + b3);
System.out.println("(b1==b3)? " + b1.equals(b3));
System.out.println("(b1.compareTo(b3)? " + b1.compareTo(b3));
/*Returns 0 if equal. Returns -1 if b1 is less than b3 and 1 if b1 is
greater than 1*/
}
}
Short
The Short class encapsulates a short value. It defines the constants
MAX_VALUE and MIN_VALUE and provides the following constructors:
Short(short s)
Short(String str)
Example
import java.util.*;
class Short1
{
public static void main(String args[])

43

{
Short s1 = new Short((short)2345);
for(int i = 32765; i<=32775; i++)
{
Short s2 = new Short((short)i);
System.out.println("s2 = " + s2);
}
System.out.println("s1 Object = " + s1);
System.out.println("Minimum Value of Short = " + Short.MIN_VALUE);
System.out.println("Maximum Value of Short = " + Short.MAX_VALUE);
System.out.println("s1* 2 = " + s1.shortValue()*2);
Short s3 = new Short("2345");
System.out.println("s3 Object = " + s3);
System.out.println("(s1==s3)? " + s1.equals(s3));
Short s4 = Short.valueOf("10", 16);
System.out.println("s4 Object = " + s4);
}
}

Integer
The Integer class encapsulates an integer value. This class provides
following constructors:
Integer(int i)
Integer(String str)
Here, i is a simple int value and str is a String object.

Example
import java.util.*;
class int1
{
public static void main(String args[])
{
Integer i1 = new Integer(12);
System.out.println("I1 = " + i1);
System.out.println("Binary Equivalent = " + Integer.toBinaryString(i1));
System.out.println("Hexadecimal
Equivalent
=
"
+
Integer.toHexString(i1));
System.out.println("Minimum
Value
of
Integer
=
"
+
Integer.MIN_VALUE);
System.out.println("Maximum
Value
of
Integer
=
"
+
Integer.MAX_VALUE);
System.out.println("Byte Value of Integer = " + i1.byteValue());
System.out.println("Double Value of Integer = " + i1.doubleValue());
Integer i2 = new Integer(12);
System.out.println("i1==i2 " + i1.equals(i2));
System.out.println("i1.compareTo(i2) = " + i2.compareTo(i1));
// Compareto - if it is less than it returns -1 else 1, if equal it return 0.

44

Integer i3 = Integer.valueOf("11", 16);


System.out.println("i3 = " + i3);
}
}

Long
The Long class encapsulates a long value. It defines the constants
MAX_VALUE and MIN_VALUE and provides the following constructors:
Long(long l)
Long(String str)

Example
import java.util.*;
class longdemo
{
public static void main(String args[])
{
Long L1 = new Long(68764);
Long L2 = new Long("686748");
System.out.println("Object L1 = " + L1);
System.out.println("Object L2 = " + L2);
System.out.println("Minimum Value of Long = " +
Long.MIN_VALUE);
System.out.println("Maximum Value of Long = " +
Long.MAX_VALUE);
System.out.println("L1 * 2 = " + L1 * 2);
System.out.println("L1.longValue() * 2 = " + L1.longValue() * 2);
System.out.println("L1.compareTo(l2) = " + L1.compareTo(L2));
System.out.println("L1==L2 ? = " + L1.equals(L2));
Long L3 = Long.valueOf("10", 16);
System.out.println("Object L3 = " + L3);
System.out.println("Byte value of Long = " + L1.byteValue());
System.out.println("int value of Long = " + L1.intValue());
System.out.println("Double
value
of
Long
=
"
+
L1.doubleValue());
int i = 12;
System.out.println("Binary equivalent of decimal " + i + "=" +
Long.toBinaryString(i));
System.out.println("Hexadecimal equivalent of decimal " + i +
"=" + Long.toHexString(i));
}
}

Double
The Double class encapsulates a double value. It defines several constants.

45

The largest and smallest values are saved in MAX_VALUE and


MIN_VALUE.
The constant NaN (Not a Number) indicates that a value is not a number.
If you divide a double number by zero, the result is NaN. This class
defines these constructors:
Double(double d)
Double(String str)

Here, d is a double value to be encapsulated in a Double object. In the


last form, str is the string representation of a double value.

Example
import java.util.*;
class double1
{
public static void main(String args[])
{
Double d1 = new Double(687642365.4563);
Double d2 = new Double("686748");
System.out.println("Object d1 = " + d1);
System.out.println("Object d2 = " + d2);
System.out.println("Minimum Value of Double = " +
Double.MIN_VALUE);
System.out.println("Maximum Value of Double = " +
Double.MAX_VALUE);
System.out.println("Byte value of Double = " + d1.byteValue());
System.out.println("int value of Double = " + d1.intValue());
System.out.println("Float value of Double = " + d1.floatValue());
Double d3 = Double.parseDoduble("765.89");
System.out.println("Double
value
from
the
string
\"765.89\"="+d3);
}
}

Float
The float class encapsulates a float value. It defines several constants:
the largest and smallest values are stored in MAX_VALUE and
MIN_VALUE.
The constant NaN indicates that a value is not a number. If you divide a
floating point number by zero, the result is NaN.
This class defines these constructors:
Float(float f)
Float(double d)
Float(String str)

46

Here, f and d are float and double types to be encapsulated in a Float


object.
str is the string representation of a float value.

Example
import java.util.*;
class Float1
{
public static void main(String args[])
{
Float f1 = new Float(123.5626);
Float f2 = new Float(854.32f);
Float i = new Float(10);
System.out.println("Object f1 = " + f1);
System.out.println("Object f2 = " + f2);
System.out.println("Minimum Value of Float = " +
Float.MIN_VALUE);
System.out.println("Maximum Value of Float = " +
Float.MAX_VALUE);
System.out.println("Byte value of Float = " + f1.byteValue());
System.out.println("Short value of Float = " + f1.shortValue());
System.out.println("Integer value of Float = " + f1.intValue());
System.out.println("Double
value
of
Float
=
"
+
f1.doubleValue());
System.out.println("(f1==f2) ?= " + f1.equals(f2));
System.out.println("f1.compareTo(f2) = " + f1.compareTo(f2));
System.out.println("f1 is not a number = " + i.isNaN());
}
}

Character
The Character class encapsulates a char value. This class provides the
following constructor.
Character(char ch)

Here, c is a char value. charValue() method returns the char value that
is encapsulated by a Character object and has the following form:

char charValue()
Example
import java.util.*;

47

class char1
{
public static void main(String args[])
{
Character c1 = new Character('m');
char c2 = 'O';
System.out.println("Object C1 = " + c1);
System.out.println("char value of Character Object =
c1.charValue());
System.out.println(c2 + " is defined character set ?
Character.isDefined(c2));
System.out.println("c2 is digit = " + Character.isDigit(c2));
System.out.println("c2 is lowercase character =
Character.isLowerCase(c2));
System.out.println("c2 is uppercase character =
Character.isUpperCase(c2));

" +
" +

"

"

}
}

Boolean
The Boolean class encapsulates a Boolean value. It defines FALSE and
TRUE constants.
This class provides following constructors:
Boolean(Boolean b)
Boolean(String str)

Here, b is a Boolean value and str is the string equivalent of a Boolean


value.

The methods associated with Boolean Class are as follows:


1. Boolean booleanValue()
2. Boolean equals(Boolean b)
3. String toString(Boolean b)

Example
import java.util.*;
class boolean1
{
public static void main(String args[])
{
Boolean b1 = new Boolean(true);

48

Boolean b2 = new Boolean(false);


System.out.println("Object B1 = " + b1);
System.out.println("Object B2 = " + b2);
Boolean b3 = new Boolean("true");
Boolean b4 = new Boolean("false");
System.out.println("Object B3 = " + b3);
System.out.println("Object B4 = " + b4);
System.out.println("Boolean Value = " + b1.booleanValue());
System.out.println("(b1==b2)? " + b1.equals(b2));
String S1 = b1.toString();
System.out.println("String S1 " + S1);
}
}

Tips
o Constants defined in Java are called literals.
o Characters defined in Java are called Unicode characters.

7. What is an Enumeration Interface ? Example with an example ?


The Enumeration interface defines the methods by which you can
enumerate the elements in a collection of objects.
It is used by several methods defined by the legacy classes (such as Vector
and Properties),
is also used by several other API classes, and is currently in widespread
use in application code. Enumeration specifies the following two methods.
Boolean hasMoreElements( )
Object nextElement()

When implemented, hasMoreElements( ) must return true while there are


still more elements to extract,
and false when all the elements have been extracted. nextElement() returns
the next object from the enumeration. That is,
each call to nextElement( ) obtains the next element from the enumeration.

Example
import java.util.*;
class Enum1
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(10));
v.addElement(new Integer(11));

49

v.addElement(new Integer(12));
v.addElement(new Integer(13));
Enumeration e = v.elements();
while (e.hasMoreElements())
{
System.out.print(e.nextElement() + " ");
}
}
}
8. 9. What is Hashtable ? Explain with an Example ?
Hashtable is a part of the java.util library and is a concrete implementation
of a dictionary.
(Dictionary is a class that represents a key/value storage repository.
Given a key and value, you can store the value in a Dictionary object.
Once the value is stored, you can retrieve it by using its key.)

Hashtable stores key/value pairs in a hash table.

When using a Hashtable, you specify an object that is used as a key, and
the value that you want to link to that key.

The key is then hashed, and the resulting hash code is used as the index at
which the value is stored within the table.

The Hashtable constructors are shown here:


Hashtable()
Hashtable(int size)

The first constructor is the default constructor.


The second constructor creates a hash table that has an initial size
specified by size.
The methods available with Hashtable are

Method
Void clear()
Boolean containsKey(Object key)

Boolean containsValue(Object value)

Enumeration elements( )

Description
Resets and empties the hash table.
Returns true if some key equals to
key exists within the hash table.
Returns false if the key isnt found.
Returns true if some value equal to
value exists within the hash table.
Returns false if the value isnt found.
Returns an enumeration of the values
contained in the hash table.

50

Object get(Object key)

Boolean isEmpty( )

Enumeration keys( )
Object put(Object key Object value)
Object remove(Object key)

Int size( )
String toString( )

Returns the object that contains the


value associated with key. If key is
not in the hash table, a null object is
returned.
Returns true if the hash table is
empty; Returns false if it contains at
least one key.
Returns an enumeration of the keys
contained in the hash table.
Inserts a key and a value into the
hash table.
Removes key and its value. Returns
the value associated with key. If key
is not in the hash table, a null object is
returned.
Returns the number of entries in the
hash table.
Returns the string equivalent of a
hash table.

Example
import java.util.*;
class hash1
{
public static void main(String args[])
{
Hashtable marks = new Hashtable();
Enumeration names;
Enumeration emarks;
String str;
int nm;
// Checks wheather the hashtable is empty
System.out.println("Is Hashtable empty " + marks.isEmpty());
marks.put("Ram", 58);
marks.put("Laxman", 88);
marks.put("Bharat", 69);
marks.put("Krishna", 99);
marks.put("Janki", 54);
System.out.println("Is Hashtable empty " + marks.isEmpty());
// Creates enumeration of keys
names = marks.keys();
while(names.hasMoreElements())
{

51

str = (String) names.nextElement();


System.out.println(str + ": " +
marks.get(str));
}
/*
nm = (Integer) marks.get("Janki");
marks.put("Janki", nm+15);
System.out.println("Janki's
new
marks.get("Janki"));

marks:

"

// Creates enumeration of values


emarks = marks.elements();
while(emarks.hasMoreElements())
{
nm = (Integer) emarks.nextElement();
System.out.println(nm);
}
// Number of entries in a hashtable
System.out.println("The number of entries in a table are " +
marks.size());
// Checking wheather the element available
System.out.println("The
element
is
marks.containsValue(88));
*/
// Removing an element from hashtable

their

"

System.out.println("========");
marks.remove("Bharat");
names = marks.keys();
while(names.hasMoreElements())
{
str = (String) names.nextElement();
System.out.println(str + ": " +
marks.get(str));
}
// Returning an String equivalent of the Hashtable
System.out.println("String " + marks.toString());
// Emptying hashtable
marks.clear();
System.out.println("Is Hashtable empty " + marks.isEmpty());
}
}

52

STRING HANDLING

In Java, a string is defined as a sequence of characters.


But, unlike many other languages that implement strings as character
arrays, java implements strings as objects of type String.
Java handles String by two classes StringBuffer and String. The String and
StringBuffer classes are defined in java.lang. Thus,
they are available to all programs automatically.

String Concatenation (+)


Example
import java.util.*;
class str3
{
public static void main(String args[])
{
String s1 = new String ("Pen");
String s2 = "Academy";
String s3 = s1+s2;
System.out.println("S1 = " + s1);
System.out.println("S2 = " + s2);
System.out.println("Concatenation Operator = " + s1+s2);
System.out.println("S3 = " + s3);
byte num [] = {65,66,67,68};
String s4 = new String(num);
System.out.println("S4 = " + s4);
}
}
3. Explain Character Extraction ?
The String class provides ways in which characters can be extracted from a
String object.
Method
char charAt(int indexnum)

Description
charAt() function is used to extract a single
character from a String. indexnum is the index
number of the character that we want to
extract.
void
getChars(int Used to extract more than one character at a
sourceStart, int sourceEnd, time, sourceStart specifies beginning of the
char target[], int targetStart) string, and sourceEnd specifies end of the
string. The array that will receive the characters

53

Byte[ ] getBytes( )

Char[ ] toCharArray( )

is specified by target. The index within target at


which the substring will be copied.
This is an alternative to getChars( ) that stores
the characters in an array of bytes. It uses the
default character-to-byte conversions provided
by the platform.
Same as getChars

4. Explain String Comparison ?


The String class provides several methods that compare strings or
substrings within strings.
equals( ) used to compare two strings
General form:
Boolean equals(Object str)

Here, str is a String object.


It returns true if the strings contain the same character otherwise it returns
false.
The comparison is case-sensitive.

equalsIgnoreCase( ) Same as equals but this ignores case.

General form:
Boolean equalsIgnoreCase(String str)
o Here, str is the String object.
o It returns true if the strings contain the same character otherwise
it returns false.
o This is case in sensitive.

regionMatches( )
o This method compares a specific region inside a string with
another specific region in another string.
o There is an overloaded form that allows you to ignore case in
such comparisons.

General form:

Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int


numChars)

Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int


str2StartIndex, int numChars)

startsWith( ) and endsWith()

54

The startsWith( ) method determines whether a given String begins with a


specified string.
endsWith( ) determines whether the String ends with a specified string.
General Form
Boolean startsWith(String str)
Boolean endsWith(String str)

equals( ) Versus = =
o Equals( ) method and the = = operator perform two different
operations. The equals ( ) method compares the characters
inside a String object. The = = operator compares two object
references to see whether they refer to the same instance.

compareTo( )
o It is not enough to know that two strings just for equal or not.
For sorting applications,
o we need to know which is less than, equal to, or greater than the
other string.
o The String method compareTo( ) serves this purpose.

General Form:
int compareTo(String str)

6. Explain Modifying a string ?


If we want to modify a String, we must either copy it into a StringBufer or
we can use following String methods:
Method
String substring(int n)
String substring(int n, int m)
S1.concat(s2)
String replace(char
char replacement)
String trim( )

Description
Gives substring starting from nth character.
Gives substring starting from nth char up to
mth
Concatenates s1 and s2
original, The
replace()
method
replaces
all
occurrences of one character in the invoking
string with another character.
Remove white space at the beginning and
end of the string.

7. valueOf()
The valueOf() method converts data from internal format into a humanreadable form. It has several forms:
String valueOf(double num)

55

String valueOf(long num)


String valueOf(Object ob)
String valueOf(char chars[ ] )
String valueOf(char chars[], int startIndex, int numChars)
8. String Methods
Method Call
S2=s1.toLowerCase;
S2=s1.toUpperCase;
S2=s1.replace(x,y)
S2=s1.trim()
S1.equals(s2)
S1.equalsIgnoreCase(s2)
S1.length()
S1.CharAt(n)
S1.compareTo(s2)
S1.concat(s2)
S1.substring(n)
S1.substring(n, m)
String.valueOf(p)
toString()
S1.indexOf(x)
S1.indexOf(x, n)
String.ValueOf(variable)

Description
Converts the string s1 to lowercase
Converts the string s1 to uppercase
Replace all appearances of x with y.
Remove white spaces at the
beginning and of the string s1
Returns true if s1 and s2 are equal
Returns true if s1=s2, ignoring the
case of characters
Gives the length of s1
Gives the nth character of s1
Returns ve if s1<s2 +ve.if s1>s2, and
0 if s1=s2
Concatenates s1 and s2
Gives substring starting from nth
character.
Gives substring starting from nth
char up to mth
Returns the string representation of
the specified type argument.
This object (which is already a
string!) is itself returned.
Gives the position of the first
occurrence of x in the string s1
Gives the position of x that occurs
after nth position in the string s1
Converts the parameter value of
string representation

Example
import java.util.*;
class str1
{
public static void main(String args[])
{
String s1 = "Bhagirath";
System.out.println("S1 = " + s1);
int length = s1.length();
System.out.println("S1 lenth = " + length);

56

System.out.println("S1 lowercase = " + s1.toLowerCase());


System.out.println("S1 uppercase = " + s1.toUpperCase());
System.out.println("S1 replace a with z = " + s1.replace('a','z'));
System.out.println("S1 indexOf('e')= " + s1.indexOf('e'));
System.out.println("S1 lastindexof('e') = " + s1.lastIndexOf('e'));
String s2 = "ViewSonic";
System.out.println("S2 = " + s2);
System.out.println("S1 and S2 trim = " + s1.trim() + s2.trim());
System.out.println("S1 and S2 equals = " + s1.equals(s2));
System.out.println("S1 and S2 equals ignoring case = " +
s1.equalsIgnoreCase(s2));
System.out.println("S1
and
S2
compareTo
=
"
+
s1.compareTo(s2));
System.out.println("S1 and S2 concate = " + s1.concat(s2));
System.out.println("S1 substring(n) = " + s1.substring(5));
System.out.println("S1 substring(n,m) = " + s1.substring(5,8));
System.out.println("S1 toString() = " + s1.toString());
int i = 100;
System.out.println("S1.valueOf(variable)
=
"
+
(s1.valueOf(i)).length()); // converts the parameter to string
System.out.println("Start with " + s1.startsWith("P"));
System.out.println("Start with " + s1.endsWith("y"));
}
}
Example
import java.util.*;
class str4
{
public static void main(String args[])
{
String s = "This is a dAmo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[10];
//System.out.println("Character at 10 = " + s.charAt(10));
s.getChars(start, end, buf,0);
System.out.println(buf);
s.getChars(start, end, buf,5);
System.out.println(buf);
byte bt [] = new byte[10];
s.getBytes(start, end, bt,0);
System.out.println(bt[0]);

57

System.out.println(bt[1]);
System.out.println(bt[2]);
System.out.println(bt[3]);
char buf1[] = s.toCharArray();
System.out.println(buf1);
}
}
Example
import java.util.*;
class str5
{
public static void main(String args[])
{
String s1 = "Rome was not built in a not day";
System.out.println("S1 = " + s1);
/*System.out.println("S1 = " + s1.indexOf('o'));
System.out.println("S1 = " + s1.indexOf("not"));
System.out.println("S1 = " + s1.indexOf('o',5));
System.out.println("S1 = " + s1.indexOf("not", 15));
System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o'));
System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not"));
System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o',15));
System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not",
15));
*/
String s2 = "Rome was not built in a Not day";
System.out.println("S2 = " + s2);
//System.out.println("S1 = " + s1.indexOf("not"));
//System.out.println("S1 = " + s1.lastIndexOf("not"));
System.out.println("Region Matches = ");
boolean b1 = s1.regionMatches(false,9,s2,24,3);
System.out.println("b1 = " + b1);

}
}
Example
import java.util.*;
class str6
{

58

public static void main(String args[])


{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

}
}

9. Explain StringBuffer class ? with an Example ?


StringBuffer is a peer class of String. String creates strings of fixed length,
while StringBuffer creates strings of flexible length that can be modified in
terms of both length and content.
So Strings that need modification are handled by StringBuffer class.
We can insert characters and substrings in the middle of a string, or
append another string to the end.
StringBufer defines these Constructor:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
Method Call
Sb.length()
Sb.capacity()
setLength(int len)
charAt(int where)
setCharAt(int where, char ch)
S1.append(s2)
S1.insert(n,s2)
S1.reverse()
S1.deleteCharAt(nth)
S1.delete(StartIndex, endIndex)

Task Performed
Gives the current length of a
StringBuffer.
Gives the total allocated capacity
(default 16)
Set the length of the buffer within a
String Buffer object.
Gives the value of character
Set the value of a character within a
StringBuffer.
Appends the string s2 to s1 at the end
Inserts the string s2 at the position n
of the string s1
Reverse the string of s1
Delete the nth character of string s1
Delete characters from start to end.

Example
import java.util.*;
class strbuf1
{

59

public static void main(String args[])


{
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer("Bhagirath");
StringBuffer s3 = new StringBuffer(s2);
StringBuffer s4 = new StringBuffer(100);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
System.out.println("s1.length = " + s1.length());
System.out.println("s2.length = " + s2.length());
System.out.println("s3.length = " + s3.length());
System.out.println("s4.length = " + s4.length());
System.out.println("s1.capacity = " + s1.capacity());
System.out.println("s2.capacity = " + s2.capacity());
System.out.println("s3.capacity = " + s3.capacity());
System.out.println("s4.capacity = " + s4.capacity());

}
}
Example
import java.util.*;
class strbuf1
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Bhagirath");
StringBuffer s2 = new StringBuffer("Hello");
System.out.println("s1 = " + s1);
//System.out.println("s1.charAt(5) = " + s1.charAt(5));
//s1.setCharAt(5,'z');
//System.out.println("s1 = " + s1);
//System.out.println("Inserting
String
=
"
+
s1.insert(5,s2));
//System.out.println("s1 = " + s1);
//System.out.println("Appending
String
=
"
+
s1.append(s2));
//System.out.println("s1 = " + s1);
//System.out.println("Reversing
String
=
"
+
s1.reverse());

60

//System.out.println("Deleting 5th character = " +


s1.deleteCharAt(5));
System.out.println("Deleting 5 to 8 character = " +
s1.delete(5,8));
}
}
Example
import java.util.*;
public class strbuf3
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("Hello world!");
System.out.println("s = " + s);
System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());
// Change the length of buffer to 5 characters:
s.setLength(5);
System.out.println(s);
System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());
}
}

61

What is a Inheritance ? [March/April -2009]


1. Concept
The derivation of one class from another class is called Inheritance.
A class that is inherited is called a superclass.
The class that does the inheriting is called as subclass.
A subclass inherits all instance variables and methods from its superclass
and also has its own variables and methods.
One can inherit the class using keyword extends.
General form
Class subclass-name extends superclass-name
{
// body of class.
}

In java, a class has only one super class.


Java does not support Multiple Inheritance.
One can create a hierarchy of inheritance in which a subclass becomes a
superclass of another subclass.
However, no class can be a superclass of itself.

Explain Member Access and Inheritance ? With an example ?


A subclass includes all the member of its superclass but it cannot access
those members of the superclass that have been declared as private.
Note: a class member that has been declared as private will remain private to its class
and will not accessible by any code outside its class, including subclasses.
Example
class A
{
int a,b;
void displayab()
{
System.out.println("a and b := " + a + " " + b);
}
}
class B extends A
{
int c;
void displayc()

62

{
System.out.println("c := " + c);
}
void sum()
{
System.out.println("a + b + c = " +(a+b+c));
}
}
class inhe1
{
public static void main(String args[])
{
A superob = new A();
B subob = new B();
superob.a=5;
superob.b=10;
System.out.println("Contents of superob : ");
superob.displayab();
System.out.println();
subob.a=15;
subob.b=20;
subob.c=15;
System.out.println("Contents of subob : ");
superob.displayab();
System.out.println();
subob.displayab();
subob.displayc();
System.out.println();
System.out.println("Sum of a,b and c in subob = ");
subob.sum();
}
}
Example
class A
{
int num1;
int num2;
void setVal(int no1, int no2)
{
num1 = no1;
num2 = no2;
}
}

63

class B extends A
{
int multi;
void mul()
{
multi = num1*num2;
}
}
class inhe2
{
public static void main(String args[])
{
B subob = new B();
subob.setVal(5,6);
subob.mul();
System.out.println("Multiplication is " + subob.multi);
}
}
Example
// This program uses inheritance to extend Box.
class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
// Here, Box is extended to include weight.
class BoxWeight extends Box
{
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;

64

}
}
class inhe3
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 30, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}

4. Explain Multilevel Hierarchy ?


It is common that a class is derived from another derived class.
The class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
The class B is known as intermediated base class since it provides a link
for the inheritance between A and C.
The chain ABC is known as inheritance path. When this type of situation
occurs, each subclass inherits all of the features found in all of its super
classes. In this case, C inherits all aspects of B and A.
Superclass

Intermediate superclass

Subclass

Multilevel Inheritance
Example
class student
{
int rollno;
String name;

65

student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student
{
int total;
marks(int r, String n, int t)
{
super(r,n);
total = t;
}
void dispdatam()
{
dispdatas();
System.out.println("Total = " + total);
}
}
class percentage extends marks
{
int per;
percentage(int r, String n, int t, int p)
{
super(r,n,t);
per = p;
}
void dispdatap()
{
dispdatam();
System.out.println("Percentage = " + per);
}
}
class inhe6
{
public static void main(String args[])
{

66

percentage stu = new percentage(1912, "SAM", 350, 50);


stu.dispdatap();
}
}
Explain Method Overriding ? With an Example ? [ Nov / Dec 2008] ,
[March/April -2009], [Oct / Nov 2009]

When a method in a subclass has the same name, same argument and
same return type (type signature) as those of the superclass,
then the method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within a subclass,
it will always refer to the version of that method defined by the subclass.

Example
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("Super i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
System.out.println("Sub k: " + k);
}
}
class inhe7

67

{
public static void main(String args[])
{
A superob = new A(10,20);
B subOb = new B(1, 2, 3);
superob.show();
subOb.show(); // this calls show() in B
}
}
7. What is an Abstract Classes ?
When the keyword abstract appears in a class definition, it means that
zero or more of its methods are abstract.
An abstract method has no body.
Some of the subclass has to override it and provide the implementation.
Objects cannot be created out of abstract class.
Abstract classes basically provide a guideline for the properties and
methods of an object.
Inorder to use abstract classes, they have to be subclassed.

There are situations in which you want to define a superclass that declares
the structure of a given abstraction without providing a complete
implementation of every method.

That is, sometimes you want to create a superclass that only defines
generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.

One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.

To declare an abstract method, use this general form:


abstract type name(parameter-list);

As you can see, no method body is present.


Any class that contains one or more abstract methods must also be
declared abstract.
To declare a class abstract, you simply use the abstract keyword in front of
the class keyword at the beginning of the class declaration.
There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new
operator.
Any subclass of an abstract class must either implement all of the abstract
methods of the superclass, or be itself declared abstract.

Example

68

abstract class A
{
abstract void displayb();
void displaya()
{
System.out.println("This is a concrete method");
}
}
class B extends A
{
void displayb()
{
System.out.println("B's implementation");
}
}
class inhe9
{
public static void main(String args[])
{
B b = new B();
b.displayb();
b.displaya();
}
}
Example
abstract class shape
{
double dim1;
double dim2;
shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}
class rectangle extends shape
{
rectangle(double a, double b)
{
super(a,b);

69

}
double area()
{
System.out.println("Area of rectangle.");
return dim1*dim2;
}
}
class triangle extends shape
{
triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of triangle.");
return dim1*dim2/2;
}
}
class inhe10
{
public static void main(String args[])
{
rectangle r = new rectangle(10,20);
triangle t = new triangle(10,6);
System.out.println(r.area());
System.out.println(t.area());
}
}

INTERFACE [ Nov / Dec 2008] , [March/April -2009], [Oct / Nov 2009]


1. Explain Concept of Interface ?
Interfaces are similar to abstract classes, but differ in their functionality.
In interfaces, none of the methods are implemented means interfaces
defines methods without body.
Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body.

70

But, it can contain final variables, which must be initialized with values.
Once it is defined, any number of classes can implement an interface.
One class can implement any number of interfaces.
If we are implementing an interface in a class we must implement all the
methods defined in the interface as well as a class can also implement its
own methods.

Interfaces add most of the functionality that is required for many


applications which would normally resort to using multiple inheritance in
C++.

2. How to define an Interface ?


The general form of an Interface
[Access-specifier] interface interface-name
{
Access-specifier return-type method-name(parameter-list);
final type var1=value;
}

Where, Access-specifier is either public or it is not given.


When no access specifier is used, it results into default access specifier
and if interface has default access specifier then it is only available to other
members of the same package.
When it is declared as public, the interface can be used by any other code
of other package.

Interface-Name: name of an interface, it can be any valid identifier.

The methods which are declared having no bodies they end with a
semicolon after the parameter list. Actually they are abstract methods;
any class that includes an interface must implement all of the methods.
Variables can be declared inside interface declarations.
They are implicitly final and static, means they can not be changed by
implementing it in a class.
They must also be initialized with a constant value.

3. How to Implementing an Interfaces ?


Once an interface has been defined, one or more classes can implement
that interface.
To implement an interface, include the implements clause in a class
definition, and then create the methods declared by the interface.

The general form of a class that includes the implements clause looks like
this:

71

Access-specifier class
interface, [, interface..]]

classname

[extends

superclass]

[implements

{
// class body
}

If a class implements from more than one interface, names are separated
by comma.
If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.
The methods that implement an interface must be declared as public.
The type-signature of implementing method must match exactly the type
signature specified in the interface.

Example 1
interface religion
{
String city = new String("Amritsar");
void greet();
void pray();
}
class gsikh implements religion
{
public void greet()
{
System.out.println("We greet - Sasi ya Kal");
}
public void pray()
{
System.out.println("We pray - Mattha tekte Hai ");
}
}
class iface1
{
public static void main(String args[])
{
gsikh sikh = new gsikh();
sikh.greet();
sikh.pray();
}
}
Example 2
interface i1

72

{
void dispi1();
}
interface i2
{
void dispi2();
}
class c1 implements i1
{
public void dispi1()
{
System.out.println("This is display of i1");
}
}
class c2 implements i2
{
public void dispi2()
{
System.out.println("This is display of i2");
}
}
class c3 implements i1, i2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
class iface2
{
public static void main(String args[])
{
c1 c1obj = new c1();
c2 c2obj = new c2();
c3 c3obj = new c3();
c1obj.dispi1();

73

c2obj.dispi2();
c3obj.dispi1();
c3obj.dispi2();
}
}
Example
// Implementing interface having common function name
interface i1
{
void disp();
}
interface i2
{
void disp();
}
class c implements i1, i2
{
public void disp()
{
System.out.println("This is display .. ");
}
}
class iface7
{
public static void main(String args[])
{
c cobj = new c();
cobj.disp();
}
}

Note: When implementing an interface method, it must be declared as public. It is


possible for classes that implement interfaces to define additional members of their
own.

4. How to Accessing and Implement through Interface References ?


One can declare variable as object references that uses an interface rather
than a class type.
When you call a method through one of these references, the correct
version will be called based on the actual instance of the interface being
referred to.

74

Example
interface AreaCal
{
final double pi = 3.14;
double areacalculation(double r);
}
class Circle implements AreaCal
{
public double areacalculation(double r)
{
double ar;
ar = pi*r*r;
return ar;
}
}
class iface3
{
public static void main(String args[])
{
double area;
AreaCal ac = new Circle();
area = ac.areacalculation(10.25);
System.out.println("Area of Circle is : " + area);
}
}
Variable ac is declared to be of the interface type AreaCal,
it was assigned an instance of circle. Although ac can be used to access the
areacalculation() method,
it cannot access any other members of the client class. An interface
reference variable only has knowledge of the method declared by its
interface declaration.
5. How to Partial Implementation of Interface ?
If we want to implement an interface in a class we have to implement all
the methods defined in the interface,
but if a class implements an interface but does not fully implement the
method defined by that interface,
then that class must be declared as abstract.
Example
// Partial Implementation

75

interface i1
{
void disp1();
void disp2();
}
abstract class c1 implements i1
{
public void disp1()
{
System.out.println("This is display of 1");
}
}
class c2 extends c1
{
public void disp2()
{
System.out.println("This is display of 2");
}
}
class iface5
{
public static void main(String args[])
{
c2 c2obj = new c2();
c2obj.disp1();
c2obj.disp2();
}
}
6. How Interfaces can be Extended ?
One interface can inherit another by use of the keyword extends. The
syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface,
it must provide implementation of all methods defined within the
interface inheritance.

Note: Any class that implements an interface must implement all methods
defined by that interface, including any that inherited from other
interfaces.

// Interface can be extended


interface i1
{

76

void dispi1();
}
interface i2 extends i1
{
void dispi2();
}
class c1 implements i2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
class iface3
{
public static void main(String args[])
{
c1 c1obj = new c1();
c1obj.dispi1();
c1obj.dispi2();
}
}
Multiple inheritance using interface ?
Example
// Multiple inheritance using interface
class stu
{
int rollno;
String name = new String();
int marks;
stu(int r, String n, int m)
{
rollno = r;
name = n;
marks = m;
}
}
interface i

77

{
void display();
}
class studerived extends stu implements i
{
studerived(int r, String n, int m)
{
super(r,n,m);
}
public void display()
{
System.out.println("Displaying student details .. ");
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
System.out.println("Marks = " + marks);
}
}
class iface6
{
public static void main(String args[])
{
studerived obj = new studerived(1912, "Ram", 75);
obj.display();
}
}

78

79

CHAPTER 4
MULTITHREADING AND EXCEPTION HANDLING
2. Explain Concept of exception Handling ? [ Nov / Dec 2008], [March/April
-2009], [Oct / Nov 2009]

An exception is an object that is generated at run-time.


When java interpreter encounters an error such as integer division-byzero,
array index negative or out-of-bounds, illegal casting, interrupted I/O
operation, unexpected end-of-file condition, missing file, incorrect
number format it creates an exception object and throws it.
If the exception object is not handled properly, the interpreter will
display the error and will terminate the program.
Now if we want to continue the program with the remaining code,
then we should try to catch the exception object and should display
error message for taking proper action.
This process is known as Exception handling. The purpose of
exception handling is to detect and report an exception so that proper
action can be taken.
Java exception handling is managed by using five keywords: try, catch,
throw, throws and finally.

Try:
Piece of code of your program that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try block, it
is thrown.
Catch:
Catch block can catch this exception and handle it in some logical manner.
Throw:
System-generated exceptions are automatically thrown by the Java runtime system. Now if we want to manually throw an exception, we have to
use the throw keyword.
Throws:
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception. You do this by including a throws
clause in the methods declaration. Basically it is used for IOException. A
throws clause lists the types of exceptions that a method might throw. This
is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a

80

method can throw must be declared in the throws clause. If they are not, a
compile-time error will result.
Finally:
Any code that absolutely must be executed before a method returns is put
in a finally block.
General form:
try
{
//code to monitor for errors
//generate the exception
}
catch(ExceptionType e)
{
//handle the exception
}

The try block contains a block of code that may generate an exception. If
any problem occurs during its execution, an exception will be generated
and it is thrown.
Immediately following the try block there is a sequence of catch blocks.
Each of these begins with the catch keyword.
An argument is passed to each catch block.
That argument is the exception object that contains information about the
problem. If a problem occurs during execution of the try block,
the JVM immediately stops executing the try block and looks for a catch
block that can process that type of exception.
Any remaining statements in the try block are not executed. The search
begins at the first catch block.
If the type of the exception object matches the type of the catch block
parameter, those statements are executed. Otherwise,
the remaining catch clauses are examined in sequence for a type match.
When a catch block completes executing,
control passes to the statements in the finally block. The finally block is
executed in all circumstances.
If a try block completes without problems, the finally block executes. Even
if a return statement is included in a try block,
the compiler ensures that the finally block is executed before the current
method returns. The finally block is optional.
Each try block must have at least one catch or finally block.

Example
class etion1
{
public static void main(String args[])
{

81

int num1 = 100;


int num2 = 50;
int num3 = 50;
int result1;
int result2;
try
{
result1 = num1/(num2+num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}

result2 = num1/(num2+num3);
System.out.println("Result2 = " + result2);
}
}

4. Displaying a Description of an Exception ?


You can display the description of thrown object by using it in a println()
statement by simply passing the exception as an argument. For example;
catch (ArithmeticException e)
{
system.out.pritnln(Exception: +e);
}

Example
// Multiple catch
class etion2
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;

82

int arr[] = {4,5,6};


try
{
result1 = num1/(num2+num3);
arr[9] = 13;
System.out.println("Result1 = " + result1);
for(int i =0; i<=2;i++)
{
System.out.println(arr[i]);
}
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array is index in not in range");
}
}
}

When you are using multiple catch blocks, it is important to remember


that exception subclasses must come before any of their superclasses.
This is because a catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses.
Thus, a subclass will never be reached if it comes after its superclass. And
it will result into syntax error.

// Catching super exception before sub


class etion3
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;

try
{
result1 = num1/(num2-num3);

83

System.out.println("Result1 = " + result1);


}
catch (Exception e)
{
System.out.println("This is mistake. ");
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
}
}

If you try to compile this program, you will receive an error message
because the exception has already been caught in first catch block.
Since ArithmeticException is a subclass of Exception, the first catch block
will handle all exception based errors,
including ArithmeticException. This means that the second catch
statement will never execute.
To fix the problem, revere the order of the catch statement.

6. Explain Nested try statements ? With an Example ?


The try statement can be nested.
That is, a try statement can be inside a block of another try.
Each time a try statement is entered, its corresponding catch block has to
entered.
The catch statements are operated from corresponding statement blocks
defined by try.
// Nested try statements
class etion4
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
try
{

84

result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException e)
{
System.out.println("This is inner catch");
}
}
catch(ArithmeticException g)
{
System.out.println("This is outer catch");
}
}
}
7. Explain Throw with an Example ?
We saw that an exception was generated by the JVM when certain runtime problems occurred.
It is also possible for our program to explicitly generate an exception.
This can be done with a throw statement. Its form is as follows:
Throw object;

Inside a catch block, you can throw the same exception object that was
provided as an argument.
This can be done with the following syntax:

catch(ExceptionType object)
{
throw object;
}
Alternatively, you may create and throw a new exception object as follows:
Throw new ExceptionType(args);

Here, exceptionType is the type of the exception object and args is the
optional argument list for its constructor.
When a throw statement is encountered, a search for a matching catch
block begins and if found it is executed.

Example
// Example of throw

class etion4
{

85

public static void a()


{
try
{
System.out.println("Before b");
b();
System.out.println("********");
System.out.println("");
System.out.println("After b");
}
catch(ArithmeticException e)
{
System.out.println("a : " + e);
}
}
public static void b()
{
try
{
System.out.println("Before c");
c();
System.out.println("********");
System.out.println("");
System.out.println("After c");
}
catch(ArithmeticException e)
{
System.out.println("b : " + e);
}
catch(ArrayIndexOutOfBoundsException j)
{
System.out.println("J : " + j)
;
}
}
public static void c()
{
try
{
System.out.println("Before d");
d();
System.out.println("********");
System.out.println("");
System.out.println("After d");
}

86

catch(ArithmeticException e)
{
System.out.println("c : " + e);
throw new ArrayIndexOutOfBoundsException("demo");
}
}
public static void d()
{
try
{
int i=1;
int j=0;
System.out.println("Before Division");
System.out.println(i/j);
System.out.println("After Division");
}
catch(ArithmeticException e)
{
System.out.println("d : " + e);
throw e;
}
}
public static void main(String args[])
{
try
{
System.out.println("Before a");
a();
System.out.println("********");
System.out.println("");
System.out.println("After a");
}
catch(ArithmeticException e)
{
System.out.println("Main Program : " + e);
}
}
}
Example
// Example of throw
class etion4

87

{
public static void a()
{
try
{
System.out.println("Before b");
b();
System.out.println("********");
System.out.println("");
System.out.println("After b");
}
catch(ArithmeticException e)
{
System.out.println("a : " + e);
}
}
public static void b()
{
try
{
System.out.println("Before c");
c();
System.out.println("********");
System.out.println("");
System.out.println("After c");
}
catch(ArithmeticException e)
{
System.out.println("b : " + e);
}
}
public static void c()
{
try
{
System.out.println("Before d");
d();
System.out.println("********");
System.out.println("");
System.out.println("After d");
}
catch(ArithmeticException e)
{
System.out.println("c : " + e);

88

}
}
public static void d()
{
try
{
int i=1;
int j=0;
System.out.println("Before Division");
System.out.println(i/j);
System.out.println("After Division");
}
catch(ArithmeticException e)
{
System.out.println("d : " + e);
throw e;
}
}
public static void main(String args[])
{
try
{
System.out.println("Before a");
a();
System.out.println("********");
System.out.println("");
System.out.println("After a");
}
catch(ArithmeticException e)
{
System.out.println("Main Program : " + e);
}
}
}

89

8. Explain Throws with an Example ?


If a method is capable of causing an exception that it does not handle, \
it must specify this behavior so that callers of the method can guard
themselves against that exception.
You do this by including a throws clause in the methods declaration.
Basically it is used for IOException.
A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type Error or
RuntimeException,
or any of their subclasses. All other exceptions that a method can throw
must be declared in the throws clause. If they are not,
a compile-time error will result.

This is the general form of a method declaration that includes a throws


clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.

Throw is used to actually throw the exception, whereas throws is


declarative statement for the method. They are not interchangeable.

Example
// -------throws example
class NewException extends Exception
{
public String toS()
{
return "You are in NewException ";
}
}
class customexception
{
public static void main(String args[])
{
try
{
doWork(3);
doWork(2);

90

doWork(1);
doWork(0);
}
catch (NewException e)
{
System.out.println("Exception : " + e.toS());
}
}
static void doWork(int value) throws NewException
{
if (value == 0)
{
throw new NewException();
}
else
{
System.out.println("****No Problem.****");
}
}
}
9. Finally
When exception generated inside the try block,
the statement placed in between the point of occurring of the exception
and the end of the try block will be skipped and the control looks for
matching catch block.
When a catch block completes executing, control passes to the statements
in the finally block.
The finally block is executed in all circumstances. Even if a try block
completes without problems, the finally block executes.
Example
// Example of Final
class etion10
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);

91

}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
finally
{
System.out.println("This is final");
}
}
}

MULTITHREADING
2. EXPLAIN LIFE CYCLE OF THREAD ? [ Nov / Dec 2008] , [March/April 2009], [Oct / Nov 2009]

During the life time of a thread, there are many states it can enter. They
include:
1.
2.
3.
4.
5.

Newborn state
Runnable state
Running state
Blocked state
Dead state

1. Newborn state
When we create a thread object, the thread is said to be in
newborn state.
The thread is not yet scheduled for running. At this state, we can
do only one of the following with it:
o Schedule it for running using start() method.
o Kill it using stop() method

If we schedule it for running, it moves to the runnable state. If we attempt


to use any other method at this stage, an exception will be thrown.

2. Runnable state (start())


The runnable state means that the thread is ready for execution.
The thread has joined the queue of threads that are waiting for execution
and waiting for the availability of the processor.

92

If all threads have equal priority, then they are given time slots for
execution in round robin fashion i.e.
First-Come, First-Serve manner.
The thread that relinquishes (gives up) control joins the queue at the end
and again waits for its turn.
This process of assigning time to threads is known as time-slicing.
If we want a thread to relinquish control to another thread of equal
priority before its turn comes,
we can do so by using they yield() method.

3. Running state
Running means that the processor has given its time to the thread for its
execution.
The thread runs until it relinquishes (gives up) control on its own or it is
preempted by a higher priority thread.
A running thread may relinquish its control in one of the following
situations:
It has been suspended using suspend() method. A suspend thread can be
revived by using the resume() method.
This approach is useful when we want to suspend a thread for some time
due to certain reason, but do not want to kill it.
It has been made to sleep. We can put a thread to sleep for a specified time
period using the method sleep(time), where time is in milliseconds.
This means that the thread is out of the queue during this time period. The
thread re-enter the runnable state as soon as this time period is lapsed.
It has been told to wait until some event occurs. This is done using the
wait() method. The thread can be scheduled to run again using the notify()
method.
4. Blocked State
A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently into the running state.
This happens when the thread is suspended, sleeping, or waiting in order
to satisfy certain requirements.
A blocked thread is considered not runnable but not dead and therefore
fully qualified to run again.
5. Dead State
A running thread ends its life when it has completed executing its run()
method.
It is a natural death. However, we can kill it by sending the stop message
to it at any state thus causing a premature death to it.
A thread can be killed as soon it is born, or while it is running, or even
when it is in not runnable (blocked) condition.
3. THREAD CLASS

93

Some of the constructors for Thread are as follows:


thread()
thread(Runnable r)
thread(Runnable r, String s)
thread(String s)
here, r is a reference to an object that implements the Runnable
interface and s is a String used to identify the thread.
4. Methods of Threads class
Method
Thread currentThread()

Description
Returns a reference to the current
thread
Void sleep(long msec)
Causes the current thread to wait for
Throws InterruptedException
msec milliseconds
Void sleep(long msec, int nsec)
Causes the current thread to wait for
Throws InterruptedException
msec
milliseconds
plus
nsec
nanoseconds
Void yield()
Causes the current thread to yield
control of the processor to other
threads
String getName()
Returns the name of the thread.
Int getPriority()
Returns the priority of the thread.
Boolean isAlive()
Returns true if this thread has been
started and has no yet died.
Otherwise, returns false.
Void
join()
throws Causes the caller to wait until this
InterruptedException
thread dies.
Void join(long msec)
Causes the called to wait a max of
Throws InterruptedException
msec until this thread dies. If msec is
zero, there is no limit for the wait
time.
Void join(long msec, int nsec) throws Causes the called to wait a max of
Interruptedexception
msec plus nsec until this thread dies.
If msec plus nsec is zero, there is no
limit for the wait time.
Void run()
Comprises the body of the thread.
This Method is overridden by sub
classes.
Void setName(String s)
Sets the name of this thread to s.
Void setPriority(int p)
Sets the priority of this thread to p.
Void start()
Starts the thread
String toString()
Returns the string equivalent of this
thread.

Although the main thread is created automatically when your


program is started,

94

it can be controlled through a Thread object. To do so, you must


obtain a reference to it by calling the method currentThread( ),
which is a public static member of Thread. Its general form is
shown here:
static Thread currentThread( )
Example
// Basic of Thread
class ThreadX
{
ThreadX()
{
hello();
}
public void hello()
{
r();
}
public void r()
{
try
{
int i = 1;
while(i<=5)
{
Thread.sleep(20);
System.out.println("\n\tHello ** " + i);
System.out.println("\n\tThread name
Thread.currentThread().getName());
System.out.println("\n\tPriority
**
Thread.currentThread().getPriority());
i++;
//
if (i==3)
//
{
//
Thread.currentThread().stop();
//
}
}
}
catch(InterruptedException ex)
{
System.out.println("It is interrupted");
}
}
}
class ThreadDemo1
{

95

**
"

"

+
+

public static void main(String args[])


{
ThreadX tx = new ThreadX();
try
{
System.out.println("\n\nThis is before sleep ** ");
Thread.sleep(5000);
System.out.println("\n\tThis is after sleep ** ");
String nm = Thread.currentThread().getName();
System.out.println("\n\tThread name ** " + nm);
int pr = Thread.currentThread().getPriority();
System.out.println("\n\tPriority ** " + pr);
Thread.currentThread().setName("Bill Gates");
nm = Thread.currentThread().getName();
System.out.println("\n\tThread name ** " + nm);
Thread.currentThread().setPriority(3);
System.out.println("\n\tPriority
**
Thread.currentThread().getPriority());
tx.hello();
}
catch(InterruptedException ex)
{
System.out.println("It is interrupted");
}
}

"

}
5. How to Create Threads ?
Thread class in the java.lang package allows you to create and manage
threads. Each thread is a separate instance of this class.
A new thread can be created in two ways:
a. by extending a thread class - Define a class that extends Thread class and
override its run() method with the code required by the thread.
b. by implementing an interface - Define a class that implements Runnable
interface. The Runnable interface has only one method, run(), that is to be
defined in the method with the code to be executed by the thread.
A. Extending the Thread class
We can directly extend the Thread class

96

class ThreadX extends Thread


{
public void run()
{
//logic for the thread
}
}

The class ThreadX extends Thread. The logic for the thread is contained in
the run() method.
That method may be very simple or complex. It can create other objects or
even initiate other threads.
The program can start an instance of the thread by using the form shown
here;

ThreadX tx=new ThreadX();


tx.start();
The first line instantiates the ThreadX class.
The second line invokes the start() method of that object to start the thread
executing.
One of the actions of the start() method is to invoke the run() method.
Example
// Extending from Thread Class
class Textend extends Thread
{
Textend()
{
super.start();
//start();
}
public void start()
{
System.out.println("---This is before run");
run();
System.out.println("---This is after run");
}
public void run()
{
try
{
for(int i = 1; i<=5; i++)
{
System.out.println("\nName of Thread " +
(Thread.currentThread()).getName());
System.out.println(i);

97

Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Thread has been interupted");
}
}
}
class Thread2
{
public static void main(String args[])
{
Textend tobj1 = new Textend();
Textend tobj2 = new Textend();
}
}
B. How to create a thread Using Runnable Interface ?
Declare a class that implements the Runnable interface.
This method declares only one method as shown here:
public void run();
Class RunnableY implements Runnable
{
public void run()
{
// logic for thread
}
}

The application can start an instance of the thread by using the following
code:
RunnableY ry = new RunnableY();
ThreadY ty=new Thread(ry);
Ty.start();
1st line instantiate the RunnableY class
2nd line instantiate the Thread class.

A reference to the RunnableY object is provided as the argument to the


constructor.
Last line starts the thread.

98

Example
// Extending from runnable Class
class rthread implements Runnable
{
public void run()
{
try
{
for(int i = 1; i<=5; i++)
{
System.out.println("\nName of Thread
(Thread.currentThread()).getName());
System.out.println(i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Thread has been interupted");
}
}
}
class Thread3
{
public static void main(String args[])
{
rthread r1 = new rthread();
Thread t=new Thread(r1);
t.start();
}
}
6. How to Create multiple threads Explain with an Example ?
// Creating Muliple thread
class Textend extends Thread
{
Textend()
{
super.start();
//start();
}
public void start()

99

"

{
System.out.println("---This is before run");
run();
System.out.println("---This is after run");
}
public void run()
{
try
{
for(int i = 1; i<=5; i++)
{
System.out.println("\nName of Thread
(Thread.currentThread()).getName());
System.out.println(i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Thread has been interupted");
}
}
}

"

class Thread2
{
public static void main(String args[])
{
Textend tobj1 = new Textend();
Textend tobj2 = new Textend();
}
}

7.
8. How to Stop a Thread ?
Whenever we want to stop a thread from running further, we can do that
calling its stop() method like:
ty.stop();

This statement causes the thread to move to the dead state.


A thread will also move to the dead state automatically when it reaches
the end of its method.

100

The stop() method is used when the premature death of a thread is


desired.

12. What is a Dead Lock ? [March/April -2009]


Deadlock is an error that can be encountered in multithreaded programs.
It occurs when two or more threads wait for ever for each other to
relinquish locks.
Assume that thread1 holds lock on object1 and waits for a lock on object2.
Thread2 holds a lock on object2 and waits for a lock on object1.
Neither of these threads may proceed. Each waits forever for the other to
relinquish the lock it needs.
Deadlock situations can also arise that involve more than two threads.
Assume that thread1 waits for a lock held by thread2.
thread2 waits for a lock held by thread3. thread3 waits for a lock held by
thread1.
// An example of Dead lock
class A
{
B b;
synchronized void a1()
{
System.out.println("Method a1");
System.out.println("Calling b2");
b.b2();
}
synchronized void a2()
{
System.out.println("Method a2");
}
}
class B
{
A a;
synchronized void b1()
{
System.out.println("Method b1");
System.out.println("Calling a2");
a.a2();
}
synchronized void b2()
{
System.out.println("Method b2");
}

101

}
class ThreadA extends Thread
{
A a;
ThreadA(A a)
{
this.a =a;
}
public void run()
{
for (int i = 0;i<500;i++)
a.a1();
}
}
class ThreadB extends Thread
{
B b;
ThreadB(B b)
{
this.b =b;
}
public void run()
{
for (int i = 0;i<500;i++)
b.b1();
}
}
class Thread6
{
public static void main(String args[])
{
A a = new A();
B b = new B();
a.b = b;
b.a = a;
ThreadA t1 = new ThreadA(a);
ThreadB t2 = new ThreadB(b);
t1.start();

102

t2.start();
System.out.println("Main Method");
}
}

103

CHAPTER 5
INPUT AND OUTPUT
Explain concept of FILES AND DIRECTORIES ? [ Nov / Dec 2008], [Oct /
Nov 2009]

The java.io package provides a File class that supports for creating files
and directories.
These include its read and write permissions, time of last modification,
and length.
It is also possible to determine the files that are contained in a directory.
New directories can be created, and existing files and directories can be
deleted or renamed.
The File class provides the following constructors:
File(String path)
File(String directoryPath, String filename)
File(File object, String filename)

In first form one has to provide the path to a file or directory.


In second form, directory path specifies the path to a directory and
filename provides the name of a file in that directory.
In last form you have to provide a File object for a directory and the name
of a file in that directory.
All of these constructors throw a NullPointerException if path or filename
is null.
File defines two char constants. These are separatorChar (\) and
pathSeparatorChar(;).

Methods of File class


Method
Boolean canRead()

Description
Returns true if the file exists and can be read. Otherwise,
returns false.
Boolean canWrite()
Returns true if the file exists and can be written.
Otherwise, returns false.
Boolean delete()
Deletes the file. Returns true if the file is successfully
deleted. Otherwise, returns false. Not that a directory
must be empty before it can be deleted.
Boolean equals(Object Returns true if the current object and obj refer to the
obj)
same file. Otherwise, return false.
Boolean exists()
Returns true if the file exists. Otherwise, returns false.
104

String getAbsolutePath()
String
getCanonicalPath()
String getName()
String getParent()
String getPath()
Boolean isAbsolute()

Returns the absolute path to the file.


Returns the canonical path to the file.

Returns the name of the file.


Returns the parent of the file.
Returns the path to the file.
Returns true if the file path name is absolute. Otherwise,
returns false.
Boolean isDirectory()
Returns true if the file is a directory. Otherwise, returns
false.
Boolean isFile()
Returns true if the file is not a directory. Otherwise,
returns false.
Long lastModified()
Returns the number of milliseconds between 0:00:00
GMT, January 1, 1970, and the time of last modification
for this file.
Long length()
Returns the number of bytes in the file.
String[] list()
Returns the names of the files in the directory.
Boolean mkdir()
Creates a directory with the name of the file. All parent
directories must already exist. Returns true if the
directory is created. Otherwise, returns false.
Boolean mkdirs()
Creates a directory with the name of the file. Any
missing parent directories are also created. Returns true
if the directory is created. Otherwise, returns false.
Boolean renameTo (File Renames the file or directory to newName. Returns true
newName)
if the current object has been renamed to newName.
Otherwise, returns flase.

2. What is a Stream ? Explain Stream Classes ?


A stream is the ordered sequence of data, that is a common characteristics
shared by the entire input/output device.
A stream has a source and a destination of data.
A stream is linked to a physical device by the Java I/O system. For
example, an input stream may read its data from a keyboard, file or
memory buffer.
An output stream may write its data to a monitor, file or memory buffer.
other types of devices may also be used as the source or destination for a
stream.
There are two types of streams:
[1]
Character Streams
[2]
Byte Streams
[1]
Character Streams
Character Streams allows you to read and write characters and strings.

105

The characters are stored and retrieved in a human readable form. An


input character Stream converts bytes to Character.
An output character Stream converts character to bytes.

[2]
Byte Streams
Byte stream allows you to read write binary data. In this, data is accessed
as a sequence of bytes.
[1]
Character Streams Classes
Character stream classes allow you to read and write characters and
strings.
The characters are stored and retrieved in a human readable form.
An input character stream converts bytes to characters.
An output character stream converts characters to bytes.
Java internally represents characters according to the 16-bit Unicode
encoding.
Though, this may not be the encoding used on all machines.
Character streams translate between these two formats.
Following are the character streams provided by the java.io package.
1. Reader
a. BufferedReader
b. InputStreamReader
i. FileReader
2. Writer
a. BufferedWriter
b. OutputStreamWriter
i. FileWriter
c. PrintWriter

Explain Reader Classes Methods?


Reader stream classes are used to read characters from the file.
The Reader class defines the functionality that is available for all character
input streams.
Reader is an abstract class so, we cannot create an instance of this class.
We can use the subclasses BufferedReader and InputStreamReader of
Reader class.

Methods of Reader class


Method
Description
void close()
Closes the input stream. Further read attempts
generate an IOException. Must be implemented by
a subclass.
void
mark(int Places a mark at the current point in the input
numChars)
stream that will remain valid until numChars

106

characters are read.


Returns true if mark()/reset() are supported in this
stream.
Reads a character from the stream. Waits until data
is available.
int read(char buffer[])
Attempts to read up to buffer-length characters into
buffer and returns the actual number of characters
that were successfully read. Waits until data is
available.
int read(char buffer[], Attempts to read up to numChars characters into
int
offset,
int buffer starting at buffer[offset] and return the actual
numChars)
number of characters that were successfully read.
Waits until data is available.
Boolean ready()
Returns true if the next read() will not wait.
void reset()
Resets the input pointer to the previously set mark.
int
skip(long Skips over numChars bytes of input returning the
numChars)
number of characters actually skipped.
Boolean
markSupported()
int read()

Explain Input Stream Reader ? [March/April -2009]


The Input Stream Reader class is a subclass of Reader class.
It converts a stream of bytes to a stream of characters.
This is done according to the rules of a specific character encoding.
The constructors provided by this class are as follows:
InputStreamReader(InputStream is)
InputStreamReader(InputStream is, String encoding)

Here, is = input stream


Encoding is name of character encoding.
getEncoding() returns the name of the character encoding. It has following
syntax;
String getEncoding()
o Explain File Reader
o The File Reader class is a subclass of InputStreamReader class
and inputs characters from a file. Its two most common
constructors are:
FileReader(String filepath)
FileReader(File object)
Either can throw a FileNotFoundException.

Writer
The writer stream classes are used to perform all output operations on
files.

107

The writer class is an abstract class which acts as a base class for all other
writer stream classes.
Its constructors are:
Writer()
Writer(Object obj)

Methods of Writer class


Method
void close()
void flush()

Description
Closes the output stream.
Writes any buffered data to the physical device
represented by that stream.
void write(char buffer[])
Writes the characters in buffer to the stream.
void write (char buffer[], int Writes size characters from buffer starting at
index, int size)
position index to the stream.
void write(String s)
Writes s to the stream.
Void write
Writes size characters from s starting at
(String s, int index, int size) position index to the stream.

Explain Output Stream Writer ?


The OutputStreamWriter class is a subclass of writer class.
It converts a stream of characters to a stream of bytes.
This is done according to the rules of a specific character encoding.
Its constructors are like this:
OutputStreamWriter(OutputStream os)
OutputStreamWriter(OutputStream os, String encoding)

Here, os is the output stream and encoding is the name of a character


encoding.
The first form of the constructor uses the default character encoding of the
users machine.
The getEncoding() method returns the name of the character encoding. It
has this syntax:
String getEncoding()

o File Writer
o The file writer class is a subclass of OutputStreamWriter class
and outputs characters to a file.
o Its constructors are as follows:
FileWriter(String filepath) throws IOException
FileWriter(String filepath, Boolean append) Throws IOException
FileWriter(File object) throws IOException
Example 1
import java.io.*;

108

class FileWriteDemo
{
public static void main (String args[])
{
try
{
FileWriter fw = new FileWriter("Hi.txt");
for(int i = 0; i<=5; i++)
{
System.out.println(i);
fw.write(i);
}
fw.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}
/* A program to read from file */
import java.io.*;
class FileReadDemo
{
public static void main (String args[])
{
try
{
FileReader fr = new FileReader("Hi.txt");
int i;
i=fr.read();
while(i!= -1)
{
System.out.println(i);
i=fr.read();
}
fr.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);

109

}
}
}

Explain Buffered Character Streams? With an Example ?

There are two classes BufferedWriter and BufferedReader.


The advantage of buffering is that the number of reads and writes to a
physical device is reduced. This improves performance.

[a] BufferedWriter
The BufferWriter class is a subclass of Writer class and buffers output to a
character stream. Its constructors are as follows:
BufferedWriter(Writer w)
BufferedWriter(Writer w, int bufSize)

The first form creates a buffered stream using a buffer with a default size.
In second, the size of the buffer is specified by bufsize.

This class implements all of the methods defined by Writer. In addition, it


provides the newLine() method to output a line separator. The syntax is :
void newLine() throws IOException

[b] BufferedReader
The BufferedReader class is a subclass of Reader class and buffers input
from a character stream. Its constructors are as follows:
BufferedReader(Reader r)
BufferedReader(Reader r, int bufSize)

The first form creates a buffered stream using a buffer with a default size.
In second, the size of the buffer is specified by bufsize.

This class implements all of the functionality defined by Reader.

In addition, the readLine() method reads newline-terminated strings from


a character stream. Its signature is:
String readLine() throws IOException

Example
/* Writing into file using buffer */
import java.io.*;
class BufferedWriterDemo

110

{
public static void main(String args[])
{
try
{
FileWriter fw = new FileWriter("Hello.txt");
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 10; i<15; i++)
{
bw.write(i);
}
bw.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}
Example
/* Reading from file using buffer */
import java.io.*;
class BufferedReadDemo
{
public static void main(String args[])
{
try
{
FileReader fr = new FileReader("Hello.txt");
BufferedReader br = new BufferedReader(fr);
int i;
i=br.read();
while(i!= -1)
{
System.out.println(i);
i=br.read();
}
fr.close();
}
catch(Exception e)

111

{
System.out.println("Exception : " + e);
}
}
}

System.in is passed as the argument to the InputStreamReader


constructor.
This is done because System.in is an InputStream.
The InputStreamReader object is then passed as the argument to the
BufferedReader constructor.

Example
/* Reads input from keyboard and displays the length of string */
import java.io.*;
class ReadConsole
{
public static void main(String args[])
{
try
{
InputStreamReader
isr
=
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s;
int i = 0;
while((s=br.readLine())!=null)
{
System.out.println(s.length());
i++;
if (i==2)
break;
}
isr.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

112

new

[2] What is Byte Streams Explain in details ?


Byte streams allow a programmer to work with the binary data in a file.
In this, stream data is accessed as a sequence of bytes.
All types other than text or character are dealt in this stream.
ByteStream
includes
OutputStream,
FileOutputStream,
DataOutputStream, and PrintStream classes that are used for output,
while the InputStream,
FileInputStream,
FilterInputStream,
BuferedInputStream
and
DataInputStream classes are used for input.
Method
Void close()
Throws IOException
Void flush()
Throws IOException
Void write(byte buffer[])
Throws IOException
Viod write(byte buffer[],
int index, int size)
Throws IOException

Description
Closes the output stream.
Flushes the output stream.
Writes buffer to the stream.
Writes size bytes from buffer starting at position
index to the stream.

Following are the Byte streams provided by the java.io package.


1. InputStream
a. FileInputStream
b. FilterInputStream
i. BufferedInputStream
ii. DataInputStream
2. OutputStream
a. FileOutputStream
b. FilterOutputStream
i. BufferedOutputStream
ii. DataOutputStream
iii. PrintStream

Explain InputStream ?
The abstract InputStream class defines the functionality that is available
for all byte input streams.
The methods provided by the InputStream are:
Method
Description
int available()
Returns the number of bytes
currently available for reading.
void close()
Closes the input stream.
void mark(int numBytes)
Places a mark at the current point in
the input stream. It remains valid
until numBytes are read.
Boolean markSupported()
Returns true if mark()/reset() are

113

supported. Otherwise, returns false.


Reads one byte form the input
stream.
Int read(byte buffer[])
Attempts to read up to buffer length
bytes into buffer and returns the
actual number of bytes that were
successfully read.
int read(byte buffer[], int offset, Attempts to read up to numBytes
intnumBytes)
bytes into buffer starting at
buffer[offset]. Returns the number of
bytes successfully read.
void reset()
Resets the input pointer to the
previously set mark.
int skip(long numBytes)
Skips numBytes of input. Returns the
number of bytes actually skipped.
int read()

Explain FileInputStream ?

Here, filepath is the full path name of a file and object is a File object that
describes the file.

Explain FilterInputStream ?

The fileInputStream class is a subclass of InputStream class and allows you


to read binary data from a file. Its constructors are as follows:
FileInputStream(String filepath) throws FileNotFoundException
FileInputStream(File object) throws FileNotFoundException

The FilterInputStream class is a subclass of InputStream class and filters an


input stream.
FilterInputStream is an abstract class so you cannot create an instance of
this class but you can create a subclass to implement the desired
functionality. It provides this constructor:
FilterInputStream(InputStream is)
Here, is is the input stream to be filtered.
o BufferdInputStream
o The BufferedInputStream class is a subclass of FilterInputStream
class and buffers input from a byte stream. Its constructors are
as follows:
BufferedInputStream(InputStream is)
BufferedInputStream(InputStream is, int bufSize)
o The first argument to both constructors is a reference to the input
stream.
o The first form creates a buffered stream by using a buffer with a default
size. In second, the size of the buffer is specified by bufSize.
o DataInputStream

114

o The DataInputStream class is a subclass of FilterInputStream


class and implements DataInput interface. It allows you to read
the simple java types using a byte input stream. This class
provides this constructor:
DataInputStream(InputStream is)
Here, is is the input stream.

Explain DataInput Interface ?

The DataInput interface defines methods that can be used to read the
simple java types from a byte input stream.
The following methods defined by the interface.
All of these can throw an IOException.

Methods of DataInput interface


Method
Boolean readBoolean()
Byte readByte()
Char readChar()
Double readDouble()
Float readFloat()
Int readInt()
Long readLong()
Short readShort()
Int readUnsignedByte()
Int readUsignedShort()
Int skipBytes(int n)

Description
Reads and returns a Boolean from
stream.
Reads and returns byte from the
stream.
Reads and returns a char from the
stream.
Reads and returns a double from the
stream.
Reads and returns a float from the
stream.
Reads and return an int form the
stream.
Reads and returns a long from the
stream.
Reads and returns a short form the
stream.
Reads and returns an unsigned byte
from the stream.
Reads and returns an unsigned short
from the stream.
Skips ahead n bytes in the stream.

Explain FilterOutputStream ?
The FilterOutputStream class is a subclass of OutputStream class.
FilterOutputStream is an abstract class so you can not create an instance
of this class but you can create a subclass to implement the desired
functionality.
It is used to filter output and provides this constructor:
115

FilterOutputStream(OutputStream os)
Here, os is the output stream to be filtered.
o BufferedOutputStream
o The
bufferedOutputStream class is
a subclass of
FilterOutputStream class and buffers output to a byte stream. Its
constructors are as follows:
BufferedOutputStream(OutputStream os)
BufferedOutputStream(OutputStream os, int bufSize)

The first argument to both constructors is a reference to the output stream.


The first form create buffered stream by using with a default size.
In the second, the size of the buffer is specified by bufSize.
o DataOutputStream
o The DataOutputStream class is a subclass of FilterOutputStream
class and implements DataOutput. It allows you to write the
simple java types to a byte output stream. The class provides
this constructor:
DataOutputStream(OutputStream os)
Here, os is output stream.

Explain DataOutput interface ?

The DataOutput interface defines methods that can be used to write the
simple java types to a byte output stream.
Following table shows the methods provided by the DataOutput interface.
All of these can throw an IOException.

Method
Void write(int i)
Void write(byte buffer[])
Void write(byte buffer[],
Int index, int size)
Void writeBoolean
(Boolean b)
Void writeByte(byte i)
Viod writeBytes(String s)
Void writeChar(char c)
Void writeChars(String s)
Void writeFloat(float f)
Void writeInt(int i)
Void writeLong(long l)
Void writeShort(short s)

Description
Writes i to the stream.
Writes buffer to the stream.
Writes size bytes from buffer starting at position
index to the stream.
Writes b to the stream.
Writes bytes.
Writes s to the stream.
Writes character.
Writes s to the stream.
Writes f to the stream.
Writes i to the stream.
Writes l to the stream.
Writes s to the stream.

Explain PrintStream ?

116

The PrintStream class is a subclass of FilterOutputStream class and


provides all of the formatting capabilities,
we have been using from System.out since the beginning.

Javas PrintStream object support the print() and println() methods for all
types including Object.

If an argument is not a simple type, the PrintStream methods will call the
objects toString() method and then print out the result.

Example
// An example of Byte stream - Writing to a file
import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[])
{
try
{
FileOutputStream fos = new FileOutputStream("F1");
for (int i = 0; i<12; i++)
{
fos.write(i);
}
fos.close();
}
catch(Exception e)
{
System.out.println("Exception :- " + e);
}
}
}
Example
// An example of Byte stream - Reading from a file
import java.io.*;
class FileInputStreamDemo
{
public static void main(String args[])
{
try
{
FileInputStream fis = new FileInputStream("F1");
int i;

117

while((i=fis.read())!=-1)
{
System.out.println(i);
}
fis.close();
}
catch(Exception e)
{
System.out.println("Exception :- " + e);
}
}
}

118

CHAPTER 6
APPLETS
WHAT IS APPLET? [March/April -2009]
Applets are a second type of a java program.
The applet class is contained in the java.applet package.
All applets are subclasses of applet. Thus, all applets must import
java.applet.
Applet must also import java.awt (abstract window toolkit).
Applet code uses the services of two classes, Applet and Graphics.
Applet is a Java program that is embedded in an HTML document and
runs in the context of a Java-compitable browser.

Applet programs are compiled like other java programs but are not
executed by the console based java run-time interpreter.

Rather they are executed by either a web browser or an applet viewer


called appletviewer, provided by the JDK.

Once an applet has been compiled, it is included in an HTML file using


Applet tag.

The applet will be executed by java-enabled web-browser when it


encounters the APPLET tag within the HTML file.

Explain APPLET LIFE CYCLE ? [Oct / Nov 2009]

1.
2.
3.
4.

Every java applet extends the Applet class. As a result, when an applet is
loaded, it goes in all the states. They are:
Born and initialization state (init())
Running state (start())
Idle state (stop())
Dead or Destroyed state (destroy())

1. Initialization state (init())


Applet is said to be in the initialization state when it is first loaded. This
can is achieved by calling the init() method of Applet class.
The applet is born. At this stage we may do the following if required:
1.
2.
3.
4.

Create objects needed by the applet


Set up initial values
Load images or fonts
Set up colors

119

The initialization occurs only once in the applets cycle.


To provide any of the behaviors mentioned above, we must override the
init() method.
public void init()
{
//code
}

2. Running state (start())


Applet is said to be in the running state when the system calls the start()
method of Applet class.
This occurs automatically after the applet is initialized.
Starting can also occur if the applet is already in stopped (idle) state.
For example, we may leave the web page containing the applet
temporarily to another page and return back to the page.
This again starts the applet running. The start() method may be called
more than once.
We may override the start() method to create a thread to control the
applet.
public void start()
{
//code
}
3. Idle or Stopped state (stop())
An Applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the
currently running applet.
We can also do so by calling the stop() method explicitly.
If we use a thread to run the applet, then we must use stop() method to
terminate the thread. We can achieve by overriding the stop() method.
public void stop()
{
//code
}
4. Dead state (destroy())
An applet is said to be dead when it is removed from the memory.
This occurs automatically by invoking the destroy() method or when we
quit browser.
Like initialization, destroying stage happens only once in the applets life
cycle. If the applet has created any resources, like threads we may override
the destroy() method to clean up these resources.
public void destroy()
{
//code

120

}
5. Display state (paint())
Applet uses the display state whenever it has to perform some output
operations on the screen.
This happens immediately after the applet enters into the running state.
The paint() method is used to perform some output operation.
The default version of paint() method does absolutely nothing.
We must therefore override this method if we want anything to be
displayed on the screen.
public void paint(Graphics g)
{
Display statement;
}

It is to be noted that the display state is not considered as a part of the


applets life cycle.

4. How to Embadded Applet and HTML ?


The applet viewer uses the HTML source code at the beginning of a .java
file to display an applet.
It is also possible to embed an applet in a web page.
You can then supply the URL for that web page to a browser and it
presents the applet. The attributes used with <applet> are
<applet
[codebase=url]
Code=clsName
[alt=text]
[name=appName]
width=wpixels
height=hpixels
[align=alignment]
[vspace=vspixels]
[hspace=hspixels]
>
[<param name=pname1 value=value1>]
[<param name=pname2 value=value2>]

121


[<param name=pnameN value=valueN>]
</applet>

CODEBASE
The second line in this listing defines an optional parameter known as
code base.
This is the location from which the .
class files for the applet are retrieved.
You can assign a URL to code base. However, if code base is not specified
in the <applet> tag, the .class files for the applet are retrieved from the
same location where the HTML
document was obtained. That location is known as document base.
CODE
The code parameter of the <applet> tag is required. It is assigned the name
of the applet class.
ALT
Browsers that cannot support applets use text as an alternate
representation of this applet.
NAME
Each instance of an applet on a web page may be assigned a unique name
shown above as appName.
WIDTH AND HEIGHT
The width and height of the applet must be specified in pixels.
ALIGN
The alignment of the applet may have a value of LEFT, RIGHT, TOP,
BOTTOM, MIDDLE and many more. These constants have the same
meaning as they do in HTML when used to align images.
VSPACE AND HSPACE
The vertical and horizontal spacing around the applet can be specified as
vspixels and hspixels.
PARAM NAME
Parameters can be passed to an applet via a series of param tags. In the
syntax shown above, the names of the paramenters are pname1 through
pnameN. The values of these parameters are value1 through valueN.

Example 1
import java.applet.*;
import java.awt.*;
/*
<applet code="apple1" width = 200 height = 200>
</applet>
*/
public class apple1 extends Applet
{

122

public void paint(Graphics g)


{
g.drawArc(20,60,100,100,30,100);
g.drawString("Bhagirath.",20,100);
}
}

1. Explain Color class With all its constructors ?


The java.awt.Color class is used to work with colors.
Each object of this class represents a particular color.
With the help of this class we can draw colored strings, lines, and shapes
in an applet.
It is possible to fill a shape such as an oval or rectangle with a color.
This class has following constructors.
Color(int red, int green, int blue)
Color(int rgb)
Color(float r, float g, float b)
Fro example,
Color c = new Color(255, 255, 240);
this.setBackground(c);

Here, red, green, and blue are integer values that range between 0 and 255.
The argument rgb contains an encoding of a color in which the red, green,
and blue components are specified in bits 23 to 16, 15 to 8 and 7 to 0,
respectively. Finally, r,g, and b are float values that range between 0.0 and
1.0f inclusive.

Table shows some of the methods defined by Color class:


Method
Description
Color brighter()
Returns a brighter version of the
current Object.
Color darker()
Returns a darker version of the
current object.
Boolean equals(Object obj)
Returns true if the current object and
obj represent the same color value.
Int getBlue()
Returns the blue component of the
current object.
Int getGreen()
Returns the green component of the
current object.
Int getRGB()
Returns an int encoding of the
current object.
Int getRed()
Returns the red component of the
current object.

123

Example
import java.applet.*;
import java.awt.*;
/*
<applet code="apple6" width = 400 height = 200>
</applet>
*/
public class apple6 extends Applet
{
public void paint(Graphics g)
{
Color c = new Color(255,0,10);
this.setBackground(c.darker());
g.setFont(new Font("serif",Font.BOLD,36));
g.setColor(Color.blue);
g.drawString("Font example", 5,100);
int i = c.getBlue();
System.out.println(i);
}
}

8. How to Display text in applet ?


We have seen that drawstring() method of the Graphics class is used to
display text. We can also display strings by using different fonts.

Explain Java.awt.Font?
Information about a font is encapsulated by the java.awt.Font class. A font
determines the size and appearance of characters in a string. The following
is one of its constructors:
Font(String name, int style, int ps)
Here, name identifies the font. Some commonly used font names are Serif,
SansSerif, and Monospaced. The style may be BOLD, ITALIC, or PLAIN.
The point size (fontsize) of the font is ps.

After a font has been created, you can then use it in a graphics context.
This is done by calling the setFont() method of the Graphics class.

This method has the following format:


void setFont(Font fontobj)

Here, fontobj is a Font object. After this method is called, any strings that
is displayed using drawstring() method will be displayed with that font.

Explain Java.awt.FontMetrics?
124

The java.awt.FontMetrics class allows you to get several metrics about the
size of a font.
Size of a font is provided in pixels.
The specific metrics that are available are the ascent, descent, leading and
height.
When a string is displayed, all of its characters are aligned to a horizontal
baseline.
Characters extend above and below that line.
The number of pixels above the baseline is the ascent.
The number of pixels below the baseline is the descent.
The number of pixels between the descent of one line and the ascent of the
next line is the leading.
The sum of the ascent, descent, and leading is called height.

The constructor for this class is


FontMetrics(Font font)
Here, font indicates the font for which metrics will be applied.
Some of the methods of this class are:
Method
Int charWidth(char c)
Int getAscent()
Int getDescent()
Int getHeight()
Int getLeading()
Int stringWidth(String
str)

Description
Returns the width of c.
Returns the ascent.
Returns the descent.
Returns the height.
Returns the leading
Returns width of str.

Example
import java.applet.*;
import java.awt.*;
/*
<applet code="apple7" width = 400 height = 200>
</applet>
*/
public class apple7 extends Applet
{
public void paint(Graphics g)
{
int baseline = 100;
g.setColor(Color.blue);
g.drawLine(0,baseline,300,baseline);
Font font = new Font("serif", Font.BOLD,36);
g.setFont(font);
g.setColor(Color.black);

125

g.drawString("Font Metrices Demo",5,baseline);


g.setColor(Color.blue);
FontMetrics fm = g.getFontMetrics(font);
int ascent=fm.getAscent();
int y = baseline-ascent;
g.drawLine(0,y,300,y);
}
}
9. How to Pass parameter to applet ?
The APPLET tag in HTML allows you to pass parameters to your applet.
To retrieve a parameter, use the getParameter() method.
It returns the value of the specified parameter in the form of a String
object.
Example
import java.applet.*;
import java.awt.*;
public class apple8 extends Applet
{
public void paint(Graphics g)
{
String myFont = getParameter("font");
String myString = getParameter("string");
int mySize = Integer.parseInt(getParameter("size"));
Font f = new Font(myFont, Font.BOLD, mySize);
g.setFont(f);
g.setColor(Color.red);
g.drawString(myString,20,20);
}
}
<HTML>
<HEAD>
<TITLE> Passing parameters to Java applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE = "apple8" WIDTH = 400 HEIGHT =50>
<PARAM NAME = "font" VALUE = "Chiller">
<PARAM NAME = "size" VALUE = "24">
<PARAM NAME = "string" VALUE = ""Hello, World ... it's me : ">
</APPLET>
</BODY>
</HTML>

126

Chapter 7
EVENT HANDLING
1. Explain Delegation Event Model ? [Nov Dev 2008] ,[Oct / Nov 2009]

The modern approach to handling event is based on the delegation event


model, which defines standard and consistent mechanisms to generate
and process events.
The delegation event model provides a standard mechanism for a source
to generate an event and send it to a set of listener.

Event
An event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the
elements in a graphical user interface.
Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list
and clicking the mouse.
Events may also occur that are not directly caused by interactions with a
user interface.
For example, an event may be generated when a timer expires, a counter
exceeds a value, software or hardware failure occurs, or an operation is
completed.
We are free to define events that are appropriate for our application.
Event Sources
A source is an object that generates an event.
This occurs when the internal state of that object changes in some way.
Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive
notifications about a specific type of event.
Each type of event has its own registration method. Here is the general
form:
public void addTypeListener(TypeListener el)

Here, type is the name of the event, and el is a reference to the event
listener. For example, the method that registers a keyboard event listener
is called addKeyListener().
The method that registers a mouse motion listener is called
addMotionListener().
When an event occurs, all registered listeners are notified and receive a
copy of the event object.
This is known as multicasting the event. In all cases, notifications are sent
only to listeners that register to receive them.

127

A source must also provide a method that allows a listener to unregister a


specific type of event.

The general form of such a method is this:


public void removeTypeListener(TypeListener el)

Here, type is an object that is notified when an event listener. For example,
to remove a keyboard listener, you would call removeKeyListener().

Button
Checkbox
Choice
List

Menu Item

Scrollbar
Text
Component
Window

Generates action events when the button is pressed.


Generates item events when the check box is selected or
deselected.
Generates item events when the choice is changed.
Generates action events when an item is double-clicked;
Generates item events when an item is selected or
deselected.
Generates action events when a menu item is selected;
Generates item events when a checkable menu item is
selected or deselected.
Generates adjustment events when the scroll bar is
manipulated.
Generates text events when the user enters a character.
Generates window events when a window is activated,
close, deactivated, deiconified, iconified, opened or quit.

Event Listeners
A listener is an object that is notified when an event occurs.
It has two major requirements.
First, it must have been registered with one or more sources to receive
notifications about specific types of events.
Second, it must implement methods to receive and process these
notifications.
The method that receive and process events are defined in a set of
interfaces found in java.awt.event.
2. Explain Event Classes ?
EventObject
The EventObject class extends Object which is in java.util.
It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods:
- getSource()
- toString()
128

The getSource() method returns the source of the event. toString() returns
the string equivalent of the event.

AWTEvent
The AWTEvent class is a subclass of EventObject and is part of the
java.awt package.
AWTEvent is an abstract class.
All of the AWT event types are subclasses of AWTEvent. Constructor for
AWTEvent is as follows:
AWTEvent(Object source, int id)

Here, source is the object that generates the event and id identifies the type
of the event.

Two of its methods are:


int getId()
String toString()

The getId() returns the type of the event, and toString() returns the string
equivalent of the event.

EventObject is a superclass of all events. AWTEvent is a superclass of all


AWT events that are handled by the delegation event model.

The package java.awt.event defines several types of events that are


generated by various user interface elements.

Event Class
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent

KeyEvent
MouseEvent

Description
Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
Generated when a scroll bar is manipulated.
Generated when a component is hidden, moved,
resized, or becomes visible.
Generated when a component is added to or
removed from a container.
Generated when a component gains or loses
keyboard focus.
Abstract subclass for all component input event
classes.
Generated when a check box or list item is clicked
also occurs when a choice selection is made or a
checkable menu item is selected or deselected.
Generated when input is received from the
keyboard.
Generated when the mouse is dragged, moved,

129

MouseWheelEvent
TextEvent
WindowEvent

clicked, pressed, or released, also generated when


the mouse enters or exits a component.
Generated when the mouse wheel is moved.
Generated when the value of a text area or text field
is changed.
Generated when a window is activated, closed,
deactivated, deiconified, iconified, opened or quit.

ActionEvent
An ActionEvent is generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
ActionEvent has these three constructor:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)

Here, src is a reference to the object that generated this event.


The type of the event is specified by type, and its command string is cmd.
The modifiers indicate which modifier keys were pressed when the event
was generated. The when specifies when the event occurred.

AdjustmentEvent
An AdjustmentEvent is generated by a scroll bar.
There are five types of adjustment events.
The AdjustmentEvent class defines integer constants that can be used to
identify them. The constants are:

BLOCK_DECREMENT
BLOCK_INCREMENT
TRACK
UNIT_DECREMENT
UNIT_INCREMENT

The user clicked inside the scroll bar


to decrease its value.
The user clicked inside the scroll bar
to increase its value.
The slider was dragged.
The button at the end of the scroll bar
was clicked to decrease its value.
The button at the end of the scroll bar
was clicked to increase its value.

There is an integer constant, ADJUSTMENT_VALUE_CHANGED, that


indicates that how much a change has occurred.
The constructor is:
AdjustmentEvent(Adjustable src, int id, int type, int data)

ComponentEvent

130

A component Event is generated when the size, position, or visibility of a


component is changed.
The ComponentEvent class defines integer constants that can be used to
identify them.
The constants and their meaning are:

COMPONENT_HIDDEN
COMPONENT_MOVED
COMPONENT_RESIZED
COMPONENT_SHOWN

The component was hidden.


The component was moved.
The component was resized.
The component became visible.

ComponentEvent has this constructor:


ComponentEvent(Component src, int type)
Here, src is a reference to the object that generated this event. The type of the
event is specified by type.
ContainerEvent
ContainerEvent is a subclass of ComponentEvent.
A ContainerEvent is generated when a component is added to or removed
from a container.
There are two types of container events. The ContainerEvent class defines
integer
constants
that
can
be
used
to
identify
them:
COMPONENT_ADDED and COMPONENT_REMOVED. They indicate
that a component has been added to or removed from the container.
Constructor for ContainerEvent is as follows:
ContainerEvent(Component src, int type, Component comp)

Here, src is a reference to the container that generated this event.


The type of the event is specified by type, and the component that has
been added to or removed form the container is comp.

Explain FocusEvent ?

A FocusEvent is generated when a component gains or loses input focus.


These events are identified by the integer constants FOCUS_GAINED and
FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, Boolean tempflag)

Here, src is ref to the component that generated this event.


The type of the event is specified by type.
The argument tempflag is set to true if the focus is temporary, otherwise it
is False.

Explain InputEvent?

131

InputEvent is a subclass of ComponentEvent and is the superclass for


KeyEvent and MouseEvent.

Explain ItemEvent ?

An ItemEvent is generated when a check box or a list item is clicked or


when a checkable menu item is selected or deselected.
There are two types of item events, which are identified by the following
integer constants:
DESELECTED = the user deselected an item
SELECTED = the user selected an item.

Constructor for ItemEvent is as follows:


ItemEvent(ItemSelectable src, int type, Object entry, int state)

Here, src is a reference to the component that generated this event.


The type of the event is specified by type.
The specific item that generated the item event is passed an entry.
The current state of that item is in state.

KeyEvent
A KeyEvent is generated when a keyboard input occurs.
There are 3 types of key event, which are identified by these integer
constants KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first
two events are generated when a key is pressed or released. The last event
occurs only when a character is generated.
MouseWheelEvent
The mouseWheelEvent class encapsulates a mouse wheel event.
It is a subclass of MouseEvent. MouseEvent defines two integer constants:
WHEEL_BLOCK_SCROLL
WHELL_UNIT_SCROLL

A page-up or page-down scroll event


occurred.
A line-up or line-down scroll event
occurred.

The constructor for MouseWheelEvent is as follows:


MouseWheelEvent(Component src, int type, long when, int modifiers, int x,
int y, int clicks, Boolean triggersPopup, int scrollHow, int count)
TextEvent
TextEvent are generated by text fields and text areas when characters
are entered by a user or program. TextEvent defines the integer
constant TEXT_VALUE_CHANGED.
TextEvent(Object src, int type)

Here, src is a reference to the object that generated this event.

132

The type of the event is specified by type.

Explain WindowEvent ?
WindowEvent is a subclass of Component Event. There are ten types of
window event.

WINDOW_ACTIVATED
WINDOW_CLOSED
WINDOW_CLOSING
WINDOW_DEACTIVATED
WINDOW_DEICONIFIED
WINDOW_GAINED_FOCUS
WINDOW_ICONIFIED
WINDOW_LOST_FOCUS
WINDOW_OPENED
WINDOW_STATE_CHANGED

The window was activated.


Window has been closed.
User requested that the window be
closed.
Window was deactivated.
Window was deiconified.
Window gained inpt focus.
Window was iconified.
Window lost input focus.
Window was opened.
The state of the window changed.

ComponentEvent defines several constructors:


WindowEvent(window src, int type)
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromstate, int tostate)
WindowEvent(Window src, int type, Window other, int fromstate, int
tostate)
3. Explain Event Listener Interface ?
The delegation event model has two parts:
sources and listeners.
Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its
argument.
Interface
ActionListener
AdjustmentListener
ComponentListener
FocusListener
ItemListener
keyListener

Description
Defines one method to receive action events.
Defines one method to receive adjustment event.
Defines four methods to recognize when a
component is hidden, moved, resized, or shown.
Defines two methods to recognize when a
component gains or loses keyboard focus.
Defines one method to recognize when the state of an
item changes.
Defines three methods to recognize when a key is
pressed, release, or typed.

133

MouseListener

Defines five methods to recognize when the mouse is


clicked, enters a component, exits a component, is
pressed, or is released
MouseMotionListener Defines two methods to recognize when the mouse is
dragged or moved.
MouseWheelListener
Defines one method to recognize when a the mouse
wheel is moved.
TextListener
Defines one method to recognize when a text value
changes.
WindowFocusListener Defines two methods to recognize when a window
gains or loses input focus.
WIndowListener
Defines seven methods to recognize when a window
is activated, close, deactivated, deicnified, iconified,
opened, or quit.

ActionListener Interface
ActionListener interface defines the actionPerformed() method that is
invoked when an action event occurs.
Its general form is shown here:
Void actionPerformed(ActionEvent ae)

AdjustmentListener Interface
AdjustmentListener interface defines the adjustmentValueChange() method
that is invoked when an adjustment event occurs. Its general form is
Void adjustmentValueChagned(AdjustmentEvent ae)
ComponentListener Interface
ComponentListener interface defines four methods that are invoked when
a component is resized, moved, shown or hidden.
Their general forms are shown here:
Void componentResized(ComponentEvent ce)
Void componentMoved(ComponentEvent ce)
Void componentShown(ComponentEvent ce)
Void componentHidden(ComponentEvent ce)
FocusListener Interface
FocusListener interface defines two methods. When a component obtains
keyboard focus, focusGained() is invoked. When a component loses
keyboard focus, focusLost() is called. Their general form is shown here:
Void focusGained(FocusEvent fe)
Void focusLost(FocusEvent fe)
ItemListener Interface
ItemListener interface defines the itemStateChanged() method that is
invoked when the state of an item changes. Its general form is shown here:
Void itemStateChanged(ItemEvent ie)

134

KeyListener Interface
KeyListener interface defines three methods. The keyPressed() invoked
when key is pressed and keyReleased()invoked when a key is released.
The keyTyped() method is invoked when a character has been entered.

For example, if a user presses and releases the A key, three events are
generated in sequence key pressed, typed and released. If a user presses
and releases the HOME key, two key events are generated in sequence
keypressed and release.

Void keyPressed(KeyEvent ke)


Void keyReleased(KeyEvent ke)
Void keyTyped(KeyEvent ke)

135

Explain MouseListener Interface ?


MouseListener interface defines five methods.
If the mouse is pressed and released at the same point, mouseClicked() is
invoked.
When the mouse enters a component, the mouseEntered() method is
called.
When it leaves, mouseExited() is called. The mousePressed() and
mouseReleased() methods are invoked when the mouse is pressed and
released, respectively.
Void mouseClicked(MouseEvent me)
Void mouseEntered(MouseEvent me)
Void mouseExited(MouseEvent me)
Void mousePressed(MouseEvent me)
Void mouseReleased(MouseEvent me)

MouseMotionListener Interface
MouseMotionListener
interface
defines
two
methods.
The
mouseDragged() method is called multiple times as the mouse is dragged.
The mouseMoved() method is called multiple times as the mouse is
moved. Their general form:
Void mouseDragged(MouseEvent me)
Void mouseMoved(MouseEvent me)
MouseWheelListener Interface
MouseWheelListener interface defines the mouseWheelMoved() that is
invoked when the mouse wheel is moved. Its general form is shown here:
Void mouseWheelMoved(MouseWheelEvent me)
TextListener Interface
TextListener interface defines the textChanged() method that is invoked
when a change occurs in a text area or text field. Its general form is shown
here:
Void textChanged(TextEvent te)

WindowFocusListener Interface
WindowFocusListener
interface
defines
two
methods:
windowGainedFocus() and windowLostFocus().
These are called when a window gains or loses input focus. Their general
forms are shown here:
Void windowGainedFocus(WinowEvent we)
Void windowLostFocus(WindowEvent we)

136

WindowListener Interface
WindowListener interface defines seven methods.
The windowActivated() windowDeactivated() methods are invoked when
a window is activated or deactivated, respectively. If a window is
iconified, the windowIconified() method is called.
When a window is opened or closed, the windowOpened() or
windowClosed() methods are called, respectively. The windowClosing()
method is called when a window is being closed.
Void windowActivated(WindowEvent we)
Void windowClosed(WindowEvent we)
Void windowClosing(WindowEvent we)
Void windowDeactivated(WindowEvent we)
Void windowDeiconified(WindowEvent we)
Void windowIconified(WindowEvent we)
Void windowOpened(WindowEvent we)

5. What is Adapter Classes ? Explain with an Example ?


When we implement an interface in any program then we must
implement all the methods declared in that interface.
For example, in our program we have implemnted MouseListene.
This MouseListener interface declares five methods.
However, it must implement all of the five methods declared by that
interface. This can be inconvenient because if we want to use only one or
two methods then?
Adapter classes make it easy to deal with this situation. An adapter class
provides empty implementations of all methods in a particular listener
interface.
It can be useful if you want to override only some of the methods defined
by that interface.

1.
2.
3.
4.
5.
6.
7.

Adapter Class
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter

Listener Interface
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener

Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

137

/*
<applet code = "event1" width = 400 height = 400>
</applet>
*/
public class event1 extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
event1 e;
public MyMouseAdapter(event1 e)
{
this.e=e;
}
public void mousePressed(MouseEvent me)
{
e.setBackground(Color.red);
e.repaint();
}
public void mouseReleased(MouseEvent me)
{
e.setBackground(Color.green);
e.repaint();
}
}

138

CHAPTER 8
Explain AWT Controls ? With an Exapmple ? [Oct / Nov 2009]

The Java GUI classes are contained in the java.awt package.


AWT package provides full support for user-interface, components like
labels, buttons, checkboxes, textfields, scroll bars, windows, menus, etc.

1. Labels
A label is a string that appears on a graphical user interface. Labels are
passive controls that do not support any interaction with the user.
It can be changed by your program but cannot be changed by a user. The
Label class defines these constructors:
Label()
Label(String str)
Label(String str, int align)
Here, str is the text for the label.

Align is a constant that indicates if the label should be left justified,


centered, or right justified. The constants are LEFT, CENTER, or RIGHT.

Example
import java.applet.*;
import java.awt.*;
/*
<applet code = "label" width = 100 height = 100>
</applet>
*/
public class label extends Applet
{
public void init()
{
String s1 = "Rome1";
String s2 = "Rome2";
String s3 = "Rome3";
Label l1 = new Label(s1, Label.LEFT);
Label l2 = new Label(s2, Label.CENTER);
Label l3 = new Label(s3, Label.RIGHT);
add(l1);
add(l2);
add(l3);
}
}

139

2. Buttons
A button is a component that appears as a push button.
A button is a component that contains a label and that generates an event
when it is pressed. The Button class defines these constructors:
Button()
Button(String str)
Here, str is the text for the button.

An action event is generated each time a button is pressed.


The methods by which objects register and unregistered to receive action
events generated by this component are:
Void addActionListener(ActionListener all)
Void removeActionListener(ActionListener all)

Here, all is an action listener.

An action listener use getActionCommand() method to obtain a command


string associated with an action event generated by the button.
setActionCommand(String str) sets the string that is returned by the
getActionCommand().

Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "awt2" width = 200 height = 200>
</applet>
*/
public class awt2 extends Applet implements ActionListener
{
Label l1;
public void init()
{
Button b1 = new Button("Yellow");
Button b2 = new Button("Red");
Button b3 = new Button("Blue");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
l1=new Label(" ");
add(l1);

140

}
public void actionPerformed(ActionEvent ae)
{
l1.setText(ae.getActionCommand());
}
}

3. Check Box
A check box is a component that combines a label and a small box. It is a
control that is used to turn an option on or off.
A small box can be either checked or unchecked.
The state of a check box is changed by clicking the mouse on the box.
The constructors for the Checkbox are:
Checkbox()
Checkbox(String str)
Checkbox(String str, boolean state)

The first form creates a check box whose label is blank. In second form str
is the text for the check box.
In third form if state is true, a check mark appears in the box.
An item event is generated when the state of a check box changes.
The methods by which other objects register and unregister to receive
these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "awt3" width = 200 height = 200>
</applet>
*/
public class awt3 extends Applet implements ItemListener
{
Label l1;
public void init()
{
Checkbox cb1=new Checkbox("Pink");
cb1.addItemListener(this);
add(cb1);
Checkbox cb2=new Checkbox("Blue");
cb2.addItemListener(this);
add(cb2);
Checkbox cb3=new Checkbox("Black");

141

cb3.addItemListener(this);
add(cb3);
Checkbox cb4=new Checkbox("White");
cb4.addItemListener(this);
add(cb4);
l1=new Label(" ");
add(l1);
}
public void itemStateChanged(ItemEvent ae)
{
Checkbox cb=(Checkbox)ae.getItemSelectable();
l1.setText(cb.getLabel());
}
}
4. Check Box Group
A check box group is a set of check boxes. In this one and only one check
box from the group can be checked at one time.
These check box group are often called radio buttons.
For this type of check box you must first define the group to which they
will belong and then specify that group when you construct the check
boxes. Check box group are objects of type CheckboxGroup.
The check box group defines only one constructor that is:
CheckboxGroup()

The methods by which other objects register and unregister to receive


these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)
Here, il is the item listener.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "awt4" width = 400 height = 400>
</applet>
*/
public class awt4 extends Applet implements ItemListener
{
Label l1;
public void init()
{
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Pink", cbg, true);
cb1.addItemListener(this);

142

add(cb1);
Checkbox cb2=new Checkbox("Blue", cbg, true);
cb2.addItemListener(this);
add(cb2);
Checkbox cb3=new Checkbox("Black", cbg, true);
cb3.addItemListener(this);
add(cb3);
Checkbox cb4=new Checkbox("White", cbg, true);
cb4.addItemListener(this);
add(cb4);
l1=new Label(" ");
add(l1);
}
public void itemStateChanged(ItemEvent ae)
{
Checkbox cb=(Checkbox)ae.getItemSelectable();
l1.setText(cb.getLabel());
}
}
5. Choice
A choice is a component that provides a list of menu items.
When user clicks on a choice, it displays whole list of choice and then a
selection can be made.
It can have only one item selected at a time. Choice shows the currently
selected item. Choice defines only one constructor that is:
Choice()
An item event is generated when a user selects one of the entries in a
choice.
The methods by which other objects register and unregister to receive
these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)
Here, il is the item listener.
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "choice1" width = 400 height = 400>
</applet>
*/
public class choice1 extends Applet implements ItemListener
{
Label l1;

143

public void init()


{
Choice c1 = new Choice();
c1.addItem("Pink");
c1.addItem("Blue");
c1.addItem("Black");
c1.addItem("White");
c1.addItemListener(this);
add(c1);
l1=new Label(" ");
add(l1);
}
public void itemStateChanged(ItemEvent ae)
{
Choice cb=(Choice)ae.getItemSelectable();
l1.setText(cb.getSelectedItem());
}
}
6. List
A list is a component that allows a user to select one or more items.
If the list is large then it will automatically provide scroll bars so that user
may see the entire list.
An action event is generated when a user double-clicks on an item in a
list.
An item event is generated when a user selects or deselects one of the
entries.
The List defines these constructors:
List()
List(int rows)
List(int rows, Boolean multiple)
Here in second form rows is the number of items that are visible to a user.
In third form if multiple is true, a user can select multiple entries from a list.
Otherwise, only one item can be selected.

The methods by which other objects register and unregister to receive


these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)
Here, il is the item listener.
The methods by which other objects register and unregister to receive
action events generated by this component are:
Void addActionListener(ActionListener al)
Void removeActionListener(ActionListener al)
Here, al is an action listener.

144

7. Scrollbar
Scrollbars are used to select any integer values between a specified
minimum and maximum.
A scroll bar contains a slider that can be dragged to continuously vary its
value.
Alternatively, the user can click on one of the buttons at either end of the
scroll bar or in the area between the slider and the buttons.
These operations also modify its value. The Scrollbar class defines these
constructors:
Scrollbars()
Scrollbar(int orientation)
Scrollbar(int orientation, int value, int width, int min, int max)

Scrollbars can be horizontally or vertically oriented. It is assigned the


value HORIZONTAL or VERTICAL.
The argument value represents the initial value of the scroll bar. The width
of the slider is width.
The range of the scroll bar is determined by the min and max arguments.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "scroll1" width = 400 height = 400>
</applet>
*/
public class scroll1 extends Applet implements AdjustmentListener
{
TextArea ta;
public void init()
{
Scrollbar sb1 = new Scrollbar(Scrollbar.VERTICAL,50,25,0,100);
sb1.addAdjustmentListener(this);
add(sb1);
ta = new TextArea(10, 20);
add(ta);
}
public void adjustmentValueChanged(AdjustmentEvent ie)
{
Scrollbar sb1 = (Scrollbar)ie.getAdjustable();
ta.append("AdjustEvent: " + sb1.getValue() + "\n");
}

145

8. TextField
A textfield allows a user to enter one line of text.
Textfield allow the user to enter strings and to edit the text using the
arrow keys, cut and paste keys, and mouse selections.
Textfield defines the following constructors:
TextField()
TextField(String str)
TextField(int cols)
TextField(String str, int cols)

Here, str is the text for the field. The argument cols indicates the width of
the field in character.

If we dont want to display characters use setEchoChar() method.


Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "textfield1" width = 400 height = 400>
</applet>
*/
public class textfield1 extends Applet
{
TextField name, pass;
public void init()
{
Label lnm = new Label("Name : ");
name = new TextField(12);
add(lnm);
add(name);
Label lpass = new Label("Password : ");
pass = new TextField(8);
pass.setEchoChar('=');
add(lnm);
add(name);
add(lpass);
add(pass);
}
}
9. TextArea
A text area allows a user to enter multiple lines of text.
Sometimes a single line of text input is not enough for a given task.

146

To handle these situations, the AWT includes a simple multiline editior


called TextArea. TextArea defines the following constructors:
TextArea()
TextArea(String str)
TextArea(int rows, int cols)
TextArea(String str, int rows, int cols)
TextArea(String str, int rows, int cols, int scrollbars)
Here, str is the text for the area. The rows and cols arguments indicate the
number of rows and columns in the component.
The scrollbars argument indicates if horizontal and/or vertical scroll bars
should be created. Its possible values are:
SCROLLBARS_BOTH,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY
SCROLLBARS_NONE.

Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "textarea1" width = 400 height = 400>
</applet>
*/
public class textarea1 extends Applet
{
public void init()
{
String txt = "A text area allows a user a user to enter \n " +
"multiple lines of text. Sometimes a single line \n" +
"of text input is not enough for a given task. \n" +
"To handle these situations, the AWT includes a \n" +
"simple multiline editor called TextArea. ";
TextArea ta = new TextArea(txt, 10, 30);
add(ta);
}
}
10. Canvas
A canvas provides a rectangular area on which we can draw.
This is valuable because we can create graphs and other diagrams on the
canvas by using methods of the Graphics class.
The Canvas class extends Components. Canvas defines this constructor:
Canvas()

147

One need to override the paint() method to draw on the canvas.


Example
import java.applet.*;
import java.awt.*;
/*
<applet code = "CanvasDemo" width = 400 height = 400>
</applet>
*/
class MyCanvas extends Canvas
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,10,100,50);
}
}
public class CanvasDemo extends Applet
{
public void init()
{
MyCanvas myc = new MyCanvas();
myc.setSize(200,200);
add(myc);
}
}

11. Menu Bars and Menus


A window can have a menu bar associated with it. A menu bar displays a
list of top-level menu choices.
Each choice is associated with a drop-down menu. This concept is
implemented by the following classes:
MenuBar, Menu and MenuItem. In short, a menu bar contains one or more
Menu objects.
Each menu object contains a list of MenuItem objects.
Each MenuItem object represents something that can be selected by the
user.
since Menu is a subclass of MenuItem, a hierarchy of nested submenus can
be created. It is also possible to include checkable menu items.
These are menu options of type CheckboxMenuItem and will have a check
mark next to them when they are selected.

To create a menu bar, first create an instance of MenuBar.


This class only defines the default constructor.

148

Next, create instances of Menu that will define the selections displayed on
the bar. Following are the constructors for Menu:
Menu()
Menu(String optionName)
Menu(String optionName, Boolean removable)

Here, optionName specifies the name of the menu selection.


If removable is true, the pop-up menu can be removed and allowed to
float free.
Otherwise, it will remain attached to the menu bar.

Individual menu items are of type MenuItem. It defines these constructors:


MenuItem()
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)

Here, itemName is the name shown in the menu, and keyAccel is the
menu shortcut for this item.

You can disable or enable a menu item by using the setEnabled() method. Its
form is shown here:
Void setEnabled(Boolean enabledFlag)

If the argument enabledFlag is true, the menu item is enabled.


If false, the menu item is disabled.
You can determine an items status by calling isEnabled(). This method is
shown here:
Boolean isEnabled()
isEnabled() returns true if the menu item on which it is called is enabled.
Otherwise, it returns false.

You can change the name of a menu item by calling setLable(). You can
retrieve the current name by using getLable(). These methods are as
follows:
Void setLabel(String newName)
String getLabel()

Here, newName becomes the new name of the invoking menu item.
getLabel() returns the current name.

You can create a checkable menu item by using a subclass of MenuItem


called CheckboxMenuItem. It has these constructors:
CheckboxMenuItem()
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName, Boolean on)

149

Here, itemName is the name shown in the menu.


Checkable items operate as toggles. Each time is selected, its state changes.
In the first two forms, the checkable entry is unchecked.
In the third form, if on is true, the checkable entry is initially checked.
Otherwise, it is cleared.

You can obtain the status of a checkable item by calling getState().

You can set it to a known state by using setState().

These methods are shown here:


Boolean getState()
Void setState(Boolean checked)

If the item is checked, getState() returns true.


Otherwise, it returns false. To check an item, pass true to setState(). To
clear an item, pass false.

Once you have created a menu item, you must add the item to a Menu
object by using add(), which has the following general form:
MenuItem add(MenuItem item)

Here, item is the item being added.

Once you have added all items to a Menu object, you can add that object to
the menu bar by using this version of add() defined by MenuBar:
Menu add(Menu menu)
Here, menu is the menu being added. The menu is returned.
import java.awt.*;
import java.awt.event.*;
class MainFrame extends Frame
{
MainFrame(String title)
{
super(title);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu file = new Menu("File");
MenuItem New = new MenuItem("New.. ");
MenuItem Open = new MenuItem("Open.. ");
MenuItem Save = new MenuItem("Save.. ");
MenuItem Exit = new MenuItem("Exit.. ");
file.add(New);

150

file.add(Open);
file.add(Save);
file.add(Exit);
Menu sub = new Menu("edit");
MenuItem Cut = new MenuItem("Cut");
MenuItem Copy = new MenuItem("Copy");
MenuItem Paste = new MenuItem("Paste");
sub.add(Cut);
sub.add(Copy);
sub.add(Paste);
file.add(sub);
mb.add(file);
}
public static void main(String args[])
{
MainFrame mf = new MainFrame("Menu");
mf.setSize(300, 300);
mf.setVisible(true);
}
}
12. Dialog Box
Dialog boxes are used to obtain user input. They are similar to frame
windows, except that dialog boxes are always child windows of a top-level
window.
Dialog boxes do not have menu bars. Dialog boxes can be modal or
modeless.
When a modal dialog box is active, all input is directed to it until it is
closed. This means that you cannot access other parts of your program
until you have closed the dialog box.
When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program
remain active and accessible.
Constructors for dialog box are:
Dialog(Frame parentWindow, Boolean mode)
Dialog(Frame parentWindow, String title, Boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the
dialog box is modal. Otherwise, it is modeless. The title of the dialog box can
be passed in title.

151

CHAPTER 9
Explain Swing Layout Controls ? [ Nov / Dec 2008] , [Oct / Nov 2009]

Swing Layout control is use to set the layout


Swing Layout consider many layout as follows
Box Lay out
Example :
import java.awt.*;
import javax.swing.*;
/* <JAPPLET
CODE = boxlayout.class
WIDTH = 250
HEIGHT = 200 >
</JAPPLET>
*/
public class boxlayout extends JJApplet
{
public void init()
{
Container contentPane = getContentPane();
JPanel jpanel1, jpanel2, jpanel3;
jpanel1 = new JPanel();
jpanel2 = new JPanel();
jpanel3 = new JPanel();
jpanel1.setLayout(new BoxLayout(jpanel1, BoxLayout.Y_AXIS));
jpanel2.setLayout(new BoxLayout(jpanel2, BoxLayout.X_AXIS));
jpanel3.setLayout(new BoxLayout(jpanel3, BoxLayout.Y_AXIS));
contentPane.setLayout(new FlowLayout());
jpanel1.add(new JTextField("Text 1"));
jpanel1.add(new JTextField("Text 2"));
jpanel1.add(new JTextField("Text 3"));
jpanel1.add(new JTextField("Text 4"));
jpanel2.add(new JTextField("Text 1"));
jpanel2.add(new JTextField("Text 2"));
jpanel2.add(new JTextField("Text 3"));
jpanel2.add(new JTextField("Text 4"));
jpanel3.add(new JTextField("Text 1"));
jpanel3.add(new JTextField("Text 2"));
jpanel3.add(new JTextField("Text 3"));
jpanel3.add(new JTextField("Text 4"));
contentPane.add(jpanel1);

152

contentPane.add(jpanel2);
contentPane.add(jpanel3);
}
}
Flow Layout
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
/*
<JAPPLET
CODE = box.class
WIDTH = 450
HEIGHT = 400 >
</JAPPLET>
*/
public class box extends JJApplet
{
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JPanel jpanel1 = new JPanel();
jpanel1.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Glue"));
jpanel1.setLayout(new BoxLayout(jpanel1, BoxLayout.X_AXIS));
jpanel1.add(Box.createGlue());
jpanel1.add(new JTextField("Text 1"));
jpanel1.add(Box.createGlue());
jpanel1.add(new JTextField("Text 2"));
jpanel1.add(Box.createGlue());
jpanel1.add(new JTextField("Text 3"));
jpanel1.add(Box.createGlue());
contentPane.add(jpanel1);
JPanel jpanel2 = new JPanel();
jpanel2.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Struts"));
jpanel2.setLayout(new BoxLayout(jpanel2, BoxLayout.X_AXIS));
jpanel2.add(new JTextField("Text 1"));
jpanel2.add(Box.createHorizontalStrut(20));
jpanel2.add(new JTextField("Text 2"));

153

jpanel2.add(Box.createHorizontalStrut(20));
jpanel2.add(new JTextField("Text 3"));
contentPane.add(jpanel2);
JPanel jpanel3 = new JPanel();
jpanel3.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Rigid"));
jpanel3.setLayout(new BoxLayout(jpanel3, BoxLayout.X_AXIS));
jpanel3.add(Box.createRigidArea(new Dimension(10, 40)));
jpanel3.add(new JTextField("Text 1"));
jpanel3.add(Box.createRigidArea(new Dimension(10, 40)));
jpanel3.add(new JTextField("Text 2"));
jpanel3.add(Box.createRigidArea(new Dimension(10, 40)));
jpanel3.add(new JTextField("Text 3"));
contentPane.add(jpanel3);
JPanel jpanel4 = new JPanel();
jpanel4.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Glue"));
jpanel4.setLayout(new BoxLayout(jpanel4, BoxLayout.Y_AXIS));
jpanel4.add(Box.createGlue());
jpanel4.add(new JTextField("Text 1"));
jpanel4.add(Box.createGlue());
jpanel4.add(new JTextField("Text 2"));
jpanel4.add(Box.createGlue());
jpanel4.add(new JTextField("Text 3"));
jpanel4.add(Box.createGlue());
contentPane.add(jpanel4);
JPanel jpanel5 = new JPanel();
jpanel5.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Struts"));
jpanel5.setLayout(new BoxLayout(jpanel5, BoxLayout.Y_AXIS));
jpanel5.add(new JTextField("Text 1"));
jpanel5.add(Box.createVerticalStrut(30));
jpanel5.add(new JTextField("Text 2"));
jpanel5.add(Box.createVerticalStrut(30));
jpanel5.add(new JTextField("Text 3"));
contentPane.add(jpanel5);
JPanel jpanel6 = new JPanel();
jpanel6.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),

154

"Rigid"));
jpanel6.setLayout(new BoxLayout(jpanel6, BoxLayout.Y_AXIS));
jpanel6.add(Box.createRigidArea(new Dimension(40, 60)));
jpanel6.add(new JTextField("Text 1"));
jpanel6.add(Box.createRigidArea(new Dimension(40, 60)));
jpanel6.add(new JTextField("Text 2"));
jpanel6.add(Box.createRigidArea(new Dimension(40, 60)));
jpanel6.add(new JTextField("Text 3"));
contentPane.add(jpanel6);
}
}
1. JLabels [March/April -2009], [Oct / Nov 2009]

A JLabels is a string that appears on a graphical user interface. JLabels s


are passive controls that do not support any interaction with the user.
It can be changed by your program but cannot be changed by a user. The
JLabels class defines these constructors:
JLabel ()
JLabel (String str)
JLabel (String str, int align)

Here, str is the text for the JLabels .

Align is a constant that indicates if the JLabels should be left justified,


centered, or right justified. The constants are LEFT, CENTER, or RIGHT.

Example
import java.JApplet.*;
import java.awt.*;
import java.swing.*;
/*
<JApplet code = "JLabels " width = 100 height = 100>
</JApplet>
*/
public class JLabels extends JApplet
{
public void init()
{
String s1 = "Rome1";
String s2 = "Rome2";
String s3 = "Rome3";
JLabels l1 = new JLabels (s1, JLabels .LEFT);
JLabels l2 = new JLabels (s2, JLabels .CENTER);
JLabels l3 = new JLabels (s3, JLabels .RIGHT);
add(l1);
add(l2);

155

add(l3);
}
}
2. JButtons [March/April -2009] , [Oct / Nov 2009]

A JButton is a component that appears as a push JButton.


A JButton is a component that contains a JLabels and that generates an
event when it is pressed. The JButton class defines these constructors:
JButton()
JButton(String str)
Here, str is the text for the JButton.

An action event is generated each time a JButton is pressed.


The methods by which objects register and unregistered to receive action
events generated by this component are:
Void addActionListener(ActionListener all)
Void removeActionListener(ActionListener all)

Here, all is an action listener.

An action listener use getActionCommand() method to obtain a command


string associated with an action event generated by the JButton.
setActionCommand(String str) sets the string that is returned by the
getActionCommand().

Example
import java.JApplet.*;
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
/*
<JApplet code = "awt2" width = 200 height = 200>
</JApplet>
*/
public class awt2 extends JApplet implements ActionListener
{
JLabels l1;
public void init()
{
JButton b1 = new JButton("Yellow");
JButton b2 = new JButton("Red");
JButton b3 = new JButton("Blue");

156

add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
l1=new JLabels (" ");
add(l1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText(ae.getActionCommand());
}
}

3. JCheck Box [March/April -2009] , [Oct / Nov 2009]

A check box is a component that combines a JLabels and a small box. It is


a control that is used to turn an option on or off.
A small box can be either checked or unchecked.
The state of a check box is changed by clicking the mouse on the box.
The constructors for the JCheckbox are:
JCheckbox()
JCheckbox(String str)
JCheckbox(String str, boolean state)
The first form creates a check box whose JLabels is blank. In second form
str is the text for the check box.
In third form if state is true, a check mark appears in the box.
An item event is generated when the state of a check box changes.
The methods by which other objects register and unregister to receive
these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)

import java.JApplet.*;
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
/*
<JApplet code = "awt3" width = 200 height = 200>
</JApplet>
*/
public class awt3 extends JApplet implements ItemListener

157

{
JLabels l1;
public void init()
{
JCheckbox cb1=new JCheckbox("Pink");
cb1.addItemListener(this);
add(cb1);
JCheckbox cb2=new JCheckbox("Blue");
cb2.addItemListener(this);
add(cb2);
JCheckbox cb3=new JCheckbox("Black");
cb3.addItemListener(this);
add(cb3);
JCheckbox cb4=new JCheckbox("White");
cb4.addItemListener(this);
add(cb4);
l1=new JLabels (" ");
add(l1);
}
public void itemStateChanged(ItemEvent ae)
{
JCheckbox cb=(JCheckbox)ae.getItemSelectable();
l1.setText(cb.getJLabels ());
}
}
4. Check Box Group [March/April -2009] , [Oct / Nov 2009]

A check box group is a set of check boxes. In this one and only one check
box from the group can be checked at one time.
These check box group are often called radio JButtons.
For this type of check box you must first define the group to which they
will belong and then specify that group when you construct the check
boxes. Check box group are objects of type JCheckboxGroup.
The check box group defines only one constructor that is:
JCheckboxGroup()

The methods by which other objects register and unregister to receive


these events are as follows:
Void addItemListener(ItemListener il)
Void removeItemListener(ItemListener il)
Here, il is the item listener.
import java.JApplet.*;
import java.awt.*;
import java.awt.event.*;

158

import java.swing.*;
/*
<JApplet code = "awt4" width = 400 height = 400>
</JApplet>
*/
public class awt4 extends JApplet implements ItemListener
{
JLabels l1;
public void init()
{
JCheckboxGroup cbg = new JCheckboxGroup();
JCheckbox cb1 = new JCheckbox("Pink", cbg, true);
cb1.addItemListener(this);
add(cb1);
JCheckbox cb2=new JCheckbox("Blue", cbg, true);
cb2.addItemListener(this);
add(cb2);
JCheckbox cb3=new JCheckbox("Black", cbg, true);
cb3.addItemListener(this);
add(cb3);
JCheckbox cb4=new JCheckbox("White", cbg, true);
cb4.addItemListener(this);
add(cb4);
l1=new JLabels (" ");
add(l1);
}
public void itemStateChanged(ItemEvent ae)
{
JCheckbox cb=(JCheckbox)ae.getItemSelectable();
l1.setText(cb.getJLabels ());
}
}
7. JScrollbar [March/April -2009] , [Oct / Nov 2009]

JScrollbars are used to select any integer values between a specified


minimum and maximum.
A scroll bar contains a slider that can be dragged to continuously vary its
value.
Alternatively, the user can click on one of the JButtons at either end of the
scroll bar or in the area between the slider and the JButtons.
These operations also modify its value. The JScrollbar class defines these
constructors:
JScrollbars()

159

JScrollbar(int orientation)
JScrollbar(int orientation, int value, int width, int min, int max)

JScrollbars can be horizontally or vertically oriented. It is assigned the


value HORIZONTAL or VERTICAL.
The argument value represents the initial value of the scroll bar. The width
of the slider is width.
The range of the scroll bar is determined by the min and max arguments.

import java.JApplet.*;
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
/*
<JApplet code = "scroll1" width = 400 height = 400>
</JApplet>
*/
public class scroll1 extends JApplet implements AdjustmentListener
{
TextArea ta;
public void init()
{
JScrollbar
sb1
=
JScrollbar(JScrollbar.VERTICAL,50,25,0,100);
sb1.addAdjustmentListener(this);
add(sb1);
ta = new TextArea(10, 20);
add(ta);
}
public void adjustmentValueChanged(AdjustmentEvent ie)
{
JScrollbar sb1 = (JScrollbar)ie.getAdjustable();
ta.append("AdjustEvent: " + sb1.getValue() + "\n");
}

new

}
11. Menu Bars and Menus [March/April -2009] , [Oct / Nov 2009]

A window can have a menu bar associated with it. A menu bar displays a
list of top-level menu choices.
Each choice is associated with a drop-down menu. This concept is
implemented by the following classes:

160

MenuBar, Menu and MenuItem. In short, a menu bar contains one or more
Menu objects.
Each menu object contains a list of MenuItem objects.
Each MenuItem object represents something that can be selected by the
user.
since Menu is a subclass of MenuItem, a hierarchy of nested submenus can
be created. It is also possible to include checkable menu items.
These are menu options of type JCheckboxMenuItem and will have a
check mark next to them when they are selected.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.swing.*;
/*
<JAPPLET
CODE = menu.class
WIDTH = 350
HEIGHT = 280 >
</JAPPLET>
*/
public class menu extends JJApplet implements ActionListener
{
public void init()
{
JMenuBar jmenubar = new JMenuBar();
JMenu jmenu1 = new JMenu("File");
JMenuItem jmenuitem1 = new JMenuItem("New..."),
jmenuitem2 = new JMenuItem("Open..."),
jmenuitem3 = new JMenuItem("Exit");
jmenu1.add(jmenuitem1);
jmenu1.add(jmenuitem2);
jmenu1.addSeparator();
jmenu1.add(jmenuitem3);
jmenuitem1.setActionCommand("You selected New");
jmenuitem2.setActionCommand("You selected Open");
jmenuitem1.addActionListener(this);
jmenuitem2.addActionListener(this);
JMenu jmenu2 = new JMenu("Edit");
JMenuItem jmenuitem4 = new JMenuItem("Cut"),
jmenuitem5 = new JMenuItem("Copy"),
jmenuitem6 = new JMenuItem("Paste");
jmenu2.add(jmenuitem4);
jmenu2.add(jmenuitem5);
jmenu2.add(jmenuitem6);

161

jmenuitem4.setActionCommand("You selected Cut");


jmenuitem5.setActionCommand("You selected Copy");
jmenuitem6.setActionCommand("You selected Paste");
jmenuitem4.addActionListener(this);
jmenuitem5.addActionListener(this);
jmenuitem6.addActionListener(this);
jmenubar.add(jmenu1);
jmenubar.add(jmenu2);
setJMenuBar(jmenubar);
}
public void actionPerformed(ActionEvent e)
{
JMenuItem jmenuitem = (JMenuItem)e.getSource();
showStatus(jmenuitem.getActionCommand());

162

You might also like