Java Points
Java Points
UNIT I
Data Types, Variables , Arrays and Operators: Primary types – Integers
– Floating point types – Characters – Booleans – A Closer Look at Literals
– Variables – Type Conversion and Casting – Automatic type Promotion in
Expressions - One Dimensional Arrays– Multi Dimensional Arrays-
Operators & its types.
Unit II:
Unit III
Packages and Interfaces: Packages – Access Protection – Importing
Packages – Interfaces.
Unit IV
The Applet Class: Applet Basics – Applet Architecture – Applet Skeleton –
Applet Display Methods – Requesting Repainting – HTML APPLET tag.
1
Event Handling: Event Handling Mechanisms – Delegation Event Model –
Event Classes – Sources of Events – Event Listener Interfaces – Handling
Mouse Events and Keyboard Events.
Unit V
Graphics: Working with Graphics – Working with color – Working with
Fonts
TEXT BOOK:
Java2, The Complete Reference 8/e , Herbert Schildt, TMH
REFERENCE BOOK:
1. Java Programming A Practical Approach, C.Xavier, TMH
University Press
2
Contents
Unit Chapter Page No.
No
1 Data Types 5
1 Variables 7
1 Arrays 9
1 Operators 15
1 Introducing Classes 22
2 Methods and Classes 30
2 Inheritance 48
3 Packages 63
3 Interfaces 68
3 Exception Handling 70
3 Multithreaded Programming 75
4 The Applet Class 82
4 Event Handling 89
5 Graphics 100
5 AWT Controls 107
3
Unit I
INTRODUCTION
Java:
Java was conceived by James Gosling and his team at Sun Micro Systems, Inc in 1991.
This language was initially called “Oak” and in 1995 it was renamed as “Java”. Java
supports Application programs and Applet programs. An Application program is one that
can be run on your computer with its operating system. An Applet is an application
designed to be transmitted over the internet and executed by a Java-compatible web
browser.
Bytecode:
Java needs a compiler and an interpreter. The java source program is passed to a
compiler and the output of the java compiler is a bytecode. The bytecode is a highly
optimized set of instructions designed to be executed by the java run-time system,
which is the Java Virtual Machine (JVM). The bytecode can be executed by any
interpreter. It is machine independent and architecture neutral ie byte can be executed
by IBM interpreter, SUN interpreter, SPARC interpreter …etc.
Java is a fully object oriented language. All java programs must have class. The three
OOP principles are Encapsulation, Inheritance and Polymorphism.
Encapsulation: It is the process that binds together code and the data it
manipulates. The basis of encapsulation is the class. In a class the user will
specify the code and the data. An object is the instance of the class.
4
DATA TYPES, VARIABLES, ARRAYS and OPERATORS
5
1.2.5 Floating-Point Literals: There are two types of floating point literals. They are
float literal or double literal: Any floating point number appended with f or F is float
literal. A double literal is any floating point number appended with d or D. Double literal
is the java‟s default floating point literal.
Example Float literal: 3.14f -8.9F 6.785F -4.53f
Double literal: 23.8976D 345.98765d -56.245D -7.8643d
1.2.6 Boolean Literals: Boolean literals can take any boolean value true or false.
Example: true false
1.2.7 Character Literals: A character literal is a character enclosed within a single
quote.
Example: „2‟ „A‟ „\n‟ „c‟
1.2.8 String Literals: A siring literal is a group of characters or a character enclosed
within double quotes.
Example: “123” “A” “CVD” “7” “nhg\nbc”
1.3 Variables:
Variable is a quantity whose value can be changed program execution. It is an
identifier that denotes a storage location used to store a data value. A variable name
may consists of alphabets, digits or underscore.
1.3.1 Variable Declaration: The general form of variable declaration is given below.
type variable-name1, variable-name2 ….nariable-namen;
Example:
int x,y,z;
float a,b;
double d1,d2;
char c1,c2;
boolean b1,b2;
1.3.2 Initialization:
The initialization can be done in either compile time or at execution(dynamically).
Dynamic initialization can be done through any valid expression at the time of variable
declaration. The general form is given below.
type variable = value;
6
type variable = expression;
Example:
int max=400;
int min=200;
double pi=3.14;
boolean result = true;
int c=max – min;
In an expression, if the precision required for a intermediate value exceeds the range of
the either operand, Java automatically promotes the operand to next higher type. For
example the byte or short type operand can be converted to int when evaluating the
expression.
Example:
byte x,y;
int ,z;
x=100;
7
y=75;
z=x * y + 25;
In the above example the intermediate term x * y exceeds the range of either of its byte
operands. Here Java automatically converts byte to short or int.
1.5.1 Type Promotion Rules:
In java, type promotion rule says that all byte and short values are promoted to int. If
one of the operand is a long, the whole expression is promoted to long. If one operand
is a float, the entire expression is promoted to float. If any one of the operand is double,
the result is in double.
1.6 One Dimensional Arrays:
An array is a group of similar data typed variables that shares a common name. The
elements of the array are accessed by the array index. The array index must begin in
zero to n-1, where n is the number of elements in the array. The array index should be a
positive integer vale. An array may be one-dimensional or multidimensional it may be of
any type ie int, float, double, char, String, objects …..
1.6.1Declaration:
A one-dimensional array is a list of similar typed variables. It can be accessed with one
array index. The one-dimensional array can be declared as follows.
Example:
In the above example a is an integer array of size 10, n is a double type array of
size 5 and s is a String array of size 7.
8
Example:
int a[ ] = { 10, 34,22,56,21};
In the above example the integer values are assigned as a[0]=10, a[1]=34,
a[2]=22, a[3]=56 and a[4]=21.
String s[ ] = { “Anand”, “Bala”, “Jhon Samuel”, “Hayes”};
In the above example the String objects are assigned as s[0]=”Anand”;
s[1]=”Bala”, s[2]=”Jhon Samuel”, s[3]=”Hayes”
1.6.3 Array Output:
The elements of the array can be accessed with the array index and a loop statement.
Example:
int b[ ]= { 34,23, 11, 67,23};
System.out.println(“ Array Elements”);
for(i=0; i<5; i++)
System.out.println(b[i]);
1.6.4 Array Processing:
The following example illustrates the array processing.
int b[ ]= { 34,23, 11, 67,23};
int s=0;
for(i=0; i<5; i++)
s=s+b[i];
System.out.println(“Sum of the elements = “ +s);
Example: Java program to arrange the given set of numbers in ascending order.
import java.io.*;
class Sort {
int a[ ]={3,5,1,-8,2};
int i,j,t;
void sorting( ) {
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
if(a[i]>a[j]) {
t=a[i];
9
a[i]=a[j];
a[j]=t;
}
}
void output( ) {
for(i=0;i<5;i++)
System.out.println(a[i]);
}
}
class Arraysort {
public static void main(String arg[ ]) {
Sort s1=new Sort( );
System.out.println("Before Sorting");
s1.output( );
s1.sorting( );
System.out.println("After Sorting");
s1.output( );
}
}
Example:
10
String name[ ][ ]= new String[3][20];
1.7.2 Input:
The matrix elements can be assigned directly along with the declaration. This is
called initialization of arrays. The values can also be assigned during execution by the
user.
Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
In the above example the integer values are assigned as a[0][0]=1, a[0][1]=2,
a[0][2]=3, a[1][2]=4 ….a[2][2]=9.
1.7.3 Output:
The elements of the matrix can be printed in the matrix format array index and two loop
statements.
Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
System.out.println(“ Matrix);
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j]+” “]);
System.out.println(“ “);
}
1.7.4 Processing:
The following example illustrates the matrix processing.
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
int b[ ][ ]= { {11,22,33},{44,55,66},{77,88,99}};
int c[ ][ ] = new int[3][3];
11
for(i=0; i<3; i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
import java.io.*;
class Retobj {
int r,c,i,j;
r=r1;
c=c1;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
a[i][j]=Integer.parseInt(x.readLine());
12
for(i=0;i<r;i++)
for(j=0;j<c;j++)
t.a[i][j]=a[i][j]+b1.a[i][j];
return(t);
void output( ) {
for(i=0;i<r;i++) {
for(j=0;j<c;j++)
System.out.print(a[i][j]+" ");
System.out.println(" ");
class Mataddretobj {
m1.input( ) ;
m2.input( );
m3=m1.sum(m2);
13
m1.output();
m2.output();
m3.output();
1.8 Operators:
1.8.1 Arithmetic Operators:
* Multiplication
/ Division
% Modulo division
++ Increment
__ Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
14
/= Division assignment
double x,y,z;
x=15.3;
y=2.0;
z=x % y;
int n,p;
n=5;
p=++n;
int n,p;
n=5;
p=n++;
Example2 and Example3 shows the difference between prefix increment and
postfix increment operator.
15
Example4: Addition assignment
int x,y;
x=5;
x+=23;
Operator Meaning
| Bitwise OR
& Bitwise AND
~ Bitwise NOT
^ Bitwise XOR
>> Right Shift
<< Left Shift
>>> Right Shift with zero fill
>>= Right Shift assignment
<<= Left Shift assignment
>>>= Right Shift zero fill assignment
^= Bitwise XOR assignment
|= Bitwise OR assignment
&= Bitwise AND assignment
Example: Bitwise AND
a = 1010; // Binary number
b = 1101;// Binary number
c= a & b;
16
c= (1010) & (1101);
c= 1000;
Bitwise OR
d=a | b;
d=(1010) | (1101);
d = 1111;
Right Shift
x=b >> 2;// Perform two times right shift operation to b and assign to x.
Now, x= 0011;// Binary
Similarly other bitwise operations can be performed.
Operator Meaning
== Equality
!= Not equal to
Example:
int a,b;
a=10;
b=20;
17
if(a>b)
else
Operator Meaning
| Logical OR
& Logical AND
^ Logical XOR
&& Short circuit AND
|| Short circuit OR
! Logical NOT
|= OR assignment
&= AND assignment
^= XOR assignment
== Equality
!= Not equal to
?: Conditional (Ternary Operator)
Example1:
boolean x=false;
boolean y=true;
boolean z=true;
boolean d;
d=x|y;
System.out.println(“Boolean OR:” + d);// true
18
d=x & z;
System.out.println(“Boolean AND:” + d);// false
Example2: Short circuit AND – Used to combine two relational expressions
int m1,m2;
m1=50;
m2=67;
if((m1>=40) &&(m2(>=40)) // short circuit AND
System.out.println(“Pass”);
else
System.out.println(“Fail” );
1.8.5 Assignment Operator:
Used to assign a value or to assign an expression to a variable.
Variable = value;
Variable = Expression;
Example:
int x,y,s;
x=10;
y=20;
s=x+y;
19
x=(a>b)?a:b;
In the above example, if the condition is true then the value of a is assigned to x,
otherwise (else) the value of b is assigned to x. Here the condition is false, so the value
of b is assigned to x.
Operators in java have its own priority. It is essential to understand the priority to write
the correct expressions. Parentheses can change the priority of the operators inside
them. Precedence of the java operators are mentioned below.
Highest Priority
() []
++ --
* / %
+ -
20
INTRODUCING CLASSES
1.10 Class Fundamentals:
Java is a fully object oriented programming language. It means that any program written
using java must be encapsulated within a class. Class defines a new data type. Once it
is created, that can be used to create objects. The class is a template for an object. The
object is an instance of a class. A class is declared using the keyword class.
Generally a class consists of instance variables and methods. The variables declared
within a class are called instance variable. The methods contain codes to access the
instance variables of the class. The instance variables and methods declared within a
class are called members of the class.
----------
Example:
class Student
int rollnum;
21
double height, weight;
String name;
void input( ) {
rollnum=2001;
height=172.5;
weight=76.8;
name=”Arun”;
void output( ) {
System.out.println(“Name = “+name);
System.out.println(“Height = “+ht);
System.out.println(“Weight = “+wt);
1.11 Declaring Objects:Objects are the instance of a class or run time entity of a
class. The members of a class are accessed by the object and the dot(.) operator.
Object of a class can be created in two steps. First create a reference variable, then
allocate memory to the object using new operator. The general form is given below.
(or)
22
class-name object-name = new class-name( );
Example1
Example2:
S1 is the object of the class type Student. Similarly we can create any number of
objects.
Object reference variables can act differently when an object is assigned. In the
following example s1 is the object of the class Student and s2 is a reference variable of
the class Student. There is no separate memory for it. When an object is assigned to a
reference variable, s2 did not allocate any memory or copy of the original object s1.
Student s2=s1;
In java class consists of instance variables and methods. Methods consist of set of
statements to access the instance variables and to perform a particular task. The
general form of a method is given below.
type method-name(arguments)
{ // Body of method
return value;
23
Type specifies the type of the data returned by the method to the calling method. The
type may be int, double, float, char, boolean, String or class-name(for object) and void
for return nothing. The return statement can be used to return a value to the calling
method.
Example:
class Demo {
int x, y, s;
x=x1;
y=y1;
int output( ) {
sx+y;
System.out.println(“x= “+x);
System.out.println(“y= “+y);
return s;
Explanation:
In the above program the Demo class consists of the instance variable x, y ,s and the
methods input( ) and output( ). The input( ) takes two arguments of type int. The
output( ) has a return type int. The return statement in the output( ) returns the value s
to the calling method.
24
1.14 Constructor:
A Constructor is similar to a method and it can be used to initialize the members of the
class. It initializes the members immediately upon creation. A Constructor is having the
same name as class name. It has no return type even void. Constructors are executed
automatically immediately after the object is created. Constructors without argument are
called default constructor. The default constructor automatically initializes all instance
variables to zero. Constructor with argument are called parameterized constructor.
Constructors can be overloaded like other methods. The general form of a constructor is
given below.
class Class-name
// Instance variables;
Class-name( ) //Constructor
------------
// inizialization
-----------------
type methodname( )
25
Example:
class Demo {
int x, y, s;
Demo( ) {
x=25;
y=35;
s=0;
void output( ) {
s=x+y;
System.out.println(“x= “+x);
System.out.println(“y= “+y);
System.out.println(“Sum y= “+s);
class Mdemo {
d.output( );
26
Explanation:
In the above program Demo( ) is the constructor and it has no arguments. The
constructor Demo( ) is used to initialize the instance variables x = 25, y = 35 and s=0.
The above constructor is executed immediately after the object d is created.
class Class-name {
// Instance variables;
// inizialization
type methodname( ) {
Example:
class Demo {
int x, y, s;
x=x1;
27
y=y1;
s=0;
void output( ) {
s=x+y;
System.out.println(“x= “+x);
System.out.println(“y= “+y);
System.out.println(“Sum y= “+s);
class Mdemo {
d.output( );
Explanation:
In the above program Demo( ) is the constructor and it has two arguments. The
constructor Demo( ) is used to initialize the instance variables x = x1, y = y1 and s=0.
The above constructor is executed immediately after the object d is created and assigns
the value to the variables x and y.
28
Unit II
import java.io.*;
class Ovload {
double l,b,s,r;
double a;
a=s1*s1;
System.out.println("Side="+s1);
System.out.println("Area of Square="+a);
double a;
a=l1*b1;
System.out.println("Length="+l1);
29
System.out.println("Breadth="+b1);
System.out.println("Area of Rect="+a);
double a;
a=pi*r1*r1;
System.out.println("Radius="+r1);
System.out.println("Area of Circle="+a);
class Movload {
Ovload d1,d2,d3;
d1=new Ovload( );
d2=new Ovload( );
d3=new Ovload( );
d1.area(10.0);
d2.area(10.0,20.0);
d3.area(3.14, 10.0,10.0);
30
Explanation: In the above example the class ovload contains a method area( ) with
three different signatures. The method area( ) will be called based on their signature.
import java.io.*;
class Consovload {
double l,b,s,r;
Consovload(double s1) {
double a;
a=s1*s1;
System.out.println("Side="+s1);
System.out.println("Area of Square="+a);
double a;
a=l1*b1;
System.out.println("Length="+l1);
System.out.println("Breadth="+b1);
31
System.out.println("Area of Rect="+a);
double a;
a=pi*r1*r1;
System.out.println("Radius="+r1);
System.out.println("Area of Circle="+a);
class Mconsovload {
Explanation: In the above example the class Consovload contains a three constructors
with different number of arguments. The constructors will be executed based on the
number of arguments.
The simple types int, char, float, double are used as parameters. It is also possible to
pass an object to methods. Similarly we can also use object as parameter in a
32
constructor or in a method. In the given below example the c1, c2 and c3 are the
objects of the class Complex. The object c3 is passed as argument in the method
process( ).
import java.io.*;
class Complex {
double rp,ip;
Complex( ) {
rp=0.0;
ip=0.0;
rp=rp1;
ip=ip1;
void process(Complex c)
t.rp=rp+c.rp;
t.ip=ip+c.ip;
if(t.ip>=0)
33
else
void output( ) {
if(ip>=0)
else
class Pasobj {
c1.input(5,7);
c2.input(2,-3);
c1.output( );
c2.output( );
c1.process(c2);
} }
34
2.4 Argument Passing:
In java there are two ways to pass an argument to methods. They are call-by- value and
call-by-reference. In call-by reference method the value of an argument is copied into
the formal parameters of the method. The changes made to the formal parameter have
no effect on the argument. In call-by-reference method a reference to an argument is
passed to the parameter. The changes made to the formal parameter will also have the
effect in the argument used to call the method.
Example: Call-by-value
import java.io.*;
class Pasval {
int x,y;
x1*=2;
y1/=2;
System.out.println("x="+x1);
System.out.println("y="+y1);
class Mpasval {
p1.input(10,20);
} }
35
Example: Call-by-reference
import java.io.*;
class Pasref {
int x,y;
x=x1;
y=y1;
System.out.println("x="+x);
System.out.println("y="+y);
void input(Pasref p) {
p.x*=2;
p.y/=2;
System.out.println("x="+x);
System.out.println("y="+y);
class Mpasref {
36
System.out.println("x="+p1.x);
System.out.println("y="+p1.y);
p1.input(p1);
System.out.println("x="+p1.x);
System.out.println("y="+p1.y);
In java a method can return any type of data ie class type, integer, character, double,
float, String or Boolean. If any method returns a class type data then it is called
returning object. In this case the receiving type must be the same class type. In the
example c1, c2 and c3 are the objects of the class Complex. The object c2 is passed as
argument by the method process( ). The method process( ) performs the complex
number addition and it returns the object t of the class Complex to the main( ).
Example: Complex number addition using passing object and returning object.
import java.io.*;
class Complex {
double rp,ip;
Complex( ) {
rp=0.0;
ip=0.0;
37
void input(double rp1, double ip1) {
rp=rp1;
ip=ip1;
Complex process(Complex c) {
t.rp=rp+c.rp;
t.ip=ip+c.ip;
return(t);
void output( ) {
if(ip>=0)
else
class Retobj {
38
Complex c3=new Complex( );
c1.input(23.2,9.7);
c2.input(6.4,8.0);
c1.output( );
c2.output( );
c3=c1.process(c2);
c3.output( );
2.6 Recursion:
import java.io.*;
class Recur {
long f;
long fact(int n) {
if (n==1)
return 1;
else
f=n*fact(n-1);
39
return f;
class Mrecur {
long f1;
f1=r.fact(5);
Access control prevents the misuse of data and methods in java. Access specifier
determines how a member can be accessed? in a class. Java supports three access
specifiers. They are public, private and protected. If no access specifier is used, then by
default the members of the class are public within its own package.
public specifier- The public members can be accessed by the members (methods and
objects) of the class where it is declared and it can also be accessed by the methods
outside the class.
Example:
private specifier- The private members can be accessed only by the members of the
class where it is declared.
40
Example:
protected specifier- The protected members are similar to private members except that
it can be accessed by the sub-class members (used in inheritance).
Example:
Example: The following program demonstrates the use of the various access
specifiers.
import java.io.*;
import java.lang.*;
class Demoaccs {
int a;
public int b;
private int c;
void output( ) {
System.out.println("a= "+a);
System.out.println("b= "+b);
System.out.println("c= "+c);
class Mdemoaccs {
41
Demoaccs d=new Demoaccs( );
d.a=60;
d.b=20;
d.output( );
Explanation: In the above program the class Demoaccs contains the instance variables
a is public (default) ,b is public and c is private. The default and public variables can be
accessed from outside the class ie the value for a nd b are assigned in main( ). An
attempt to assign the value to c creates error, since c is a private member. The private
member can be accessed by the constructor or methods of that class.
In java the member of the class must be accessed with the object of that class. It is also
possible to access the member without its object. When we declare a member as static,
it can be accessed directly without reference to any object. The keyword static can be
used to declare both the instance variables and methods of the class as static member.
The static methods can access only static members but the non-static methods can
access both static and non static instance variables.
Class Demoddce {
System.out.println(“Main as staic”);
} }
42
In java the main( ) declared as static since it must called before any object is created.
(i) Static instance variables of a class are shared by all the objects of that class.
(ii) Static methods can access only static instance variables or other static methods.
(iii) Static members cannot refer to this or super( ).
import java.io.*;
import java.lang.*;
class Demostat {
static int a;
static int b;
a=a1;
b=b1;
System.out.println("a= "+a);
System.out.println("b= "+b);
class Mdemostat {
43
Demostat d=new Demostat(10,20);
Demostat.output( );
Explanation: The class Demostat contains the static members a, b and the method
output( ). Using the static method output( ) the static instance variables are accessed.
An attempt to made by a non static instance variable creates an error.
The keyword final can be used to declare a variable as constant. It will not permit to
modify the value of a variable. The final variable must be initialized, when it is declared.
In the example the instance variables are declared constants by the keyword final. The
method output( ) is also declared final. An attempt to change the value of x in output( )
creates an error. Since x is a constant.
Import java.io.*;
class Demofinal
44
x = x+y; //Error since x is a final variable
Command line arguments are useful to pass data to main ( ) when you run the program.
The command line argument is the data that is directly next to program‟s name on the
command line. All data can be treated as String object. String object can be converted
to appropriate data types musing suitable methods.
Example:
In the above example 10, 2.3 and “Raja “ are the data items passed to main( ) using the
command line arguments.
Example: Java program to find the sum of two numbers using command line argument.
import java.io.*;
class Cmdlnarg {
int x,y,s;
45
void input(int x1, int y1) {
x=x1;
y=y1;
void display( ) {
s=x+y;
System.out.println("X="+x);
System.out.println("y="+y);
System.out.println("Sum ="+s);
class Mcmdlnarg {
int xx,yy;
xx=Integer.parseInt(arg[0]);
yy=Integer.parseInt(arg[1]);
d.input(xx,yy);
d.display( );
46
Explanation: In the above example the value of xx and yy are passed through command
line. Integer.parseInt( ) method can be used to convert the String object into integer type
data. The input( ) is used to assign the value of x and y. The display method computes
the sum of x and y and it display the values.
INHERITANCE
2.11 Inheritance:
Is the process of creating a new class with the traits of existing class. The existing
class (inherited class) is called super class and the newly created class (inheriting
class) is called sub class. The sub class (inheriting class) inherits all the instance
variables and methods of super class (inherited class) except the private members and
additional instance variables and methods can also be declared.
Single inheritance is the process of creating a sub class from a single super class. It is
also called as simple inheritance. Java does not support multiple inheritance. But we
can implement multiple inheritance through interface.
class Superclass
- ----
- ---
- - -
47
type superclassmethod ( )
// body
- --
- ----
- ---
type subclassmethod ( )
{ body
- --
import java.io.*;
class Base {
double l;
Base(doubl e l1) {
48
l=l1;
void area( ) {
double a=l* l;
double b;
super(l1);
b=b1;
void area( )
double a=l*b;
class Minheritance1 {
49
Rect r=new Rect(5.0,6.0);
b.area( );
r.area( );
In java super keyword is used by the sub class to refer its super class. It is mainly used
in Inheritance and method overriding. This super keyword has three uses.
The keyword super can be used to call the super class constructor. The general
form is given by
super( argument-list);
Example:
(i) super(10,2.4);
(ii) super(a,b);
The keyword super can be used to access the super class instance variable. It can
access the super class instance variable only when it is declared as public or protected.
Private instance variable of the super class cannot be accessed by super. The general
form is given by
50
super.variable=value;
super.variable;
Example:
Let x and y be the protected integer variables declared in the super class, then it can be
accessed as follows using super.
super.x=15;
super.y=56;
System.out.println(“X=”+super.x);
System.out.println(“Y=”+super.y);
The keyword super can be used to access the super class methods. It can able to
access the super class public and protected methods. Private methods of the super
class cannot be accessed by super. The general form is given by
super.super_class_method( arguments-list );
Example:
super.output( );
super.process( );
In the above example the methods output( ) and process( ) must be protected or public
methods, declared in the super class.
import java.io.*;
class Demo {
51
int x,y;
x=x1;
y=y1;
void display( ) {
System.out.println("Super x : "+x);
System.out.println("Super y : "+y);
int z;
z=z1;
void display( ) {
System.out.println("sub z: "+z);
52
class Moverriding1 {
d1.display( );
In multilevel hierarchy the user can able to create sub classes in different levels. In
multilevel hierarchy the super class create a sub class, and then this sub class becomes
a super class and creates another sub class. For example, consider three classes
namely Demo, Demo1 and Demo2. Here Demo is the super class and Demo1 is the
sub class of Demo, again Demo1 become a super class and it creates another sub
class Demo2. This process will for many levels. Basically multilevel hierarchy is single
inheritance in different levels.
class Superclass
- ----
- ---
type superclassmethod ( )
{ body
- --
53
}
- ----
- ---
type subclass1_method ( )
{ body
- --
- ----
- ---
type subclass2_method ( )
{ body
- --
54
Example : Java program to demonstrate multilevel inheritance
import java.io.*;
class Demo {
int x;
Demo(int x1) {
x=x1;
void display( ) {
System.out.println("Demo x : "+x);
int y;
y=y1;
void display( ) {
System.out.println("Demo1 y: "+y);
} }
55
class Demo2 extends Demo1 {
int z,s;
z=z1;
void display( ) {
s=x+y+z;
System.out.println("Demo2 Z: "+z);
System.out.println("Sum = "+s);
class Mmullvlinh {
d.display( );
Explanation: In the above program Demo is the super class and Demo1 is the sub class
of Demo. Demo1 inherits all of the traits of Demo and also it adds its own member y. In
the second level Demo1 is the super class for Demo2. It inherits all the traits of Demo1
56
and adds its own members z and s. Similarly we can construct hierarchies that contains
many levels of inheritance.
In Inheritance, when a method in a sub class has the same name, same number of
arguments, same type of arguments, arguments in the same order as a method in its
super class, then the sub class method override the super class method. When the sub
class method is called, it will always refer to the sub class method and will not refer the
super class method. This mechanism in java is called method overriding. The super
class method can be called using the keyword super .
import java.io.*;
class Demo {
int x,y;
x=x1;
y=y1;
void display( ) {
System.out.println("Super x : "+x);
System.out.println("Super y : "+y);
57
class Demo1 extends Demo {
int z;
z=z1;
void display( ) {
System.out.println("sub z: "+z);
class Moverriding1 {
d1.display( );
Explanation: In the above example Demo is the super class and Demo1 is the sub
class. The classes Demo and Demo1 have the same method void output( ) with the
same signature. Whenever you call the sub class method, it always call the sub class
method and it won‟t call the super class output( ). This is because the sub class method
overrides the super class method.
58
2.15 Dynamic Method Dispatch:
Method overriding forms the basis for Dynamic method dispatch. When a overridden
method is called through a super class reference, java determines which method has to
be executed at the time the call occurs. This is based on which sub class object is
assigned to the super class reference. This mechanism is called dynamic method
dispatch. In java, run-time polymorphism can be implemented using Dynamic method
dispatch.
import java.io.*;
class Demo {
int x;
Demo(int x1 ) {
x=x1;
void display( ) {
System.out.println("Demo x : "+x);
} }
int y;
y=y1;
59
}
void display( ) {
System.out.println("Demo1 y: "+y);
int z,s;
z=z1;
void display( ) {
s=x+y+z;
System.out.println("Demo2 Z: "+z);
System.out.println("Sum = "+s);
class Dynmtddispch {
60
Demo2 d2= new Demo2(100,200,300);
Demo dd;
dd=d;
dd.display( );
dd=d1;
dd.display( );
dd=d2;
dd.display( );
Explanation: In the above example Demo is the super class, Demo1 is the sub class of
Demo and Demo2 is the sub class of Demo1. In the main method create the objects d,
d1 and d2 for the classes Demo, Demo1 and Demo2 respectively. dd is the reference
variable of the super class. Assign the object to the reference variable dd and call the
method display( ). The call to the display ( ) will be resolved during run-time.
61
Unit III
3.1 Packages:
Packages are containers for classes and interfaces. It is a collection of related classes
and interfaces. The package restricts the visibility for the classes inside a package and
naming mechanism. The programmer can define classes inside a package that are not
accessible by the code outside the package or that may be accessible by the code
outside the class.
The keyword package is used to create a package. The package statement must be the
first statement in the source file. The classes that are declared within that file will belong
to the specified package. The keyword package defines a name space in which classes
are stored. In the absence of package keyword, the classes are stored in a default
package. The general form of package is given blow.
package package-name;
Example:
package demopack1;
In the general form package-name is the name of the package. In the above example
demopack1 is the package name. The package demopack1 must be stored in the
directory called demopack1.
Before adding a class to a package, create a package. The class to be added to the
package must follow the package definition.
62
Example:
package student;
class Stu
String name;
int roll-num;
//Body
In the above example the package student is stored in the directory and the class Stu is
in the package student.
package demopack;
class Student {
String name;
int rn;
name=name1;
rn=rn1;
void output( ) {
System.out.println("Name :"+name);
63
System.out.println("RNum :"+rn);
class Mstudent {
s.output( );
Explanation:
In the above example demopack is a package. This package must be stored in the
directory called demopack. The program file name and the class name should be same.
In this example the file name is Mstudent.java. The package demopack contains two
classes namely Student and Mstudent. Compile the program so that the class file must
be in the directory demopack. Now go one level back in the directory. Run the program
with the package qualifier.
C:Javaprg\Demopack>javac Demopack.java
C:>Javaprg>java Demopack.Mstudent
Packages are the containers for classes, interfaces and other sub-packages. Classes
are the containers for data and methods. Java supports the following access specifiers
namely private, protected, public and default (ie no access specifier). The visibility of
packages, sub-packages, classes and sub-classes are given in the following table.
64
Private Protected Public Default
Same package
No Yes Yes Yes
sub class
Same package
No Yes Yes Yes
Non sub class
Different
package sub No Yes Yes No
class
Different
package non No No Yes No
sub class
The import statement is used to bring the classes and interfaces in a package to use it
in a program. The import statement occurs immediately following the package
statement and before any class definitions. The packages, sub-packages , classes and
methods are separated by the dot( .) operator. The general form of the import statement
is given below.
import package1.sub-package2.class.*;
Example:
import demopack.demosub.Student.*;
65
package demopack;
class Student {
String name;
int rn;
name=name1;
rn=rn1;
void output( ) {
System.out.println("Name :"+name);
System.out.println("RNum :"+rn);
} }
import java.io.*;
import demopack.Student;
class Packdemo {
s1.output( );
66
Explanation:
The above example shows a program that imports the class Student from the package
demopack. The source file should be saved as Packdemo.java and then compiled. The
source file (Packdemo.java) and its class file (Packdemo.class) must be saved in the
directory ( javaprg) and demopack should be the sub directory of javaprg. Now run the
program Packdemo.java.
3.4 Interfaces:
An interface is similar to classes but it can declare only abstract methods and final
variables. This means that interfaces do not specify any code to implement these
methods and constants. An interface has two parts namely defining an interface and
implementing an interface. In java Multiple Inheritance can be implemented using
Interfaces.
An interface is defined like a class but it contains only final variables and abstract
methods. The general form of an interface is as follows.
interface Interface-name
final variable1=value;
____
____
interface Areaiface {
67
final double pi=3.14;
Explanation:
In the above example Areaiface is an interface. It contains two members namely a final
constant pi and an abstract method Carea( double ) with double type argument.
Once an interface is defined, many classes can implement the interface. The
implements clause can be used to implement an interface. Interfaces are used as super
classes whose members are used in sub classes. The general form of implementing an
interface is given below.
double r,ac;
r=r1;
ac=pi*r*r;
System.out.println("Radius="+r);
68
System.out.println("Areaof Circle="+ac);
class Macircle {
a1.carea(10.0);
Explanation:
In this program the class Acircle implements the interface Areaiface. The interface
consists of one final constant pi and an abstract method carea(double). The abstract
method carea( double) is defined inside the class Acircle. The class Macircle contains
the main( ) method through which the carea( ) is called to calculate the area of a circle.
EXCEPTION HANDLING
The abnormal condition that arises in a program during run time is called exception. In
other words the run time error is called exception. Java uses the five keywords try,
catch, throw, throws and finally to handle the exception.
try block: The set of codes that you want to monitor for exceptions are enclosed within
try block.
catch clause: Used to handle the exception thrown by the try block.
69
throw: Used to throw the exception manually.
finally block: The code that must be executed before a method returns is enclosed in the
finally block.
try {
catch(Exceptio-type1 exobj1 )
catch(Exceptio-type2 exobj2 )
_ _ _
finally
70
Example: Program to demonstrate the exception handling (Divide by zero).
import java.io.*;
class Mexcep1
int x,y,z;
try{
x=20;
y=20;
catch(ArithmeticException e){
Finally {
System.out.println("After Catch");
71
Explanation: In the above program divide by zero exception occurred. This exception is
handled by the catch clause.
In java all exception types are subclasses of the built-in-class Throwable. The two
subclasses of Throwable are Exception and Error. Some of the built-in exceptions listed
below.
Exception Meaning
The default exception handling mechanism by the java run-time system is useful for
debugging. The run time error can be handled using try – catch block. A try block and a
catch clause form a unit. The code that you want to monitor is enclosed within the try
block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
import java.io.*;
class Mexcepbnd {
72
try{
int i,s;
for(i=0;i<5;i++)
a[i]=i;
for(i=0;i<5;i++)
System.out.println(a[i]);
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("After Catch");
Explanation: In the above program the size of the array a is 5, ranging from 0 to 4. But it
tries to assign 15 to a[20]. The array indexes 20 exceeds the array size so an exception
is occurred and the catch clause catch the exception and handle it. The message is
displayed on the screen.
73
MULTITHREADED PROGRAMMING
A thread is similar to a program that has a single flow of control. Java provides built-in
support for multithreading. In java a multithreaded programs contains two or more parts
that can be executed in parallel. One part of such program is called Thread. In most of
the computers, we have only one processor. Therefore in reality the processor is doing
only one job at a time. But the processor switches between the processes. The java
model helps the programmer to write efficient programs so that the cpu utilization can
be increased and the cpu idle time is reduced.
The advantage of multithreading is that the main loop /mechanism is avoided. One
thread can stopped or suspended without affecting other threads. For example, one
thread may in sleep and the other thread is in execution. The sleeping thread resumes
the operation when it got the chance enters into the cpu for execution.
In java thread exists in several states. They are new, running, runnable, blocked and
dead.
New state – Thread object is created and is not yet scheduled for running.
Runnable state – Thread is ready for execution and and is waiting for cpu time.
Blocked state – Thread is prevented from entering into the runnable state and the
running state.
Dead state – Thread completed its execution and quits from the cpu.
Thread priority is an integer number assigned to the threads. It shows the relative
priority of one thread over another thread. Thread priority value is between 1 and 10.
74
MIN_PRIORITY=1 and MAX_PRIORITY=10. Thread‟s priority decides when the
running thread quits the cpu. The setPriority( ) method can be used to set the Thread
priority. The general form is given below.
Example: Demothread.setPriority(4);
The program must extend the Thread class or implement the runnable interface to
create a new thread. The following are the some of the methods defined by the Thread
class to manage the thread.
The main thread is the thread that starts up, when a java program begins running. The
main thread is created automatically when your program is started. It can be controlled
through a Thread object and the Thread class methods. The purposes of main thread
are
75
Main thread is the last thread to finish execution because it performs various
shutdown actions.
There are two different ways to create a thread in java. They are
The simplest method to create a thread is to create a class that implements the
Runnable interface. The class need to use the run( ) method, to implement the
Runnable interface. The body of the run( ) contains the code for the new thread. The
start( ) method executes a call to run( ). The general form of the methods used to create
the Thread is given below.
void start( )
Thread constructor is
import java.awt.*;
Thread t;
Demothread( ) {
t=new Thread(this,"DEMOTHREAD");
System.out.println("CHILD "+t);
76
t.start( );
try {
for(int i=10;i<15;i++)
Thread.sleep(500);
} catch(InterruptedException e) {
class Mthreadr1 {
try{
for(int i=25;i>20;i--)
System.out.println("MT "+i);
77
Thread.sleep(500);
}catch(InterruptedException e) {
System.out.println("MT exited");
The second method to create a thread is to create a class that extends Thread and then
it creates the thread object. The extending class must override the run( ) method, which
is the entry point for the new thread. It must also call start( ) to begin execution of the
new thread.
import java.awt.*;
import java.io.*;
Demothread( ) {
super("DEMO THREAD");
System.out.println("CT.."+this);
start( );
78
public void run( ) {
try
for(int i=20;i<25;i++)
System.out.println("CT "+i);
Thread.sleep(250);
} catch(InterruptedException e) {
System.out.println("ct exited");
class Mthreadt1 {
try
for(int i=300;i<305;i++)
79
System.out.println("MT.. "+i);
Thread.sleep(500);
}catch(InterruptedException e) {
System.out.println("MT exited");
80
Unit IV
4.1 Applet:
The Applet class is contained in the java.applet package. Applet contains several
methods to control the execution of the Applet. There are three interfaces defined by the
package java.applet namely AppletContext, AudioClip, and AppletStub.All applets are
sub classes of Applet. All applets must import java.applet. Applets must also import
java.awt. AWT stands for Abstract Window Toolkit. Since all applets run in a window,
include awt classes.
Example:
</Applet>
*/
The above example shows an Applet with height of 100 pixels and width of 300 pixels.
Demoapplet is the file of the applet program.
The Applet class defines the methods to manage the applet. Some of the Applet class
methods are given below.
(i) void destroy( ) – Called by the browser just before an applet is terminated.
81
(ii) String getAppletInfo( ) -- Returns a string that describes applet.
(iv) boolean isActive( ) – Returns true if the applet is started otherwise false.
(v) void play(URL urladdress) – To play the audio clip in the specified location.
(vi) void paly( URL urladdress, String filename) – To play the audio clip in the
specified address and name.
(vii) void resize( Dimension dim) – To change the size of an applet as per the new
dimension.
(viii) void resize(int width, int height) – Used to change the size of an applet.
(ix) void start( ) – Called by the browser when an applet should startexecution.
Java supports two types of programs namely Application program and Applet program.
In the previous chapters we discussed about application programs. An Applet is a
window-based program. Its architecture is different from he application programs. The
concepts about applet are given below.
The user initiates interaction with an applet. For an application program the
input can be fed through readLine( ) method. This will not work in applet
programming. Events are generated when the user select a Checkbox, press
the Button, pressed a key ......
Applets override a set of methods that provides the basic mechanism by which the
browser or appletviewer interfaces to the applet and controls its execution. The four
82
basic methods needed for an applet are init( ), start( ), stop( ) and destroy( ). The
paint( ) is defined by the AWTComponent class. The following program shows the
Applet skeleton.
Applet inherits a set of default behaviours from the Applet class. As a result when applet
is loaded, AWT calls the following methods in the following sequence.
init( ) This method is the first method to be called. It is used to initialize the
variables. This method is called only once during the runtime of your applet.
start( ) This method is called after init( ). It is also called to restart the applet.
The start( ) is called each time an applet‟s HTML document is displayed on the
screen.
paint( ) This method is called every time to redraw the output. The paint( ) has
one parameter of type graphics.
stop( ) This method is called when a browser leaves the HTML document
containing the applet.
Applets are displayed in a window and they use the AWT to perform input and output.
Applet use the drawstring( ) of the Graphics class to output a String to an Applet. This
method is called from either paint( ) or update( ). The general form is given below.
83
Example:
The above segment display the message in the applet at row number 100 and column
number 100. The upper left corner is location 0,0.
The following methods are sued to change or set the background and foreground
colours in an applet.
In the above general forms color1 and color2 shows the new colors.
Example:
setBackground(Color.red);
setForeground(Color.cyan);
In the above example the background color is red and the foreground color is cyan.
Generally these methods are used in the init( ) method.
It is also possible to get the foreground and background colors with the following
methods. They returns the Color object.
Color getBackground( );
Color getForeground( );
84
Example: Program to demonstrate the Applet display methods.
import java.io.*;
import java.awt.*;
import java.applet.*;
</applet> */
int x,y;
setBackground(Color.cyan);
setForeground(Color.red);
x=10;
y=100;
msg+="inside start";
g.drawString(msg,x,y);
} }
85
4.5 Requesting Repainting:
An applet uses paint( ) and update( ) methods to write information in a window. These
methods are called by AWT. Applet uses the method repaint( ) to update the information
displayed on a window. A paint( ) method within a loop will not update the information
displayed on a window. This repaint( ) method is defined by the AWT. The repaint9 )
method is available in four different forms.
void repaint( int left, int top, int width, int height) This method is used to
repaint the specified region/area.
void repaint(long delay) This method is used to repaint the window with a
delay of mili seconds.
void repaint(long delay, int x, int y, int width, int height) This method is used to
repaint the specified region/area after delay milli seconds.
The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer. The general form of the APPLET tag is given below. In the general form
the square bracketed items are optional.
<APPLET
[CODEBASE = codebaseURL]
CODE = applet-class-file
[ALT = Alternate-text]
[NAME = Applet-instance-name]
WIDTH = pixels
HEIGHT = pixels
86
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
........
......
</APPLET>
CODEBASE This is an optional attribute that specifies the base URL directory
where the applet code resides.
CODE CODE is a required attribute that gives the name of the compiled
.class file
ALT The ALT is an optional attribute used to specify a short text message that
should be displayed where the applet would go.
NAME This is an optional attribute used to specify a name for the applet
instance.
WIDTH WIDTH attribute is used to specify the width of the applet in pixels.
HEIGHT HEIGHT attribute is used to specify the height of the applet in pixels.
87
HSPACE This is an optional attribute used to specify the space in pixels, on
each side of the applet.
PARAM NAME and VALUE The PARAM tag allows you to specify applet
specific arguments in an HTML page. Applets access their attributes with the
getParameter( ) method.
EVENT HANDLING
Events are supported by the java.awt.event package. The most commonly handled
events are those generated by the mouse, the keyboard and other awt controls Button,
Checkbox, Menubar .... .The modern approach is the way that events should be
handled by all new programs.
Delegation event model defines standard and consistent mechanisms to generate and
process events. In this model a source generates an event and sends it to one or more
listeners. The listener process the event. In the delegation event model, event
notifications are sending to the registered listeners.
An event is an object that describes a state change in a source. For example pressing a
key, click a Checkbox, Click a Button or selecting an item using mouse or keyboard are
the some of the methods to generate events.
A source is an object that generates an event. This occurs when the internal state of
that object changes in some way. The source may also generate more than one type of
event. Each type of event has its own registration method. The general form is given
below.
88
Example:
B1.addActionListener(this);
C1.addItemListener(this);
In the above general form the ListenerType may be any one type of listener. In the
example the method that registers a Button event is addActionListener( ), the method
that registers a Checkbox is addItemListener( ).
Example:
B1.removeActionListener(this);
C1,removeItemListener(this);
An event listener is an object that is notified when an event occurs. It has to do two
steps to receive notifications.
It must register with one or more sources about the type of events.
The methods that receive and process events are defined in a set of interfaces are
found in java.awt.event.
The EventObject is the superclass of all events. The AWTEvent is a superclass of all
AWT events that are Handled by the delegation event model. The package
java.awt.event defines many types of events that are generated by various user
interface elements. Some of the event classes are given below.
89
ActionEvent Generated when a button is pressed, menu item is selected...
Where ob is the reference to the object that generated event, type is the type of event
generated and cmd is the command string.
90
Where src is the component that generated the event, type is the type of event
generated, ob is the specific item that generated the ItemEvent and the current state of
that item is is represented by state.
MouseEvent(Component evsrc, int evtype, long evwhen, int evmodifier, int x int
y, int click, boolean popup);
Where evsrc is the event source, evtype is the type of the event generated, evwhen
specifies the when that event took pl;ace(system time), evmodifier represents which
91
modifier is pressed, x and y represents the co-od position of the mouse, click represents
the clicks and popup is a flag indicating whether the popup appeared on this platform or
not appeared.
int getX( )
int getY( )
Point getPoint( )
int getButton( )
int getClickCount( )
void translatePoint( )
boolena isPopupTrigger( )
92
4.11 Event Listener Interfaces:
Some of the event listener interfaces and its methods are given below.
(iii) The KeyListener Interface: This interface called any one of the following three
methods when a key event occurs.
(iv) The MouseListener Interface: This interface called any one of the following five
methods when a mouse is pressed, released or quit.
(v) The MouseMotionListener Interface: This interface defines the following two
methods. The mouseDragged( ) method is called whenever the mouse id
93
dragged. The mouseMoved( ) method is called whenever the mouse is
moved.
(vi) The TextListener Interface: This interface defines the textChanged( ) method that
is invoked when achange occurs in the TextField or textArea.
The mouse events are handled by the interfaces MouseListener and the
MouseMotionListener. The MouseListener interface methods and the
MouseMotionListener interface methods are used to handle the events. The mouse
events are generated when we press or release the mouse, when the mouse is dragged
or moved, when the mouse entered or exited and when the mouse is clicked.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
94
String msg;
int x=0;
int y=0;
addMouseListener(this);
x=200;
y=50;
msg="Mouse Clicked";
repaint( );
x=200;
y=50;
msg="Mouse Entered";
repaint( );
x=200;
95
y=50;
msg="Mouse Exited";
repaint( );
x=e.getX( );
y=e.getY( );
msg="Mouse Pressed";
repaint( );
x=e.getX( );
y=e.getY( );
msg="Mouse Released";
repaint( );
g.drawString(msg,x,y);
96
4.13 Handling Keyboard Events:
The Keyboard events are handled by the interface KeyListener. The KeyListener
interface methods are used to handle the events. Key events are generated when the
key is pressed, released or typed.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
String msg;
int x=50;
int y=100;
addKeyListener(this);
requestFocus( );
showStatus("Key Pressed");
repaint( );
97
public void keyReleased(KeyEvent e) {
repaint( );
msg+=e.getKeyChar( );
repaint( );
g.drawString(msg,x,y);
98
Unit V
GRAPHICS
The graphics class defines several drawing methods. All graphics are drawn relative to
window. The origin of each window is top left corner and is 0,0. The co-ordinates are
specified in pixels. The co-ordinate position (20, 50) points the column number 20 and
row number 50. The graphics context is encapsulated by the following two methods.
The drawLine( ) method can be used to draw lines. It displays the line in the current
drawing color that begins at x1, y1 and ends at x2, y2. The general form of the
drawLine( ) and an example is given below.
Example:
_ _ _ _ _ _ _ _
g.drawLine(30,20, 200,300);
_ _ _ _ _ _
The methods used to draw a rectangle and fill the rectangle are given below.
99
void drawRect(int top, int left, int length, int breadth);
Here top and left indicates the top-left corner of the rectangle, the length represents the
length of a rectangle and breadth represents the breadth of a rectangle. The fillRect( )
method is used to fill the rectangle.
Example:
_ _ _ _ _ _ _ _
g.drawRect(100,100, 200,300);
g.fillRect(100,100, 200,300);
_ _ _ _ _ _
The drawOval( ) method can be used to draw ellipses and circles. In the given below
method if the major and minor are different then an ellipse is drawn, if the both the
major and minor are same then a circle is drawn. The fillOval( ) method can be used to
fill the ellipse and circles.
Example:
_ _ _ _ _ _ _ _
100
g.fillOval(100,100, 200,300); //Ellipse
_ _ _ _ _ _
import java.awt.*;
import java.applet.*;
</applet> */
g.setColor(Color.green);
g.drawArc(150,40,20,60,180,360);
g.drawArc(150,40,20,60,90,180);
g.fillArc(150,40,20,60,0,360);
g.setColor(Color.blue);
g.drawArc(100,75,120,25,0,-180);
g.setColor(Color.red);
101
g.drawRect(100,100,120,50);
g.fillRect(100,100,120,50);
In java color is encapsulated by Color class. The AWT color system allows you specify
any color you want. Color class defines some of the standard colors as color constant.
The user can create any color using the constructors given below.
In the first constructor red, green, blue colors are represented as integer values. The
value of the integer value must be between 0 and 255. The second constructor is used
if you want to specify the color values in floating point number. In this case the value
ranging between 0 and 1.0.
Example:
In the above example „b‟ is a Blue color, „r‟ is a Red color, „g‟ is a Green color and „c‟ is
a new color with the combination of Red, Green and Blue.
102
int getGreen( ) Returns the Green component of the Color.
Example:
g.setColor(c2);
import java.io.*;
import java.awt.*;
import java.applet.*;
String msgn=f.getName();
int r=c.getRed();
103
int b=c.getBlue();
int g=c.getGreen();
String msg1=Integer.toString(r);
String msg2=Integer.toString(b);
g.setFont(f);
g.setColor(c);
g.drawString("Welcome",50,50);
g.drawString(msg1,100,100);
g.drawString(msg2,100,150);
g.setColor(Color.green);
g.drawOval(100,100,50,30);
The Font object can be constructed using the constructor. The following
attributes/variables are defined by the Font class. The general form of the Font
constructor is given below.
104
Constructor:
Example:
Here f1 is the Font object with font name “Arial”, font style BOLD and font size 14
points.
Methods:
Font f2;
import java.io.*;
import java.awt.*;
import java.applet.*;
105
String msgn=f.getName();
String msg1=f.toString();
g.setFont(f);
g.setColor(c);
g.drawString("Welcome",50,50);
g.setColor(c1);
g.drawString(msg1,100,100);
g.drawOval(100,100,50,30);
AWT CONTROLS
The Abstract window toolkit (AWT) controls are the components that allow the user to
interact with your application in several ways. Some of the commonly used AWT
controls are Labels, Push Buttons, Check Box, TextArea and TextField. The layout
manager automatically arrange the components in an Applet or a Window. The add()
can be used to add the control to a window. The remove( ) method is used to remove
the control from the window.
106
Example:
5.5 Label:
Constructors:
Label(String name, int pos) Creates a label object along with its name and pos
shows the alignment of the label. The pos can take any one of these three
values ie Label.LEFT, Label.RIGHT, Label.CENTER.
Methods:
void setText(String name); // Used to change the existing text or to set text for a
label.
void setAlignment(int pos); // used to set alignment of the name within label .
Example:
107
String name = l1.getText( );//Returns the string DDCE to name.
5.6 Button:
A Button is a component that contains a label. Button is the most commonly used
control. It generates an event when it is pressed. The constructors and methods of the
Button class are given below.
Constructors:
Methods:
Handling Buttons:
When a button is pressed an event is generated. The registered listener receives the
event notification. The actionPerformed( ) method of the ActionListener interface is
called when an event occurs. ActionEvent object is passed as argument.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
108
public class Demobutton1 extends Applet implements ActionListener {
Button b1,b2;
String msg;
b1=new Button("ADD");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
String s;
s=ae.getActionCommand( );
if(s.equals("ADD"))
msg="ADDITION";
else if(s.equals("SUB"))
msg="SUBTRACTION";
else msg="ERROR";
repaint( );
109
public void paint(Graphics g) {
g.drawString(msg,50,100);
5.7 Checkbox:
Constructors:
Checkbox(String name, boolean on);// Creates a check box with the name and is
set to ON state
Methods:
void setState( Boolean on);// Used to set the state of a Checkbox control.
void setLabel( String label);// Used to set the label for the Checkbox
110
Handling Check Boxes:
An item event is generated when a check box is selected or deselected. The registered
listener receives the event notification. The itemStateChanged( ) method of the
ItemListener interface is called when an event occurs. ItemEvent object is passed as
argument.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
Checkbox cb1,cb2;
String msg;
cb1=new Checkbox("CBOX1");
add(cb1);
add(cb2);
cb1.addItemListener(this);
cb2.addItemListener(this);
111
public void itemStateChanged(ItemEvent ie) {
if(ie.getSource()==cb1)
msg="CHECKBOX1";
else if(ie.getSource()==cb2)
msg="CHECKBOX2";
else msg="ERROR";
repaint();
g.drawString(msg,150,100);
5.8 CheckboxGroup:
CheckboxGroup is an AWT control with more than one check box. In a check box group
at a particular time only one check box is selected and all other check boxes are in
deselected state. The check boxes in the check box group are also called radio buttons.
The constructors and methods of CheckboxGroup are given below.
Constructor:
Methods:
112
Checkbox getSelectedCheckbox( );// Returns the selected Checkbox
Example:
Checkbox cb3;
add(cb1);
add(cb2);
cb3=cbg1.getSelectedCheckbox( );
cbg1.setSelectedCheckbox(cb2);
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
CheckboxGroup cbg;
113
Checkbox cb1,cb2;
String msg;
Color c1,c2;
Font f;
cb1=new Checkbox("CBOX1",false,cbg);
add(cb1);
add(cb2);
cb1.addItemListener(this);
cb2.addItemListener(this);
c1=new Color(255,0,0);
c2=new Color(0,255,0);
f=new Font("Arial",Font.BOLD,20);
String s;
if(ie.getItemSelectable()==cb1)
msg="CHECKBOX1";
else if(ie.getItemSelectable()==cb2)
114
msg="CHECKBOX2";
else msg="ERROR";
repaint( );
if(msg=="CHECKBOX1")
setBackground(c1);
else
setBackground(c2);
g.setFont(f);
g.drawString(msg,50,100);
5.9 TextField:
A single line text entry in java is implemented through TextField class. It is also called
edit control. TextField is a sub class of TextComponent. The constructors and methods
of TextField class are given below.
Constructor:
115
Methods:
Example:
String name =tf.getText( );// Returns the text M S University to the string name.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
Checkbox cb1,cb2;
TextField tf;
String msg;
116
cb1=new Checkbox("CBOX1");
add(cb1);
add(cb2);
tf=new TextField(20);
add(tf);
cb1.addItemListener(this);
cb2.addItemListener(this);
repaint( );
String s;
if(ie.getItemSelectable()==cb1)
msg="CHECKBOX1";
else if(ie.getItemSelectable()==cb2)
msg="CHECKBOX2";
else msg="ERROR";
tf.setText(msg);
117
5.10.TextArea:
Constructors:
TextArea(String name, int lines, int characters);// Creates a TextArea with a initial
text name and specified number of lines and each line is of characters width.
Methods:
void append( String msg);//Used to append the string specified in the msg.
void insert(String msg, int location);//Used to insert the string msg in the specified
location.
void replaceRange(String msg, int start, int end);// Used to replace the existing
string with the new string msg in the specified starting index start and the ending
index end.
Example:
118
Example: Java program to handle the TextArea.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
Checkbox cb1,cb2;
TextArea ta;
String msg1,msg2;
cb1=new Checkbox("CBOX1");
add(cb1);
add(cb2);
ta=new TextArea(10,20);
add(ta);
add(l1);
119
cb1.addItemListener(this);
cb2.addItemListener(this);
String s;
ta.insert(msg1,3);
ta.setText("CB1 Disabled");
ta.insert(msg2,7);
ta.setText("Cb2 Disabled");
120
5.11 Layout Managers:
In java a layout manager automatically arranges the controls used in a program. Each
Container object has a layout associated with it. A layout manager is an instance of any
class that implements the LayoutManager interface. The setLayout() method can be
used to set layout. Java supports the following layout managers.
FlowLayout
BorderLayout
GridLayout
CardLayout
5.11.1 FlowLayout:
FlowLayout is the default layout manager. FlowLayout implements a simple layout style.
In FlowLayout the controls are arranged from top-left corner left to right and top to
bottom. A small space is left between two components, above and below two
components. The constructors and methods of a FlowLayout manager are given below.
Constructors:
Methods:
121
Example:
122
MODEL QUESTION
Part – A
Answer ALL Questions. (10 X 2=20)
1. What are the basic concepts are of object oriented programming?
2. What is a Constructor”
3. What is the difference between static and non-static member in java?
4. What are the uses of the keyword super?
5. What is the purpose of package in java?
6. What is an Exception?
7. What are the Applet display methods?.
8. What is a Delegation Event model?
9. Write the constructors of Label.
10. Write any Four AWT controls.
Part – B
11. (a) Explain the Primary Data types in java with example.
(OR)
13. (a) How will you create a Thread? Explain with an example.
(OR)
123
14. (a) Explain the Applet architecture.
(OR)
15. (a) Explain any Five Graphics class methods with example.
(OR)
Part – C
124