Java
Java
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.
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.
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.
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 (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.
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.
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;
}
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>
}
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
The execution continues with the statement having the label. This is equivalent
to a goto statement.
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(" ");
}
}
}
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.
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
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.
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};
14
Char
ch[]
={A,B,C,D};
declares an array ch
to store 4 pre-as
signed
character
values.
Meaning
Addition
Subtraction
Multiplication
Division
Modulus
Example
8 + 10
10 8
20 * 84
10 / 5
10 % 6
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
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.
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.
Only if the all the conditions are false, the expression is false. Consider the
following statement
semesterAverage >= 90 | | finalExam >= 90
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
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
19
20
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
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);
}
}
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
}
}
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.
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);
}
}
A method can return any type of data, including class type (object) that
you create.
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();
}
}
[1] Call-by-Value
This method copies the value of an argument into the formal parameter
of the subroutine.
28
[2] Call-by-Reference
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
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
Public
Yes
Protected
Yes
Default
Yes
Private
Yes
Yes
Yes
Yes
No
Yes
No
No
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
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.
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);
}
}
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.
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();
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.
39
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
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
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
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
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
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)
Example
import java.util.*;
class boolean1
{
public static void main(String args[])
{
Boolean b1 = new Boolean(true);
48
Tips
o Constants defined in Java are called literals.
o Characters defined in Java are called Unicode characters.
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.)
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.
Method
Void clear()
Boolean containsKey(Object key)
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
Boolean isEmpty( )
Enumeration keys( )
Object put(Object key Object value)
Object remove(Object key)
Int size( )
String toString( )
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
marks:
"
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
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( )
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:
54
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)
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
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
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
}
}
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
}
}
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
61
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);
}
}
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
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.
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());
}
}
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.
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.
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();
}
}
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.
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]
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
result2 = num1/(num2+num3);
System.out.println("Result2 = " + result2);
}
}
Example
// Multiple catch
class etion2
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
82
try
{
result1 = num1/(num2-num3);
83
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.
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
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
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
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
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.
94
95
**
"
"
+
+
"
}
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
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;
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.
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();
100
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)
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()
105
[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
106
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)
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.
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
}
}
}
[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.
[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.
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);
}
}
}
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
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.
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
Explain FileInputStream ?
Here, filepath is the full path name of a file and object is a File object that
describes the file.
Explain FilterInputStream ?
114
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.
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 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
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.
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())
119
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;
}
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
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.
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);
}
}
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.
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.
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
126
Chapter 7
EVENT HANDLING
1. Explain Delegation Event Model ? [Nov Dev 2008] ,[Oct / Nov 2009]
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
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
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.
The getId() returns the type of the event, and toString() returns the string
equivalent of the event.
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
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)
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
ComponentEvent
130
COMPONENT_HIDDEN
COMPONENT_MOVED
COMPONENT_RESIZED
COMPONENT_SHOWN
Explain FocusEvent ?
Explain InputEvent?
131
Explain ItemEvent ?
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
132
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
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
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.
135
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)
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]
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.
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.
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()
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
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)
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.
146
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
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, 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)
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.
149
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)
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]
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]
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]
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());
}
}
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()
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]
159
JScrollbar(int orientation)
JScrollbar(int orientation, int value, int width, int min, int max)
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
162